1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/BaseProfileJSONWriter.h"
9 namespace mozilla::baseprofiler
{
11 UniqueJSONStrings::UniqueJSONStrings(FailureLatch
& aFailureLatch
)
12 : mStringTableWriter(aFailureLatch
) {
13 mStringTableWriter
.StartBareList();
14 if (const char* failure
= mStringTableWriter
.GetFailure(); failure
) {
15 ClearAndSetFailure(failure
);
20 UniqueJSONStrings::UniqueJSONStrings(FailureLatch
& aFailureLatch
,
21 const UniqueJSONStrings
& aOther
,
22 ProgressLogger aProgressLogger
)
23 : mStringTableWriter(aFailureLatch
) {
24 using namespace mozilla::literals::ProportionValue_literals
; // For `10_pc`.
26 if (mStringTableWriter
.Failed()) {
30 if (const char* failure
= aOther
.GetFailure(); failure
) {
31 ClearAndSetFailure(failure
);
35 mStringTableWriter
.StartBareList();
36 uint32_t count
= aOther
.mStringHashToIndexMap
.count();
38 if (!mStringHashToIndexMap
.reserve(count
)) {
39 ClearAndSetFailure("Cannot reserve UniqueJSONStrings map storage");
42 auto iter
= aOther
.mStringHashToIndexMap
.iter();
43 for (auto&& [unusedIndex
, progressLogger
] :
44 aProgressLogger
.CreateLoopSubLoggersFromTo(
45 10_pc
, 90_pc
, count
, "Copying unique strings...")) {
50 mStringHashToIndexMap
.putNewInfallible(iter
.get().key(),
54 aProgressLogger
.SetLocalProgress(90_pc
, "Copied unique strings");
55 mStringTableWriter
.CopyAndSplice(
56 aOther
.mStringTableWriter
.ChunkedWriteFunc());
57 if (const char* failure
= aOther
.GetFailure(); failure
) {
58 ClearAndSetFailure(failure
);
60 aProgressLogger
.SetLocalProgress(100_pc
, "Spliced unique strings");
64 UniqueJSONStrings::~UniqueJSONStrings() = default;
66 void UniqueJSONStrings::SpliceStringTableElements(
67 SpliceableJSONWriter
& aWriter
) {
68 aWriter
.TakeAndSplice(mStringTableWriter
.TakeChunkedWriteFunc());
71 void UniqueJSONStrings::ClearAndSetFailure(std::string aFailure
) {
72 mStringTableWriter
.SetFailure(std::move(aFailure
));
73 mStringHashToIndexMap
.clear();
76 Maybe
<uint32_t> UniqueJSONStrings::GetOrAddIndex(const Span
<const char>& aStr
) {
81 uint32_t count
= mStringHashToIndexMap
.count();
82 HashNumber hash
= HashString(aStr
.data(), aStr
.size());
83 auto entry
= mStringHashToIndexMap
.lookupForAdd(hash
);
85 MOZ_ASSERT(entry
->value() < count
);
86 return Some(entry
->value());
89 if (!mStringHashToIndexMap
.add(entry
, hash
, count
)) {
90 ClearAndSetFailure("OOM in UniqueJSONStrings::GetOrAddIndex adding a map");
93 mStringTableWriter
.StringElement(aStr
);
94 if (const char* failure
= mStringTableWriter
.GetFailure(); failure
) {
95 ClearAndSetFailure(failure
);
101 } // namespace mozilla::baseprofiler