1 /* -*- Mode: C++; tab-width: 8; 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 #ifndef dom_ipc_StringTable_h
8 #define dom_ipc_StringTable_h
10 #include "mozilla/RangedPtr.h"
11 #include "nsTHashMap.h"
14 * This file contains helper classes for creating and accessing compact string
15 * tables, which can be used as the building blocks of shared memory databases.
16 * Each string table a de-duplicated set of strings which can be referenced
17 * using their character offsets within a data block and their lengths. The
18 * string tables, once created, cannot be modified, and are primarily useful in
19 * read-only shared memory or memory mapped files.
22 namespace mozilla::dom::ipc
{
25 * Contains the character offset and character length of an entry in a string
26 * table. This may be used for either 8-bit or 16-bit strings, and is required
27 * to retrieve an entry from a string table.
29 struct StringTableEntry
{
33 // Ignore mLength. It must be the same for any two strings with the same
35 uint32_t Hash() const { return mOffset
; }
37 bool operator==(const StringTableEntry
& aOther
) const {
38 return mOffset
== aOther
.mOffset
;
42 template <typename StringType
>
44 using ElemType
= typename
StringType::char_type
;
47 MOZ_IMPLICIT
StringTable(const RangedPtr
<uint8_t>& aBuffer
)
48 : mBuffer(aBuffer
.ReinterpretCast
<ElemType
>()) {
49 MOZ_ASSERT(uintptr_t(aBuffer
.get()) % alignof(ElemType
) == 0,
50 "Got misalinged buffer");
53 StringType
Get(const StringTableEntry
& aEntry
) const {
55 res
.AssignLiteral(GetBare(aEntry
), aEntry
.mLength
);
59 const ElemType
* GetBare(const StringTableEntry
& aEntry
) const {
60 return &mBuffer
[aEntry
.mOffset
];
64 RangedPtr
<ElemType
> mBuffer
;
67 template <typename KeyType
, typename StringType
>
68 class StringTableBuilder
{
70 using ElemType
= typename
StringType::char_type
;
72 StringTableEntry
Add(const StringType
& aKey
) {
73 return mEntries
.WithEntryHandle(aKey
,
74 [&](auto&& entry
) -> StringTableEntry
{
75 auto length
= uint32_t(aKey
.Length());
76 entry
.OrInsertWith([&]() {
77 Entry newEntry
{mSize
, aKey
};
83 return {entry
->mOffset
, length
};
87 void Write(const RangedPtr
<uint8_t>& aBuffer
) {
88 auto buffer
= aBuffer
.ReinterpretCast
<ElemType
>();
90 for (const auto& entry
: mEntries
.Values()) {
91 memcpy(&buffer
[entry
.mOffset
], entry
.mValue
.BeginReading(),
92 sizeof(ElemType
) * (entry
.mValue
.Length() + 1));
96 uint32_t Count() const { return mEntries
.Count(); }
98 uint32_t Size() const { return mSize
* sizeof(ElemType
); }
100 void Clear() { mEntries
.Clear(); }
102 static constexpr size_t Alignment() { return alignof(ElemType
); }
110 nsTHashMap
<KeyType
, Entry
> mEntries
;
114 } // namespace mozilla::dom::ipc