no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / xpcom / ds / PLDHashTable.h
blobf1d741791ca93f13bbebaf5c2f324499b152487d
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 // See the comment at the top of mfbt/HashTable.h for a comparison between
8 // PLDHashTable and mozilla::HashTable.
10 #ifndef PLDHashTable_h
11 #define PLDHashTable_h
13 #include <utility>
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Atomics.h"
17 #include "mozilla/HashFunctions.h"
18 #include "mozilla/Maybe.h"
19 #include "mozilla/MemoryReporting.h"
20 #include "mozilla/fallible.h"
21 #include "nscore.h"
23 using PLDHashNumber = mozilla::HashNumber;
24 static const uint32_t kPLDHashNumberBits = mozilla::kHashNumberBits;
26 #if defined(DEBUG) || defined(FUZZING)
27 # define MOZ_HASH_TABLE_CHECKS_ENABLED 1
28 #endif
30 class PLDHashTable;
31 struct PLDHashTableOps;
33 // Table entry header structure.
35 // In order to allow in-line allocation of key and value, we do not declare
36 // either here. Instead, the API uses const void *key as a formal parameter.
37 // The key need not be stored in the entry; it may be part of the value, but
38 // need not be stored at all.
40 // Callback types are defined below and grouped into the PLDHashTableOps
41 // structure, for single static initialization per hash table sub-type.
43 // Each hash table sub-type should make its entry type a subclass of
44 // PLDHashEntryHdr. PLDHashEntryHdr is merely a common superclass to present a
45 // uniform interface to PLDHashTable clients. The zero-sized base class
46 // optimization, employed by all of our supported C++ compilers, will ensure
47 // that this abstraction does not make objects needlessly larger.
48 struct PLDHashEntryHdr {
49 PLDHashEntryHdr() = default;
50 PLDHashEntryHdr(const PLDHashEntryHdr&) = delete;
51 PLDHashEntryHdr& operator=(const PLDHashEntryHdr&) = delete;
52 PLDHashEntryHdr(PLDHashEntryHdr&&) = default;
53 PLDHashEntryHdr& operator=(PLDHashEntryHdr&&) = default;
55 private:
56 friend class PLDHashTable;
59 #ifdef MOZ_HASH_TABLE_CHECKS_ENABLED
61 // This class does three kinds of checking:
63 // - that calls to one of |mOps| or to an enumerator do not cause re-entry into
64 // the table in an unsafe way;
66 // - that multiple threads do not access the table in an unsafe way;
68 // - that a table marked as immutable is not modified.
70 // "Safe" here means that multiple concurrent read operations are ok, but a
71 // write operation (i.e. one that can cause the entry storage to be reallocated
72 // or destroyed) cannot safely run concurrently with another read or write
73 // operation. This meaning of "safe" is only partial; for example, it does not
74 // cover whether a single entry in the table is modified by two separate
75 // threads. (Doing such checking would be much harder.)
77 // It does this with two variables:
79 // - mState, which embodies a tri-stage tagged union with the following
80 // variants:
81 // - Idle
82 // - Read(n), where 'n' is the number of concurrent read operations
83 // - Write
85 // - mIsWritable, which indicates if the table is mutable.
87 class Checker {
88 public:
89 constexpr Checker() : mState(kIdle), mIsWritable(true) {}
91 Checker& operator=(Checker&& aOther) {
92 // Atomic<> doesn't have an |operator=(Atomic<>&&)|.
93 mState = uint32_t(aOther.mState);
94 mIsWritable = bool(aOther.mIsWritable);
96 aOther.mState = kIdle;
97 // XXX Shouldn't we set mIsWritable to true here for consistency?
99 return *this;
102 static bool IsIdle(uint32_t aState) { return aState == kIdle; }
103 static bool IsRead(uint32_t aState) {
104 return kRead1 <= aState && aState <= kReadMax;
106 static bool IsRead1(uint32_t aState) { return aState == kRead1; }
107 static bool IsWrite(uint32_t aState) { return aState == kWrite; }
109 bool IsIdle() const { return mState == kIdle; }
111 bool IsWritable() const { return mIsWritable; }
113 void SetNonWritable() { mIsWritable = false; }
115 // NOTE: the obvious way to implement these functions is to (a) check
116 // |mState| is reasonable, and then (b) update |mState|. But the lack of
117 // atomicity in such an implementation can cause problems if we get unlucky
118 // thread interleaving between (a) and (b).
120 // So instead for |mState| we are careful to (a) first get |mState|'s old
121 // value and assign it a new value in single atomic operation, and only then
122 // (b) check the old value was reasonable. This ensures we don't have
123 // interleaving problems.
125 // For |mIsWritable| we don't need to be as careful because it can only in
126 // transition in one direction (from writable to non-writable).
128 void StartReadOp() {
129 uint32_t oldState = mState++; // this is an atomic increment
130 MOZ_RELEASE_ASSERT(IsIdle(oldState) || IsRead(oldState));
131 MOZ_RELEASE_ASSERT(oldState < kReadMax); // check for overflow
134 void EndReadOp() {
135 uint32_t oldState = mState--; // this is an atomic decrement
136 MOZ_RELEASE_ASSERT(IsRead(oldState));
139 void StartWriteOp() {
140 MOZ_RELEASE_ASSERT(IsWritable());
141 uint32_t oldState = mState.exchange(kWrite);
142 MOZ_RELEASE_ASSERT(IsIdle(oldState));
145 void EndWriteOp() {
146 // Check again that the table is writable, in case it was marked as
147 // non-writable just after the IsWritable() assertion in StartWriteOp()
148 // occurred.
149 MOZ_RELEASE_ASSERT(IsWritable());
150 uint32_t oldState = mState.exchange(kIdle);
151 MOZ_RELEASE_ASSERT(IsWrite(oldState));
154 void StartIteratorRemovalOp() {
155 // When doing removals at the end of iteration, we go from Read1 state to
156 // Write and then back.
157 MOZ_RELEASE_ASSERT(IsWritable());
158 uint32_t oldState = mState.exchange(kWrite);
159 MOZ_RELEASE_ASSERT(IsRead1(oldState));
162 void EndIteratorRemovalOp() {
163 // Check again that the table is writable, in case it was marked as
164 // non-writable just after the IsWritable() assertion in
165 // StartIteratorRemovalOp() occurred.
166 MOZ_RELEASE_ASSERT(IsWritable());
167 uint32_t oldState = mState.exchange(kRead1);
168 MOZ_RELEASE_ASSERT(IsWrite(oldState));
171 void StartDestructorOp() {
172 // A destructor op is like a write, but the table doesn't need to be
173 // writable.
174 uint32_t oldState = mState.exchange(kWrite);
175 MOZ_RELEASE_ASSERT(IsIdle(oldState));
178 void EndDestructorOp() {
179 uint32_t oldState = mState.exchange(kIdle);
180 MOZ_RELEASE_ASSERT(IsWrite(oldState));
183 private:
184 // Things of note about the representation of |mState|.
185 // - The values between kRead1..kReadMax represent valid Read(n) values.
186 // - kIdle and kRead1 are deliberately chosen so that incrementing the -
187 // former gives the latter.
188 // - 9999 concurrent readers should be enough for anybody.
189 static const uint32_t kIdle = 0;
190 static const uint32_t kRead1 = 1;
191 static const uint32_t kReadMax = 9999;
192 static const uint32_t kWrite = 10000;
194 mozilla::Atomic<uint32_t, mozilla::SequentiallyConsistent> mState;
195 mozilla::Atomic<bool, mozilla::SequentiallyConsistent> mIsWritable;
197 #endif
199 // A PLDHashTable may be allocated on the stack or within another structure or
200 // class. No entry storage is allocated until the first element is added. This
201 // means that empty hash tables are cheap, which is good because they are
202 // common.
204 // There used to be a long, math-heavy comment here about the merits of
205 // double hashing vs. chaining; it was removed in bug 1058335. In short, double
206 // hashing is more space-efficient unless the element size gets large (in which
207 // case you should keep using double hashing but switch to using pointer
208 // elements). Also, with double hashing, you can't safely hold an entry pointer
209 // and use it after an add or remove operation, unless you sample Generation()
210 // before adding or removing, and compare the sample after, dereferencing the
211 // entry pointer only if Generation() has not changed.
212 class PLDHashTable {
213 private:
214 // A slot represents a cached hash value and its associated entry stored in
215 // the hash table. The hash value and the entry are not stored contiguously.
216 struct Slot {
217 Slot(PLDHashEntryHdr* aEntry, PLDHashNumber* aKeyHash)
218 : mEntry(aEntry), mKeyHash(aKeyHash) {}
220 Slot(const Slot&) = default;
221 Slot(Slot&& aOther) = default;
223 Slot& operator=(Slot&& aOther) = default;
225 bool operator==(const Slot& aOther) const {
226 return mEntry == aOther.mEntry;
229 PLDHashNumber KeyHash() const { return *HashPtr(); }
230 void SetKeyHash(PLDHashNumber aHash) { *HashPtr() = aHash; }
232 PLDHashEntryHdr* ToEntry() const { return mEntry; }
234 bool IsFree() const { return KeyHash() == 0; }
235 bool IsRemoved() const { return KeyHash() == 1; }
236 bool IsLive() const { return IsLiveHash(KeyHash()); }
237 static bool IsLiveHash(uint32_t aHash) { return aHash >= 2; }
239 void MarkFree() { *HashPtr() = 0; }
240 void MarkRemoved() { *HashPtr() = 1; }
241 void MarkColliding() { *HashPtr() |= kCollisionFlag; }
243 void Next(uint32_t aEntrySize) {
244 char* p = reinterpret_cast<char*>(mEntry);
245 p += aEntrySize;
246 mEntry = reinterpret_cast<PLDHashEntryHdr*>(p);
247 mKeyHash++;
249 PLDHashNumber* HashPtr() const { return mKeyHash; }
251 private:
252 PLDHashEntryHdr* mEntry;
253 PLDHashNumber* mKeyHash;
256 // This class maintains the invariant that every time the entry store is
257 // changed, the generation is updated.
259 // The data layout separates the cached hashes of entries and the entries
260 // themselves to save space. We could store the entries thusly:
262 // +--------+--------+---------+
263 // | entry0 | entry1 | ... |
264 // +--------+--------+---------+
266 // where the entries themselves contain the cached hash stored as their
267 // first member. PLDHashTable did this for a long time, with entries looking
268 // like:
270 // class PLDHashEntryHdr
271 // {
272 // PLDHashNumber mKeyHash;
273 // };
275 // class MyEntry : public PLDHashEntryHdr
276 // {
277 // ...
278 // };
280 // The problem with this setup is that, depending on the layout of
281 // `MyEntry`, there may be platform ABI-mandated padding between `mKeyHash`
282 // and the first member of `MyEntry`. This ABI-mandated padding is wasted
283 // space, and was surprisingly common, e.g. when MyEntry contained a single
284 // pointer on 64-bit platforms.
286 // As previously alluded to, the current setup stores things thusly:
288 // +-------+-------+-------+-------+--------+--------+---------+
289 // | hash0 | hash1 | ..... | hashN | entry0 | entry1 | ... |
290 // +-------+-------+-------+-------+--------+--------+---------+
292 // which contains no wasted space between the hashes themselves, and no
293 // wasted space between the entries themselves. malloc is guaranteed to
294 // return blocks of memory with at least word alignment on all of our major
295 // platforms. PLDHashTable mandates that the size of the hash table is
296 // always a power of two, so the alignment of the memory containing the
297 // first entry is always at least the alignment of the entire entry store.
298 // That means the alignment of `entry0` should be its natural alignment.
299 // Entries may have problems if they contain over-aligned members such as
300 // SIMD vector types, but this has not been a problem in practice.
302 // Note: It would be natural to store the generation within this class, but
303 // we can't do that without bloating sizeof(PLDHashTable) on 64-bit machines.
304 // So instead we store it outside this class, and Set() takes a pointer to it
305 // and ensures it is updated as necessary.
306 class EntryStore {
307 private:
308 char* mEntryStore;
310 static char* Entries(char* aStore, uint32_t aCapacity) {
311 return aStore + aCapacity * sizeof(PLDHashNumber);
314 char* Entries(uint32_t aCapacity) const {
315 return Entries(Get(), aCapacity);
318 public:
319 EntryStore() : mEntryStore(nullptr) {}
321 ~EntryStore() {
322 free(mEntryStore);
323 mEntryStore = nullptr;
326 char* Get() const { return mEntryStore; }
327 bool IsAllocated() const { return !!mEntryStore; }
329 Slot SlotForIndex(uint32_t aIndex, uint32_t aEntrySize,
330 uint32_t aCapacity) const {
331 char* entries = Entries(aCapacity);
332 auto entry =
333 reinterpret_cast<PLDHashEntryHdr*>(entries + aIndex * aEntrySize);
334 auto hashes = reinterpret_cast<PLDHashNumber*>(Get());
335 return Slot(entry, &hashes[aIndex]);
338 Slot SlotForPLDHashEntry(PLDHashEntryHdr* aEntry, uint32_t aCapacity,
339 uint32_t aEntrySize) {
340 char* entries = Entries(aCapacity);
341 char* entry = reinterpret_cast<char*>(aEntry);
342 uint32_t entryOffset = entry - entries;
343 uint32_t slotIndex = entryOffset / aEntrySize;
344 return SlotForIndex(slotIndex, aEntrySize, aCapacity);
347 template <typename F>
348 void ForEachSlot(uint32_t aCapacity, uint32_t aEntrySize, F&& aFunc) {
349 ForEachSlot(Get(), aCapacity, aEntrySize, std::move(aFunc));
352 template <typename F>
353 static void ForEachSlot(char* aStore, uint32_t aCapacity,
354 uint32_t aEntrySize, F&& aFunc) {
355 char* entries = Entries(aStore, aCapacity);
356 Slot slot(reinterpret_cast<PLDHashEntryHdr*>(entries),
357 reinterpret_cast<PLDHashNumber*>(aStore));
358 for (size_t i = 0; i < aCapacity; ++i) {
359 aFunc(slot);
360 slot.Next(aEntrySize);
364 void Set(char* aEntryStore, uint16_t* aGeneration) {
365 mEntryStore = aEntryStore;
366 *aGeneration += 1;
370 // These fields are packed carefully. On 32-bit platforms,
371 // sizeof(PLDHashTable) is 20. On 64-bit platforms, sizeof(PLDHashTable) is
372 // 32; 28 bytes of data followed by 4 bytes of padding for alignment.
373 const PLDHashTableOps* const mOps; // Virtual operations; see below.
374 EntryStore mEntryStore; // (Lazy) entry storage and generation.
375 uint16_t mGeneration; // The storage generation.
376 uint8_t mHashShift; // Multiplicative hash shift.
377 const uint8_t mEntrySize; // Number of bytes in an entry.
378 uint32_t mEntryCount; // Number of entries in table.
379 uint32_t mRemovedCount; // Removed entry sentinels in table.
381 #ifdef MOZ_HASH_TABLE_CHECKS_ENABLED
382 mutable Checker mChecker;
383 #endif
385 public:
386 // Table capacity limit; do not exceed. The max capacity used to be 1<<23 but
387 // that occasionally that wasn't enough. Making it much bigger than 1<<26
388 // probably isn't worthwhile -- tables that big are kind of ridiculous.
389 // Also, the growth operation will (deliberately) fail if |capacity *
390 // mEntrySize| overflows a uint32_t, and mEntrySize is always at least 8
391 // bytes.
392 static const uint32_t kMaxCapacity = ((uint32_t)1 << 26);
394 static const uint32_t kMinCapacity = 8;
396 // Making this half of kMaxCapacity ensures it'll fit. Nobody should need an
397 // initial length anywhere nearly this large, anyway.
398 static const uint32_t kMaxInitialLength = kMaxCapacity / 2;
400 // This gives a default initial capacity of 8.
401 static const uint32_t kDefaultInitialLength = 4;
403 // Initialize the table with |aOps| and |aEntrySize|. The table's initial
404 // capacity is chosen such that |aLength| elements can be inserted without
405 // rehashing; if |aLength| is a power-of-two, this capacity will be
406 // |2*length|. However, because entry storage is allocated lazily, this
407 // initial capacity won't be relevant until the first element is added; prior
408 // to that the capacity will be zero.
410 // This will crash if |aEntrySize| and/or |aLength| are too large.
411 PLDHashTable(const PLDHashTableOps* aOps, uint32_t aEntrySize,
412 uint32_t aLength = kDefaultInitialLength);
414 PLDHashTable(PLDHashTable&& aOther)
415 // Initialize fields which are checked by the move assignment operator
416 // and the destructor (which the move assignment operator calls).
417 : mOps(nullptr), mGeneration(0), mEntrySize(0) {
418 *this = std::move(aOther);
421 PLDHashTable& operator=(PLDHashTable&& aOther);
423 ~PLDHashTable();
425 // This should be used rarely.
426 const PLDHashTableOps* Ops() const { return mOps; }
428 // Size in entries (gross, not net of free and removed sentinels) for table.
429 // This can be zero if no elements have been added yet, in which case the
430 // entry storage will not have yet been allocated.
431 uint32_t Capacity() const {
432 return mEntryStore.IsAllocated() ? CapacityFromHashShift() : 0;
435 uint32_t EntrySize() const { return mEntrySize; }
436 uint32_t EntryCount() const { return mEntryCount; }
437 uint32_t Generation() const { return mGeneration; }
439 // To search for a |key| in |table|, call:
441 // entry = table.Search(key);
443 // If |entry| is non-null, |key| was found. If |entry| is null, key was not
444 // found.
445 PLDHashEntryHdr* Search(const void* aKey) const;
447 // To add an entry identified by |key| to table, call:
449 // entry = table.Add(key, mozilla::fallible);
451 // If |entry| is null upon return, then the table is severely overloaded and
452 // memory can't be allocated for entry storage.
454 // Otherwise, if the initEntry hook was provided, |entry| will be
455 // initialized. If the initEntry hook was not provided, the caller
456 // should initialize |entry| as appropriate.
457 PLDHashEntryHdr* Add(const void* aKey, const mozilla::fallible_t&);
459 // This is like the other Add() function, but infallible, and so never
460 // returns null.
461 PLDHashEntryHdr* Add(const void* aKey);
463 // To remove an entry identified by |key| from table, call:
465 // table.Remove(key);
467 // If |key|'s entry is found, it is cleared (via table->mOps->clearEntry).
468 // The table's capacity may be reduced afterwards.
469 void Remove(const void* aKey);
471 // To remove an entry found by a prior search, call:
473 // table.RemoveEntry(entry);
475 // The entry, which must be present and in use, is cleared (via
476 // table->mOps->clearEntry). The table's capacity may be reduced afterwards.
477 void RemoveEntry(PLDHashEntryHdr* aEntry);
479 // Remove an entry already accessed via Search() or Add().
481 // NB: this is a "raw" or low-level method. It does not shrink the table if
482 // it is underloaded. Don't use it unless necessary and you know what you are
483 // doing, and if so, please explain in a comment why it is necessary instead
484 // of RemoveEntry().
485 void RawRemove(PLDHashEntryHdr* aEntry);
487 // This function is equivalent to
488 // ClearAndPrepareForLength(kDefaultInitialLength).
489 void Clear();
491 // This function clears the table's contents and frees its entry storage,
492 // leaving it in a empty state ready to be used again. Afterwards, when the
493 // first element is added the entry storage that gets allocated will have a
494 // capacity large enough to fit |aLength| elements without rehashing.
496 // It's conceptually the same as calling the destructor and then re-calling
497 // the constructor with the original |aOps| and |aEntrySize| arguments, and
498 // a new |aLength| argument.
499 void ClearAndPrepareForLength(uint32_t aLength);
501 // Measure the size of the table's entry storage. If the entries contain
502 // pointers to other heap blocks, you have to iterate over the table and
503 // measure those separately; hence the "Shallow" prefix.
504 size_t ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
506 // Like ShallowSizeOfExcludingThis(), but includes sizeof(*this).
507 size_t ShallowSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
509 // Mark a table as immutable for the remainder of its lifetime. This
510 // changes the implementation from asserting one set of invariants to
511 // asserting a different set.
512 void MarkImmutable() {
513 #ifdef MOZ_HASH_TABLE_CHECKS_ENABLED
514 mChecker.SetNonWritable();
515 #endif
518 // If you use PLDHashEntryStub or a subclass of it as your entry struct, and
519 // if your entries move via memcpy and clear via memset(0), you can use these
520 // stub operations.
521 static const PLDHashTableOps* StubOps();
523 // The individual stub operations in StubOps().
524 static PLDHashNumber HashVoidPtrKeyStub(const void* aKey);
525 static bool MatchEntryStub(const PLDHashEntryHdr* aEntry, const void* aKey);
526 static void MoveEntryStub(PLDHashTable* aTable, const PLDHashEntryHdr* aFrom,
527 PLDHashEntryHdr* aTo);
528 static void ClearEntryStub(PLDHashTable* aTable, PLDHashEntryHdr* aEntry);
530 // Hash/match operations for tables holding C strings.
531 static PLDHashNumber HashStringKey(const void* aKey);
532 static bool MatchStringKey(const PLDHashEntryHdr* aEntry, const void* aKey);
534 class EntryHandle {
535 public:
536 EntryHandle(EntryHandle&& aOther) noexcept;
537 #ifdef MOZ_HASH_TABLE_CHECKS_ENABLED
538 ~EntryHandle();
539 #endif
541 EntryHandle(const EntryHandle&) = delete;
542 EntryHandle& operator=(const EntryHandle&) = delete;
543 EntryHandle& operator=(EntryHandle&& aOther) = delete;
545 // Is this slot currently occupied?
546 bool HasEntry() const { return mSlot.IsLive(); }
548 explicit operator bool() const { return HasEntry(); }
550 // Get the entry stored in this slot. May not be called unless the slot is
551 // currently occupied.
552 PLDHashEntryHdr* Entry() {
553 MOZ_ASSERT(HasEntry());
554 return mSlot.ToEntry();
557 template <class F>
558 void Insert(F&& aInitEntry) {
559 MOZ_ASSERT(!HasEntry());
560 OccupySlot();
561 std::forward<F>(aInitEntry)(Entry());
564 // If the slot is currently vacant, the slot is occupied and `initEntry` is
565 // invoked to initialize the entry. Returns the entry stored in now-occupied
566 // slot.
567 template <class F>
568 PLDHashEntryHdr* OrInsert(F&& aInitEntry) {
569 if (!HasEntry()) {
570 Insert(std::forward<F>(aInitEntry));
572 return Entry();
575 /** Removes the entry. Note that the table won't shrink on destruction of
576 * the EntryHandle.
578 * \pre HasEntry()
579 * \post !HasEntry()
581 void Remove();
583 /** Removes the entry, if it exists. Note that the table won't shrink on
584 * destruction of the EntryHandle.
586 * \post !HasEntry()
588 void OrRemove();
590 private:
591 friend class PLDHashTable;
593 EntryHandle(PLDHashTable* aTable, PLDHashNumber aKeyHash, Slot aSlot);
595 void OccupySlot();
597 PLDHashTable* mTable;
598 PLDHashNumber mKeyHash;
599 Slot mSlot;
602 template <class F>
603 auto WithEntryHandle(const void* aKey, F&& aFunc)
604 -> std::invoke_result_t<F, EntryHandle&&> {
605 return std::forward<F>(aFunc)(MakeEntryHandle(aKey));
608 template <class F>
609 auto WithEntryHandle(const void* aKey, const mozilla::fallible_t& aFallible,
610 F&& aFunc)
611 -> std::invoke_result_t<F, mozilla::Maybe<EntryHandle>&&> {
612 return std::forward<F>(aFunc)(MakeEntryHandle(aKey, aFallible));
615 // This is an iterator for PLDHashtable. Assertions will detect some, but not
616 // all, mid-iteration table modifications that might invalidate (e.g.
617 // reallocate) the entry storage.
619 // Any element can be removed during iteration using Remove(). If any
620 // elements are removed, the table may be resized once iteration ends.
622 // Example usage:
624 // for (auto iter = table.Iter(); !iter.Done(); iter.Next()) {
625 // auto entry = static_cast<FooEntry*>(iter.Get());
626 // // ... do stuff with |entry| ...
627 // // ... possibly call iter.Remove() once ...
628 // }
630 // or:
632 // for (PLDHashTable::Iterator iter(&table); !iter.Done(); iter.Next()) {
633 // auto entry = static_cast<FooEntry*>(iter.Get());
634 // // ... do stuff with |entry| ...
635 // // ... possibly call iter.Remove() once ...
636 // }
638 // The latter form is more verbose but is easier to work with when
639 // making subclasses of Iterator.
641 class Iterator {
642 public:
643 explicit Iterator(PLDHashTable* aTable);
644 struct EndIteratorTag {};
645 Iterator(PLDHashTable* aTable, EndIteratorTag aTag);
646 Iterator(Iterator&& aOther);
647 ~Iterator();
649 // Have we finished?
650 bool Done() const { return mNexts == mNextsLimit; }
652 // Get the current entry.
653 PLDHashEntryHdr* Get() const {
654 MOZ_ASSERT(!Done());
655 MOZ_ASSERT(mCurrent.IsLive());
656 return mCurrent.ToEntry();
659 // Advance to the next entry.
660 void Next();
662 // Remove the current entry. Must only be called once per entry, and Get()
663 // must not be called on that entry afterwards.
664 void Remove();
666 bool operator==(const Iterator& aOther) const {
667 MOZ_ASSERT(mTable == aOther.mTable);
668 return mNexts == aOther.mNexts;
671 Iterator Clone() const { return {*this}; }
673 protected:
674 PLDHashTable* mTable; // Main table pointer.
676 private:
677 Slot mCurrent; // Pointer to the current entry.
678 uint32_t mNexts; // Number of Next() calls.
679 uint32_t mNextsLimit; // Next() call limit.
681 bool mHaveRemoved; // Have any elements been removed?
682 uint8_t mEntrySize; // Size of entries.
684 bool IsOnNonLiveEntry() const;
686 void MoveToNextLiveEntry();
688 Iterator() = delete;
689 Iterator(const Iterator&);
690 Iterator& operator=(const Iterator&) = delete;
691 Iterator& operator=(const Iterator&&) = delete;
694 Iterator Iter() { return Iterator(this); }
696 // Use this if you need to initialize an Iterator in a const method. If you
697 // use this case, you should not call Remove() on the iterator.
698 Iterator ConstIter() const {
699 return Iterator(const_cast<PLDHashTable*>(this));
702 private:
703 static uint32_t HashShift(uint32_t aEntrySize, uint32_t aLength);
705 static const PLDHashNumber kCollisionFlag = 1;
707 PLDHashNumber Hash1(PLDHashNumber aHash0) const;
708 void Hash2(PLDHashNumber aHash, uint32_t& aHash2Out,
709 uint32_t& aSizeMaskOut) const;
711 static bool MatchSlotKeyhash(Slot& aSlot, const PLDHashNumber aHash);
712 Slot SlotForIndex(uint32_t aIndex) const;
714 // We store mHashShift rather than sizeLog2 to optimize the collision-free
715 // case in SearchTable.
716 uint32_t CapacityFromHashShift() const {
717 return ((uint32_t)1 << (kPLDHashNumberBits - mHashShift));
720 PLDHashNumber ComputeKeyHash(const void* aKey) const;
722 enum SearchReason { ForSearchOrRemove, ForAdd };
724 // Avoid using bare `Success` and `Failure`, as those names are commonly
725 // defined as macros.
726 template <SearchReason Reason, typename PLDSuccess, typename PLDFailure>
727 auto SearchTable(const void* aKey, PLDHashNumber aKeyHash,
728 PLDSuccess&& aSucess, PLDFailure&& aFailure) const;
730 Slot FindFreeSlot(PLDHashNumber aKeyHash) const;
732 bool ChangeTable(int aDeltaLog2);
734 void RawRemove(Slot& aSlot);
735 void ShrinkIfAppropriate();
737 mozilla::Maybe<EntryHandle> MakeEntryHandle(const void* aKey,
738 const mozilla::fallible_t&);
740 EntryHandle MakeEntryHandle(const void* aKey);
742 PLDHashTable(const PLDHashTable& aOther) = delete;
743 PLDHashTable& operator=(const PLDHashTable& aOther) = delete;
746 // Compute the hash code for a given key to be looked up, added, or removed.
747 // A hash code may have any PLDHashNumber value.
748 typedef PLDHashNumber (*PLDHashHashKey)(const void* aKey);
750 // Compare the key identifying aEntry with the provided key parameter. Return
751 // true if keys match, false otherwise.
752 typedef bool (*PLDHashMatchEntry)(const PLDHashEntryHdr* aEntry,
753 const void* aKey);
755 // Copy the data starting at aFrom to the new entry storage at aTo. Do not add
756 // reference counts for any strong references in the entry, however, as this
757 // is a "move" operation: the old entry storage at from will be freed without
758 // any reference-decrementing callback shortly.
759 typedef void (*PLDHashMoveEntry)(PLDHashTable* aTable,
760 const PLDHashEntryHdr* aFrom,
761 PLDHashEntryHdr* aTo);
763 // Clear the entry and drop any strong references it holds. This callback is
764 // invoked by Remove(), but only if the given key is found in the table.
765 typedef void (*PLDHashClearEntry)(PLDHashTable* aTable,
766 PLDHashEntryHdr* aEntry);
768 // Initialize a new entry. This function is called when
769 // Add() finds no existing entry for the given key, and must add a new one.
770 typedef void (*PLDHashInitEntry)(PLDHashEntryHdr* aEntry, const void* aKey);
772 // Finally, the "vtable" structure for PLDHashTable. The first four hooks
773 // must be provided by implementations; they're called unconditionally by the
774 // generic PLDHashTable.cpp code. Hooks after these may be null.
776 // Summary of allocation-related hook usage with C++ placement new emphasis:
777 // initEntry Call placement new using default key-based ctor.
778 // moveEntry Call placement new using copy ctor, run dtor on old
779 // entry storage.
780 // clearEntry Run dtor on entry.
782 // Note the reason why initEntry is optional: the default hooks (stubs) clear
783 // entry storage. On a successful Add(tbl, key), the returned entry pointer
784 // addresses an entry struct whose entry members are still clear (null). Add()
785 // callers can test such members to see whether the entry was newly created by
786 // the Add() call that just succeeded. If placement new or similar
787 // initialization is required, define an |initEntry| hook. Of course, the
788 // |clearEntry| hook must zero or null appropriately.
790 // XXX assumes 0 is null for pointer types.
791 struct PLDHashTableOps {
792 // Mandatory hooks. All implementations must provide these.
793 PLDHashHashKey hashKey;
794 PLDHashMatchEntry matchEntry;
795 PLDHashMoveEntry moveEntry;
797 // Optional hooks start here. If null, these are not called.
798 PLDHashClearEntry clearEntry;
799 PLDHashInitEntry initEntry;
802 // A minimal entry is a subclass of PLDHashEntryHdr and has a void* key pointer.
803 struct PLDHashEntryStub : public PLDHashEntryHdr {
804 const void* key;
807 #endif /* PLDHashTable_h */