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/. */
6
7 #include "mozilla/BaseProfileJSONWriter.h"
8
9 namespace mozilla::baseprofiler {
10
UniqueJSONStrings(JSONWriter::CollectionStyle aStyle)11 UniqueJSONStrings::UniqueJSONStrings(JSONWriter::CollectionStyle aStyle) {
12 mStringTableWriter.StartBareList(aStyle);
13 }
14
UniqueJSONStrings(const UniqueJSONStrings & aOther,ProgressLogger aProgressLogger,JSONWriter::CollectionStyle aStyle)15 UniqueJSONStrings::UniqueJSONStrings(const UniqueJSONStrings& aOther,
16 ProgressLogger aProgressLogger,
17 JSONWriter::CollectionStyle aStyle) {
18 using namespace mozilla::literals::ProportionValue_literals; // For `10_pc`.
19
20 mStringTableWriter.StartBareList(aStyle);
21 uint32_t count = aOther.mStringHashToIndexMap.count();
22 if (count != 0) {
23 MOZ_ALWAYS_TRUE(mStringHashToIndexMap.reserve(count));
24 auto iter = aOther.mStringHashToIndexMap.iter();
25 for (auto&& [unusedIndex, progressLogger] :
26 aProgressLogger.CreateLoopSubLoggersFromTo(
27 10_pc, 90_pc, count, "Copying unique strings...")) {
28 (void)unusedIndex;
29 if (iter.done()) {
30 break;
31 }
32 mStringHashToIndexMap.putNewInfallible(iter.get().key(),
33 iter.get().value());
34 iter.next();
35 }
36 aProgressLogger.SetLocalProgress(90_pc, "Copied unique strings");
37 mStringTableWriter.CopyAndSplice(
38 aOther.mStringTableWriter.ChunkedWriteFunc());
39 aProgressLogger.SetLocalProgress(100_pc, "Spliced unique strings");
40 }
41 }
42
43 UniqueJSONStrings::~UniqueJSONStrings() = default;
44
SpliceStringTableElements(SpliceableJSONWriter & aWriter)45 void UniqueJSONStrings::SpliceStringTableElements(
46 SpliceableJSONWriter& aWriter) {
47 aWriter.TakeAndSplice(mStringTableWriter.TakeChunkedWriteFunc());
48 }
49
GetOrAddIndex(const Span<const char> & aStr)50 uint32_t UniqueJSONStrings::GetOrAddIndex(const Span<const char>& aStr) {
51 uint32_t count = mStringHashToIndexMap.count();
52 HashNumber hash = HashString(aStr.data(), aStr.size());
53 auto entry = mStringHashToIndexMap.lookupForAdd(hash);
54 if (entry) {
55 MOZ_ASSERT(entry->value() < count);
56 return entry->value();
57 }
58
59 MOZ_RELEASE_ASSERT(mStringHashToIndexMap.add(entry, hash, count));
60 mStringTableWriter.StringElement(aStr);
61 return count;
62 }
63
64 } // namespace mozilla::baseprofiler
65