Bug 1826905 [wpt PR 39420] - view-transition: Add WPTs for damage tracking when new...
[gecko.git] / mfbt / HashTable.h
blobe5fadcf5516b5e6919bf06d6309f42e6e4e0c7c7
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 //---------------------------------------------------------------------------
8 // Overview
9 //---------------------------------------------------------------------------
11 // This file defines HashMap<Key, Value> and HashSet<T>, hash tables that are
12 // fast and have a nice API.
14 // Both hash tables have two optional template parameters.
16 // - HashPolicy. This defines the operations for hashing and matching keys. The
17 // default HashPolicy is appropriate when both of the following two
18 // conditions are true.
20 // - The key type stored in the table (|Key| for |HashMap<Key, Value>|, |T|
21 // for |HashSet<T>|) is an integer, pointer, UniquePtr, float, or double.
23 // - The type used for lookups (|Lookup|) is the same as the key type. This
24 // is usually the case, but not always.
26 // There is also a |CStringHasher| policy for |char*| keys. If your keys
27 // don't match any of the above cases, you must provide your own hash policy;
28 // see the "Hash Policy" section below.
30 // - AllocPolicy. This defines how allocations are done by the table.
32 // - |MallocAllocPolicy| is the default and is usually appropriate; note that
33 // operations (such as insertions) that might cause allocations are
34 // fallible and must be checked for OOM. These checks are enforced by the
35 // use of [[nodiscard]].
37 // - |InfallibleAllocPolicy| is another possibility; it allows the
38 // abovementioned OOM checks to be done with MOZ_ALWAYS_TRUE().
40 // Note that entry storage allocation is lazy, and not done until the first
41 // lookupForAdd(), put(), or putNew() is performed.
43 // See AllocPolicy.h for more details.
45 // Documentation on how to use HashMap and HashSet, including examples, is
46 // present within those classes. Search for "class HashMap" and "class
47 // HashSet".
49 // Both HashMap and HashSet are implemented on top of a third class, HashTable.
50 // You only need to look at HashTable if you want to understand the
51 // implementation.
53 // How does mozilla::HashTable (this file) compare with PLDHashTable (and its
54 // subclasses, such as nsTHashtable)?
56 // - mozilla::HashTable is a lot faster, largely because it uses templates
57 // throughout *and* inlines everything. PLDHashTable inlines operations much
58 // less aggressively, and also uses "virtual ops" for operations like hashing
59 // and matching entries that require function calls.
61 // - Correspondingly, mozilla::HashTable use is likely to increase executable
62 // size much more than PLDHashTable.
64 // - mozilla::HashTable has a nicer API, with a proper HashSet vs. HashMap
65 // distinction.
67 // - mozilla::HashTable requires more explicit OOM checking. As mentioned
68 // above, the use of |InfallibleAllocPolicy| can simplify things.
70 // - mozilla::HashTable has a default capacity on creation of 32 and a minimum
71 // capacity of 4. PLDHashTable has a default capacity on creation of 8 and a
72 // minimum capacity of 8.
74 #ifndef mozilla_HashTable_h
75 #define mozilla_HashTable_h
77 #include <utility>
78 #include <type_traits>
80 #include "mozilla/AllocPolicy.h"
81 #include "mozilla/Assertions.h"
82 #include "mozilla/Attributes.h"
83 #include "mozilla/Casting.h"
84 #include "mozilla/HashFunctions.h"
85 #include "mozilla/MathAlgorithms.h"
86 #include "mozilla/Maybe.h"
87 #include "mozilla/MemoryChecking.h"
88 #include "mozilla/MemoryReporting.h"
89 #include "mozilla/Opaque.h"
90 #include "mozilla/OperatorNewExtensions.h"
91 #include "mozilla/ReentrancyGuard.h"
92 #include "mozilla/UniquePtr.h"
93 #include "mozilla/WrappingOperations.h"
95 namespace mozilla {
97 template <class, class = void>
98 struct DefaultHasher;
100 template <class, class>
101 class HashMapEntry;
103 namespace detail {
105 template <typename T>
106 class HashTableEntry;
108 template <class T, class HashPolicy, class AllocPolicy>
109 class HashTable;
111 } // namespace detail
113 // The "generation" of a hash table is an opaque value indicating the state of
114 // modification of the hash table through its lifetime. If the generation of
115 // a hash table compares equal at times T1 and T2, then lookups in the hash
116 // table, pointers to (or into) hash table entries, etc. at time T1 are valid
117 // at time T2. If the generation compares unequal, these computations are all
118 // invalid and must be performed again to be used.
120 // Generations are meaningfully comparable only with respect to a single hash
121 // table. It's always nonsensical to compare the generation of distinct hash
122 // tables H1 and H2.
123 using Generation = Opaque<uint64_t>;
125 //---------------------------------------------------------------------------
126 // HashMap
127 //---------------------------------------------------------------------------
129 // HashMap is a fast hash-based map from keys to values.
131 // Template parameter requirements:
132 // - Key/Value: movable, destructible, assignable.
133 // - HashPolicy: see the "Hash Policy" section below.
134 // - AllocPolicy: see AllocPolicy.h.
136 // Note:
137 // - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members
138 // called by HashMap must not call back into the same HashMap object.
140 template <class Key, class Value, class HashPolicy = DefaultHasher<Key>,
141 class AllocPolicy = MallocAllocPolicy>
142 class HashMap {
143 // -- Implementation details -----------------------------------------------
145 // HashMap is not copyable or assignable.
146 HashMap(const HashMap& hm) = delete;
147 HashMap& operator=(const HashMap& hm) = delete;
149 using TableEntry = HashMapEntry<Key, Value>;
151 struct MapHashPolicy : HashPolicy {
152 using Base = HashPolicy;
153 using KeyType = Key;
155 static const Key& getKey(TableEntry& aEntry) { return aEntry.key(); }
157 static void setKey(TableEntry& aEntry, Key& aKey) {
158 HashPolicy::rekey(aEntry.mutableKey(), aKey);
162 using Impl = detail::HashTable<TableEntry, MapHashPolicy, AllocPolicy>;
163 Impl mImpl;
165 friend class Impl::Enum;
167 public:
168 using Lookup = typename HashPolicy::Lookup;
169 using Entry = TableEntry;
171 // -- Initialization -------------------------------------------------------
173 explicit HashMap(AllocPolicy aAllocPolicy = AllocPolicy(),
174 uint32_t aLen = Impl::sDefaultLen)
175 : mImpl(std::move(aAllocPolicy), aLen) {}
177 explicit HashMap(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
179 // HashMap is movable.
180 HashMap(HashMap&& aRhs) = default;
181 HashMap& operator=(HashMap&& aRhs) = default;
183 // -- Status and sizing ----------------------------------------------------
185 // The map's current generation.
186 Generation generation() const { return mImpl.generation(); }
188 // Is the map empty?
189 bool empty() const { return mImpl.empty(); }
191 // Number of keys/values in the map.
192 uint32_t count() const { return mImpl.count(); }
194 // Number of key/value slots in the map. Note: resize will happen well before
195 // count() == capacity().
196 uint32_t capacity() const { return mImpl.capacity(); }
198 // The size of the map's entry storage, in bytes. If the keys/values contain
199 // pointers to other heap blocks, you must iterate over the map and measure
200 // them separately; hence the "shallow" prefix.
201 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
202 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
204 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
205 return aMallocSizeOf(this) +
206 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
209 // Attempt to minimize the capacity(). If the table is empty, this will free
210 // the empty storage and upon regrowth it will be given the minimum capacity.
211 void compact() { mImpl.compact(); }
213 // Attempt to reserve enough space to fit at least |aLen| elements. This is
214 // total capacity, including elements already present. Does nothing if the
215 // map already has sufficient capacity.
216 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
218 // -- Lookups --------------------------------------------------------------
220 // Does the map contain a key/value matching |aLookup|?
221 bool has(const Lookup& aLookup) const {
222 return mImpl.lookup(aLookup).found();
225 // Return a Ptr indicating whether a key/value matching |aLookup| is
226 // present in the map. E.g.:
228 // using HM = HashMap<int,char>;
229 // HM h;
230 // if (HM::Ptr p = h.lookup(3)) {
231 // assert(p->key() == 3);
232 // char val = p->value();
233 // }
235 using Ptr = typename Impl::Ptr;
236 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
237 return mImpl.lookup(aLookup);
240 // Like lookup(), but does not assert if two threads call it at the same
241 // time. Only use this method when none of the threads will modify the map.
242 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
243 return mImpl.readonlyThreadsafeLookup(aLookup);
246 // -- Insertions -----------------------------------------------------------
248 // Overwrite existing value with |aValue|, or add it if not present. Returns
249 // false on OOM.
250 template <typename KeyInput, typename ValueInput>
251 [[nodiscard]] bool put(KeyInput&& aKey, ValueInput&& aValue) {
252 return put(aKey, std::forward<KeyInput>(aKey),
253 std::forward<ValueInput>(aValue));
256 template <typename KeyInput, typename ValueInput>
257 [[nodiscard]] bool put(const Lookup& aLookup, KeyInput&& aKey,
258 ValueInput&& aValue) {
259 AddPtr p = lookupForAdd(aLookup);
260 if (p) {
261 p->value() = std::forward<ValueInput>(aValue);
262 return true;
264 return add(p, std::forward<KeyInput>(aKey),
265 std::forward<ValueInput>(aValue));
268 // Like put(), but slightly faster. Must only be used when the given key is
269 // not already present. (In debug builds, assertions check this.)
270 template <typename KeyInput, typename ValueInput>
271 [[nodiscard]] bool putNew(KeyInput&& aKey, ValueInput&& aValue) {
272 return mImpl.putNew(aKey, std::forward<KeyInput>(aKey),
273 std::forward<ValueInput>(aValue));
276 template <typename KeyInput, typename ValueInput>
277 [[nodiscard]] bool putNew(const Lookup& aLookup, KeyInput&& aKey,
278 ValueInput&& aValue) {
279 return mImpl.putNew(aLookup, std::forward<KeyInput>(aKey),
280 std::forward<ValueInput>(aValue));
283 // Like putNew(), but should be only used when the table is known to be big
284 // enough for the insertion, and hashing cannot fail. Typically this is used
285 // to populate an empty map with known-unique keys after reserving space with
286 // reserve(), e.g.
288 // using HM = HashMap<int,char>;
289 // HM h;
290 // if (!h.reserve(3)) {
291 // MOZ_CRASH("OOM");
292 // }
293 // h.putNewInfallible(1, 'a'); // unique key
294 // h.putNewInfallible(2, 'b'); // unique key
295 // h.putNewInfallible(3, 'c'); // unique key
297 template <typename KeyInput, typename ValueInput>
298 void putNewInfallible(KeyInput&& aKey, ValueInput&& aValue) {
299 mImpl.putNewInfallible(aKey, std::forward<KeyInput>(aKey),
300 std::forward<ValueInput>(aValue));
303 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
304 // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using
305 // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new key/value. E.g.:
307 // using HM = HashMap<int,char>;
308 // HM h;
309 // HM::AddPtr p = h.lookupForAdd(3);
310 // if (!p) {
311 // if (!h.add(p, 3, 'a')) {
312 // return false;
313 // }
314 // }
315 // assert(p->key() == 3);
316 // char val = p->value();
318 // N.B. The caller must ensure that no mutating hash table operations occur
319 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
320 // key a second time, the caller may use the more efficient relookupOrAdd()
321 // method. This method reuses part of the hashing computation to more
322 // efficiently insert the key if it has not been added. For example, a
323 // mutation-handling version of the previous example:
325 // HM::AddPtr p = h.lookupForAdd(3);
326 // if (!p) {
327 // call_that_may_mutate_h();
328 // if (!h.relookupOrAdd(p, 3, 'a')) {
329 // return false;
330 // }
331 // }
332 // assert(p->key() == 3);
333 // char val = p->value();
335 using AddPtr = typename Impl::AddPtr;
336 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
337 return mImpl.lookupForAdd(aLookup);
340 // Add a key/value. Returns false on OOM.
341 template <typename KeyInput, typename ValueInput>
342 [[nodiscard]] bool add(AddPtr& aPtr, KeyInput&& aKey, ValueInput&& aValue) {
343 return mImpl.add(aPtr, std::forward<KeyInput>(aKey),
344 std::forward<ValueInput>(aValue));
347 // See the comment above lookupForAdd() for details.
348 template <typename KeyInput, typename ValueInput>
349 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, KeyInput&& aKey,
350 ValueInput&& aValue) {
351 return mImpl.relookupOrAdd(aPtr, aKey, std::forward<KeyInput>(aKey),
352 std::forward<ValueInput>(aValue));
355 // -- Removal --------------------------------------------------------------
357 // Lookup and remove the key/value matching |aLookup|, if present.
358 void remove(const Lookup& aLookup) {
359 if (Ptr p = lookup(aLookup)) {
360 remove(p);
364 // Remove a previously found key/value (assuming aPtr.found()). The map must
365 // not have been mutated in the interim.
366 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
368 // Remove all keys/values without changing the capacity.
369 void clear() { mImpl.clear(); }
371 // Like clear() followed by compact().
372 void clearAndCompact() { mImpl.clearAndCompact(); }
374 // -- Rekeying -------------------------------------------------------------
376 // Infallibly rekey one entry, if necessary. Requires that template
377 // parameters Key and HashPolicy::Lookup are the same type.
378 void rekeyIfMoved(const Key& aOldKey, const Key& aNewKey) {
379 if (aOldKey != aNewKey) {
380 rekeyAs(aOldKey, aNewKey, aNewKey);
384 // Infallibly rekey one entry if present, and return whether that happened.
385 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
386 const Key& aNewKey) {
387 if (Ptr p = lookup(aOldLookup)) {
388 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewKey);
389 return true;
391 return false;
394 // -- Iteration ------------------------------------------------------------
396 // |iter()| returns an Iterator:
398 // HashMap<int, char> h;
399 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
400 // char c = iter.get().value();
401 // }
403 using Iterator = typename Impl::Iterator;
404 Iterator iter() const { return mImpl.iter(); }
406 // |modIter()| returns a ModIterator:
408 // HashMap<int, char> h;
409 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
410 // if (iter.get().value() == 'l') {
411 // iter.remove();
412 // }
413 // }
415 // Table resize may occur in ModIterator's destructor.
416 using ModIterator = typename Impl::ModIterator;
417 ModIterator modIter() { return mImpl.modIter(); }
419 // These are similar to Iterator/ModIterator/iter(), but use different
420 // terminology.
421 using Range = typename Impl::Range;
422 using Enum = typename Impl::Enum;
423 Range all() const { return mImpl.all(); }
426 //---------------------------------------------------------------------------
427 // HashSet
428 //---------------------------------------------------------------------------
430 // HashSet is a fast hash-based set of values.
432 // Template parameter requirements:
433 // - T: movable, destructible, assignable.
434 // - HashPolicy: see the "Hash Policy" section below.
435 // - AllocPolicy: see AllocPolicy.h
437 // Note:
438 // - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by
439 // HashSet must not call back into the same HashSet object.
441 template <class T, class HashPolicy = DefaultHasher<T>,
442 class AllocPolicy = MallocAllocPolicy>
443 class HashSet {
444 // -- Implementation details -----------------------------------------------
446 // HashSet is not copyable or assignable.
447 HashSet(const HashSet& hs) = delete;
448 HashSet& operator=(const HashSet& hs) = delete;
450 struct SetHashPolicy : HashPolicy {
451 using Base = HashPolicy;
452 using KeyType = T;
454 static const KeyType& getKey(const T& aT) { return aT; }
456 static void setKey(T& aT, KeyType& aKey) { HashPolicy::rekey(aT, aKey); }
459 using Impl = detail::HashTable<const T, SetHashPolicy, AllocPolicy>;
460 Impl mImpl;
462 friend class Impl::Enum;
464 public:
465 using Lookup = typename HashPolicy::Lookup;
466 using Entry = T;
468 // -- Initialization -------------------------------------------------------
470 explicit HashSet(AllocPolicy aAllocPolicy = AllocPolicy(),
471 uint32_t aLen = Impl::sDefaultLen)
472 : mImpl(std::move(aAllocPolicy), aLen) {}
474 explicit HashSet(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
476 // HashSet is movable.
477 HashSet(HashSet&& aRhs) = default;
478 HashSet& operator=(HashSet&& aRhs) = default;
480 // -- Status and sizing ----------------------------------------------------
482 // The set's current generation.
483 Generation generation() const { return mImpl.generation(); }
485 // Is the set empty?
486 bool empty() const { return mImpl.empty(); }
488 // Number of elements in the set.
489 uint32_t count() const { return mImpl.count(); }
491 // Number of element slots in the set. Note: resize will happen well before
492 // count() == capacity().
493 uint32_t capacity() const { return mImpl.capacity(); }
495 // The size of the set's entry storage, in bytes. If the elements contain
496 // pointers to other heap blocks, you must iterate over the set and measure
497 // them separately; hence the "shallow" prefix.
498 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
499 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
501 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
502 return aMallocSizeOf(this) +
503 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
506 // Attempt to minimize the capacity(). If the table is empty, this will free
507 // the empty storage and upon regrowth it will be given the minimum capacity.
508 void compact() { mImpl.compact(); }
510 // Attempt to reserve enough space to fit at least |aLen| elements. This is
511 // total capacity, including elements already present. Does nothing if the
512 // map already has sufficient capacity.
513 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
515 // -- Lookups --------------------------------------------------------------
517 // Does the set contain an element matching |aLookup|?
518 bool has(const Lookup& aLookup) const {
519 return mImpl.lookup(aLookup).found();
522 // Return a Ptr indicating whether an element matching |aLookup| is present
523 // in the set. E.g.:
525 // using HS = HashSet<int>;
526 // HS h;
527 // if (HS::Ptr p = h.lookup(3)) {
528 // assert(*p == 3); // p acts like a pointer to int
529 // }
531 using Ptr = typename Impl::Ptr;
532 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
533 return mImpl.lookup(aLookup);
536 // Like lookup(), but does not assert if two threads call it at the same
537 // time. Only use this method when none of the threads will modify the set.
538 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
539 return mImpl.readonlyThreadsafeLookup(aLookup);
542 // -- Insertions -----------------------------------------------------------
544 // Add |aU| if it is not present already. Returns false on OOM.
545 template <typename U>
546 [[nodiscard]] bool put(U&& aU) {
547 AddPtr p = lookupForAdd(aU);
548 return p ? true : add(p, std::forward<U>(aU));
551 // Like put(), but slightly faster. Must only be used when the given element
552 // is not already present. (In debug builds, assertions check this.)
553 template <typename U>
554 [[nodiscard]] bool putNew(U&& aU) {
555 return mImpl.putNew(aU, std::forward<U>(aU));
558 // Like the other putNew(), but for when |Lookup| is different to |T|.
559 template <typename U>
560 [[nodiscard]] bool putNew(const Lookup& aLookup, U&& aU) {
561 return mImpl.putNew(aLookup, std::forward<U>(aU));
564 // Like putNew(), but should be only used when the table is known to be big
565 // enough for the insertion, and hashing cannot fail. Typically this is used
566 // to populate an empty set with known-unique elements after reserving space
567 // with reserve(), e.g.
569 // using HS = HashMap<int>;
570 // HS h;
571 // if (!h.reserve(3)) {
572 // MOZ_CRASH("OOM");
573 // }
574 // h.putNewInfallible(1); // unique element
575 // h.putNewInfallible(2); // unique element
576 // h.putNewInfallible(3); // unique element
578 template <typename U>
579 void putNewInfallible(const Lookup& aLookup, U&& aU) {
580 mImpl.putNewInfallible(aLookup, std::forward<U>(aU));
583 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
584 // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using
585 // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.:
587 // using HS = HashSet<int>;
588 // HS h;
589 // HS::AddPtr p = h.lookupForAdd(3);
590 // if (!p) {
591 // if (!h.add(p, 3)) {
592 // return false;
593 // }
594 // }
595 // assert(*p == 3); // p acts like a pointer to int
597 // N.B. The caller must ensure that no mutating hash table operations occur
598 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
599 // key a second time, the caller may use the more efficient relookupOrAdd()
600 // method. This method reuses part of the hashing computation to more
601 // efficiently insert the key if it has not been added. For example, a
602 // mutation-handling version of the previous example:
604 // HS::AddPtr p = h.lookupForAdd(3);
605 // if (!p) {
606 // call_that_may_mutate_h();
607 // if (!h.relookupOrAdd(p, 3, 3)) {
608 // return false;
609 // }
610 // }
611 // assert(*p == 3);
613 // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the
614 // entry |t|, where the caller ensures match(l,t).
615 using AddPtr = typename Impl::AddPtr;
616 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
617 return mImpl.lookupForAdd(aLookup);
620 // Add an element. Returns false on OOM.
621 template <typename U>
622 [[nodiscard]] bool add(AddPtr& aPtr, U&& aU) {
623 return mImpl.add(aPtr, std::forward<U>(aU));
626 // See the comment above lookupForAdd() for details.
627 template <typename U>
628 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
629 U&& aU) {
630 return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
633 // -- Removal --------------------------------------------------------------
635 // Lookup and remove the element matching |aLookup|, if present.
636 void remove(const Lookup& aLookup) {
637 if (Ptr p = lookup(aLookup)) {
638 remove(p);
642 // Remove a previously found element (assuming aPtr.found()). The set must
643 // not have been mutated in the interim.
644 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
646 // Remove all keys/values without changing the capacity.
647 void clear() { mImpl.clear(); }
649 // Like clear() followed by compact().
650 void clearAndCompact() { mImpl.clearAndCompact(); }
652 // -- Rekeying -------------------------------------------------------------
654 // Infallibly rekey one entry, if present. Requires that template parameters
655 // T and HashPolicy::Lookup are the same type.
656 void rekeyIfMoved(const Lookup& aOldValue, const T& aNewValue) {
657 if (aOldValue != aNewValue) {
658 rekeyAs(aOldValue, aNewValue, aNewValue);
662 // Infallibly rekey one entry if present, and return whether that happened.
663 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
664 const T& aNewValue) {
665 if (Ptr p = lookup(aOldLookup)) {
666 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewValue);
667 return true;
669 return false;
672 // Infallibly replace the current key at |aPtr| with an equivalent key.
673 // Specifically, both HashPolicy::hash and HashPolicy::match must return
674 // identical results for the new and old key when applied against all
675 // possible matching values.
676 void replaceKey(Ptr aPtr, const Lookup& aLookup, const T& aNewValue) {
677 MOZ_ASSERT(aPtr.found());
678 MOZ_ASSERT(*aPtr != aNewValue);
679 MOZ_ASSERT(HashPolicy::match(*aPtr, aLookup));
680 MOZ_ASSERT(HashPolicy::match(aNewValue, aLookup));
681 const_cast<T&>(*aPtr) = aNewValue;
682 MOZ_ASSERT(*lookup(aLookup) == aNewValue);
684 void replaceKey(Ptr aPtr, const T& aNewValue) {
685 replaceKey(aPtr, aNewValue, aNewValue);
688 // -- Iteration ------------------------------------------------------------
690 // |iter()| returns an Iterator:
692 // HashSet<int> h;
693 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
694 // int i = iter.get();
695 // }
697 using Iterator = typename Impl::Iterator;
698 Iterator iter() const { return mImpl.iter(); }
700 // |modIter()| returns a ModIterator:
702 // HashSet<int> h;
703 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
704 // if (iter.get() == 42) {
705 // iter.remove();
706 // }
707 // }
709 // Table resize may occur in ModIterator's destructor.
710 using ModIterator = typename Impl::ModIterator;
711 ModIterator modIter() { return mImpl.modIter(); }
713 // These are similar to Iterator/ModIterator/iter(), but use different
714 // terminology.
715 using Range = typename Impl::Range;
716 using Enum = typename Impl::Enum;
717 Range all() const { return mImpl.all(); }
720 //---------------------------------------------------------------------------
721 // Hash Policy
722 //---------------------------------------------------------------------------
724 // A hash policy |HP| for a hash table with key-type |Key| must provide:
726 // - a type |HP::Lookup| to use to lookup table entries;
728 // - a static member function |HP::hash| that hashes lookup values:
730 // static mozilla::HashNumber hash(const Lookup&);
732 // - a static member function |HP::match| that tests equality of key and
733 // lookup values:
735 // static bool match(const Key&, const Lookup&);
737 // Normally, Lookup = Key. In general, though, different values and types of
738 // values can be used to lookup and store. If a Lookup value |l| is not equal
739 // to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
740 // true. E.g.:
742 // mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
743 // if (!p) {
744 // assert(HP::match(k, l)); // must hold
745 // h.add(p, k);
746 // }
748 // A pointer hashing policy that uses HashGeneric() to create good hashes for
749 // pointers. Note that we don't shift out the lowest k bits because we don't
750 // want to assume anything about the alignment of the pointers.
751 template <typename Key>
752 struct PointerHasher {
753 using Lookup = Key;
755 static HashNumber hash(const Lookup& aLookup) {
756 size_t word = reinterpret_cast<size_t>(aLookup);
757 return HashGeneric(word);
760 static bool match(const Key& aKey, const Lookup& aLookup) {
761 return aKey == aLookup;
764 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
767 // The default hash policy, which only works with integers.
768 template <class Key, typename>
769 struct DefaultHasher {
770 using Lookup = Key;
772 static HashNumber hash(const Lookup& aLookup) {
773 // Just convert the integer to a HashNumber and use that as is. (This
774 // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
775 // subsequently called on the value to improve the distribution.
776 return aLookup;
779 static bool match(const Key& aKey, const Lookup& aLookup) {
780 // Use builtin or overloaded operator==.
781 return aKey == aLookup;
784 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
787 // A DefaultHasher specialization for enums.
788 template <class T>
789 struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
790 using Key = T;
791 using Lookup = Key;
793 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
795 static bool match(const Key& aKey, const Lookup& aLookup) {
796 // Use builtin or overloaded operator==.
797 return aKey == static_cast<Key>(aLookup);
800 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
803 // A DefaultHasher specialization for pointers.
804 template <class T>
805 struct DefaultHasher<T*> : PointerHasher<T*> {};
807 // A DefaultHasher specialization for mozilla::UniquePtr.
808 template <class T, class D>
809 struct DefaultHasher<UniquePtr<T, D>> {
810 using Key = UniquePtr<T, D>;
811 using Lookup = Key;
812 using PtrHasher = PointerHasher<T*>;
814 static HashNumber hash(const Lookup& aLookup) {
815 return PtrHasher::hash(aLookup.get());
818 static bool match(const Key& aKey, const Lookup& aLookup) {
819 return PtrHasher::match(aKey.get(), aLookup.get());
822 static void rekey(UniquePtr<T, D>& aKey, UniquePtr<T, D>&& aNewKey) {
823 aKey = std::move(aNewKey);
827 // A DefaultHasher specialization for doubles.
828 template <>
829 struct DefaultHasher<double> {
830 using Key = double;
831 using Lookup = Key;
833 static HashNumber hash(const Lookup& aLookup) {
834 // Just xor the high bits with the low bits, and then treat the bits of the
835 // result as a uint32_t.
836 static_assert(sizeof(HashNumber) == 4,
837 "subsequent code assumes a four-byte hash");
838 uint64_t u = BitwiseCast<uint64_t>(aLookup);
839 return HashNumber(u ^ (u >> 32));
842 static bool match(const Key& aKey, const Lookup& aLookup) {
843 return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
847 // A DefaultHasher specialization for floats.
848 template <>
849 struct DefaultHasher<float> {
850 using Key = float;
851 using Lookup = Key;
853 static HashNumber hash(const Lookup& aLookup) {
854 // Just use the value as if its bits form an integer. ScrambleHashCode() is
855 // subsequently called on the value to improve the distribution.
856 static_assert(sizeof(HashNumber) == 4,
857 "subsequent code assumes a four-byte hash");
858 return HashNumber(BitwiseCast<uint32_t>(aLookup));
861 static bool match(const Key& aKey, const Lookup& aLookup) {
862 return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
866 // A hash policy for C strings.
867 struct CStringHasher {
868 using Key = const char*;
869 using Lookup = const char*;
871 static HashNumber hash(const Lookup& aLookup) { return HashString(aLookup); }
873 static bool match(const Key& aKey, const Lookup& aLookup) {
874 return strcmp(aKey, aLookup) == 0;
878 //---------------------------------------------------------------------------
879 // Fallible Hashing Interface
880 //---------------------------------------------------------------------------
882 // Most of the time generating a hash code is infallible, but sometimes it is
883 // necessary to generate hash codes on demand in a way that can fail. Specialize
884 // this class for your own hash policy to provide fallible hashing.
886 // This is used by MovableCellHasher to handle the fact that generating a unique
887 // ID for cell pointer may fail due to OOM.
889 // The default implementations of these methods delegate to the usual HashPolicy
890 // implementation and always succeed.
891 template <typename HashPolicy>
892 struct FallibleHashMethods {
893 // Return true if a hashcode is already available for its argument, and
894 // sets |aHashOut|. Once this succeeds for a specific argument it
895 // must continue to do so.
897 // Return false if a hashcode is not already available. This implies that any
898 // lookup must fail, as the hash code would have to have been successfully
899 // created on insertion.
900 template <typename Lookup>
901 static bool maybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
902 *aHashOut = HashPolicy::hash(aLookup);
903 return true;
906 // Fallible method to ensure a hashcode exists for its argument and create one
907 // if not. Sets |aHashOut| to the hashcode and retuns true on success. Returns
908 // false on error, e.g. out of memory.
909 template <typename Lookup>
910 static bool ensureHash(Lookup&& aLookup, HashNumber* aHashOut) {
911 *aHashOut = HashPolicy::hash(aLookup);
912 return true;
916 template <typename HashPolicy, typename Lookup>
917 static bool MaybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
918 return FallibleHashMethods<typename HashPolicy::Base>::maybeGetHash(
919 std::forward<Lookup>(aLookup), aHashOut);
922 template <typename HashPolicy, typename Lookup>
923 static bool EnsureHash(Lookup&& aLookup, HashNumber* aHashOut) {
924 return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
925 std::forward<Lookup>(aLookup), aHashOut);
928 //---------------------------------------------------------------------------
929 // Implementation Details (HashMapEntry, HashTableEntry, HashTable)
930 //---------------------------------------------------------------------------
932 // Both HashMap and HashSet are implemented by a single HashTable that is even
933 // more heavily parameterized than the other two. This leaves HashTable gnarly
934 // and extremely coupled to HashMap and HashSet; thus code should not use
935 // HashTable directly.
937 template <class Key, class Value>
938 class HashMapEntry {
939 Key key_;
940 Value value_;
942 template <class, class, class>
943 friend class detail::HashTable;
944 template <class>
945 friend class detail::HashTableEntry;
946 template <class, class, class, class>
947 friend class HashMap;
949 public:
950 template <typename KeyInput, typename ValueInput>
951 HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
952 : key_(std::forward<KeyInput>(aKey)),
953 value_(std::forward<ValueInput>(aValue)) {}
955 HashMapEntry(HashMapEntry&& aRhs) = default;
956 HashMapEntry& operator=(HashMapEntry&& aRhs) = default;
958 using KeyType = Key;
959 using ValueType = Value;
961 const Key& key() const { return key_; }
963 // Use this method with caution! If the key is changed such that its hash
964 // value also changes, the map will be left in an invalid state.
965 Key& mutableKey() { return key_; }
967 const Value& value() const { return value_; }
968 Value& value() { return value_; }
970 private:
971 HashMapEntry(const HashMapEntry&) = delete;
972 void operator=(const HashMapEntry&) = delete;
975 namespace detail {
977 template <class T, class HashPolicy, class AllocPolicy>
978 class HashTable;
980 template <typename T>
981 class EntrySlot;
983 template <typename T>
984 class HashTableEntry {
985 private:
986 using NonConstT = std::remove_const_t<T>;
988 // Instead of having a hash table entry store that looks like this:
990 // +--------+--------+--------+--------+
991 // | entry0 | entry1 | .... | entryN |
992 // +--------+--------+--------+--------+
994 // where the entries contained their cached hash code, we're going to lay out
995 // the entry store thusly:
997 // +-------+-------+-------+-------+--------+--------+--------+--------+
998 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
999 // +-------+-------+-------+-------+--------+--------+--------+--------+
1001 // with all the cached hashes prior to the actual entries themselves.
1003 // We do this because implementing the first strategy requires us to make
1004 // HashTableEntry look roughly like:
1006 // template <typename T>
1007 // class HashTableEntry {
1008 // HashNumber mKeyHash;
1009 // T mValue;
1010 // };
1012 // The problem with this setup is that, depending on the layout of `T`, there
1013 // may be platform ABI-mandated padding between `mKeyHash` and the first
1014 // member of `T`. This ABI-mandated padding is wasted space, and can be
1015 // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
1016 // In such cases, we're throwing away a quarter of our entry store on padding,
1017 // which is undesirable.
1019 // The second layout above, namely:
1021 // +-------+-------+-------+-------+--------+--------+--------+--------+
1022 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
1023 // +-------+-------+-------+-------+--------+--------+--------+--------+
1025 // means there is no wasted space between the hashes themselves, and no wasted
1026 // space between the entries themselves. However, we would also like there to
1027 // be no gap between the last hash and the first entry. The memory allocator
1028 // guarantees the alignment of the start of the hashes. The use of a
1029 // power-of-two capacity of at least 4 guarantees that the alignment of the
1030 // *end* of the hash array is no less than the alignment of the start.
1031 // Finally, the static_asserts here guarantee that the entries themselves
1032 // don't need to be any more aligned than the alignment of the entry store
1033 // itself.
1035 // This assertion is safe for 32-bit builds because on both Windows and Linux
1036 // (including Android), the minimum alignment for allocations larger than 8
1037 // bytes is 8 bytes, and the actual data for entries in our entry store is
1038 // guaranteed to have that alignment as well, thanks to the power-of-two
1039 // number of cached hash values stored prior to the entry data.
1041 // The allocation policy must allocate a table with at least this much
1042 // alignment.
1043 static constexpr size_t kMinimumAlignment = 8;
1045 static_assert(alignof(HashNumber) <= kMinimumAlignment,
1046 "[N*2 hashes, N*2 T values] allocation's alignment must be "
1047 "enough to align each hash");
1048 static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
1049 "subsequent N*2 T values must not require more than an even "
1050 "number of HashNumbers provides");
1052 static const HashNumber sFreeKey = 0;
1053 static const HashNumber sRemovedKey = 1;
1054 static const HashNumber sCollisionBit = 1;
1056 alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];
1058 private:
1059 template <class, class, class>
1060 friend class HashTable;
1061 template <typename>
1062 friend class EntrySlot;
1064 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
1065 // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
1066 // through |void*|. Placing the latter cast in these separate functions
1067 // breaks the chain such that affected GCC versions no longer warn/error.
1068 void* rawValuePtr() { return mValueData; }
1070 static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }
1072 HashTableEntry(const HashTableEntry&) = delete;
1073 void operator=(const HashTableEntry&) = delete;
1075 NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }
1077 void destroyStoredT() {
1078 NonConstT* ptr = valuePtr();
1079 ptr->~T();
1080 MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr));
1083 public:
1084 HashTableEntry() = default;
1086 ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this)); }
1088 void destroy() { destroyStoredT(); }
1090 void swap(HashTableEntry* aOther, bool aIsLive) {
1091 // This allows types to use Argument-Dependent-Lookup, and thus use a custom
1092 // std::swap, which is needed by types like JS::Heap and such.
1093 using std::swap;
1095 if (this == aOther) {
1096 return;
1098 if (aIsLive) {
1099 swap(*valuePtr(), *aOther->valuePtr());
1100 } else {
1101 *aOther->valuePtr() = std::move(*valuePtr());
1102 destroy();
1106 T& get() { return *valuePtr(); }
1108 NonConstT& getMutable() { return *valuePtr(); }
1111 // A slot represents a cached hash value and its associated entry stored
1112 // in the hash table. These two things are not stored in contiguous memory.
1113 template <class T>
1114 class EntrySlot {
1115 using NonConstT = std::remove_const_t<T>;
1117 using Entry = HashTableEntry<T>;
1119 Entry* mEntry;
1120 HashNumber* mKeyHash;
1122 template <class, class, class>
1123 friend class HashTable;
1125 EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
1126 : mEntry(aEntry), mKeyHash(aKeyHash) {}
1128 public:
1129 static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }
1131 EntrySlot(const EntrySlot&) = default;
1132 EntrySlot(EntrySlot&& aOther) = default;
1134 EntrySlot& operator=(const EntrySlot&) = default;
1135 EntrySlot& operator=(EntrySlot&&) = default;
1137 bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }
1139 bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }
1141 EntrySlot& operator++() {
1142 ++mEntry;
1143 ++mKeyHash;
1144 return *this;
1147 void destroy() { mEntry->destroy(); }
1149 void swap(EntrySlot& aOther) {
1150 mEntry->swap(aOther.mEntry, aOther.isLive());
1151 std::swap(*mKeyHash, *aOther.mKeyHash);
1154 T& get() const { return mEntry->get(); }
1156 NonConstT& getMutable() { return mEntry->getMutable(); }
1158 bool isFree() const { return *mKeyHash == Entry::sFreeKey; }
1160 void clearLive() {
1161 MOZ_ASSERT(isLive());
1162 *mKeyHash = Entry::sFreeKey;
1163 mEntry->destroyStoredT();
1166 void clear() {
1167 if (isLive()) {
1168 mEntry->destroyStoredT();
1170 MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry));
1171 *mKeyHash = Entry::sFreeKey;
1174 bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }
1176 void removeLive() {
1177 MOZ_ASSERT(isLive());
1178 *mKeyHash = Entry::sRemovedKey;
1179 mEntry->destroyStoredT();
1182 bool isLive() const { return isLiveHash(*mKeyHash); }
1184 void setCollision() {
1185 MOZ_ASSERT(isLive());
1186 *mKeyHash |= Entry::sCollisionBit;
1188 void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
1189 bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
1190 bool matchHash(HashNumber hn) {
1191 return (*mKeyHash & ~Entry::sCollisionBit) == hn;
1193 HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }
1195 template <typename... Args>
1196 void setLive(HashNumber aHashNumber, Args&&... aArgs) {
1197 MOZ_ASSERT(!isLive());
1198 *mKeyHash = aHashNumber;
1199 new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
1200 MOZ_ASSERT(isLive());
1203 Entry* toEntry() const { return mEntry; }
1206 template <class T, class HashPolicy, class AllocPolicy>
1207 class HashTable : private AllocPolicy {
1208 friend class mozilla::ReentrancyGuard;
1210 using NonConstT = std::remove_const_t<T>;
1211 using Key = typename HashPolicy::KeyType;
1212 using Lookup = typename HashPolicy::Lookup;
1214 public:
1215 using Entry = HashTableEntry<T>;
1216 using Slot = EntrySlot<T>;
1218 template <typename F>
1219 static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
1220 auto hashes = reinterpret_cast<HashNumber*>(aTable);
1221 auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
1222 Slot slot(entries, hashes);
1223 for (size_t i = 0; i < size_t(aCapacity); ++i) {
1224 f(slot);
1225 ++slot;
1229 // A nullable pointer to a hash table element. A Ptr |p| can be tested
1230 // either explicitly |if (p.found()) p->...| or using boolean conversion
1231 // |if (p) p->...|. Ptr objects must not be used after any mutating hash
1232 // table operations unless |generation()| is tested.
1233 class Ptr {
1234 friend class HashTable;
1236 Slot mSlot;
1237 #ifdef DEBUG
1238 const HashTable* mTable;
1239 Generation mGeneration;
1240 #endif
1242 protected:
1243 Ptr(Slot aSlot, const HashTable& aTable)
1244 : mSlot(aSlot)
1245 #ifdef DEBUG
1247 mTable(&aTable),
1248 mGeneration(aTable.generation())
1249 #endif
1253 // This constructor is used only by AddPtr() within lookupForAdd().
1254 explicit Ptr(const HashTable& aTable)
1255 : mSlot(nullptr, nullptr)
1256 #ifdef DEBUG
1258 mTable(&aTable),
1259 mGeneration(aTable.generation())
1260 #endif
1264 bool isValid() const { return !!mSlot.toEntry(); }
1266 public:
1267 Ptr()
1268 : mSlot(nullptr, nullptr)
1269 #ifdef DEBUG
1271 mTable(nullptr),
1272 mGeneration(0)
1273 #endif
1277 bool found() const {
1278 if (!isValid()) {
1279 return false;
1281 #ifdef DEBUG
1282 MOZ_ASSERT(mGeneration == mTable->generation());
1283 #endif
1284 return mSlot.isLive();
1287 explicit operator bool() const { return found(); }
1289 bool operator==(const Ptr& aRhs) const {
1290 MOZ_ASSERT(found() && aRhs.found());
1291 return mSlot == aRhs.mSlot;
1294 bool operator!=(const Ptr& aRhs) const {
1295 #ifdef DEBUG
1296 MOZ_ASSERT(mGeneration == mTable->generation());
1297 #endif
1298 return !(*this == aRhs);
1301 T& operator*() const {
1302 #ifdef DEBUG
1303 MOZ_ASSERT(found());
1304 MOZ_ASSERT(mGeneration == mTable->generation());
1305 #endif
1306 return mSlot.get();
1309 T* operator->() const {
1310 #ifdef DEBUG
1311 MOZ_ASSERT(found());
1312 MOZ_ASSERT(mGeneration == mTable->generation());
1313 #endif
1314 return &mSlot.get();
1318 // A Ptr that can be used to add a key after a failed lookup.
1319 class AddPtr : public Ptr {
1320 friend class HashTable;
1322 HashNumber mKeyHash;
1323 #ifdef DEBUG
1324 uint64_t mMutationCount;
1325 #endif
1327 AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
1328 : Ptr(aSlot, aTable),
1329 mKeyHash(aHashNumber)
1330 #ifdef DEBUG
1332 mMutationCount(aTable.mMutationCount)
1333 #endif
1337 // This constructor is used when lookupForAdd() is performed on a table
1338 // lacking entry storage; it leaves mSlot null but initializes everything
1339 // else.
1340 AddPtr(const HashTable& aTable, HashNumber aHashNumber)
1341 : Ptr(aTable),
1342 mKeyHash(aHashNumber)
1343 #ifdef DEBUG
1345 mMutationCount(aTable.mMutationCount)
1346 #endif
1348 MOZ_ASSERT(isLive());
1351 bool isLive() const { return isLiveHash(mKeyHash); }
1353 public:
1354 AddPtr() : mKeyHash(0) {}
1357 // A hash table iterator that (mostly) doesn't allow table modifications.
1358 // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
1359 // hash table operation unless the |generation()| is tested.
1360 class Iterator {
1361 void moveToNextLiveEntry() {
1362 while (++mCur < mEnd && !mCur.isLive()) {
1363 continue;
1367 protected:
1368 friend class HashTable;
1370 explicit Iterator(const HashTable& aTable)
1371 : mCur(aTable.slotForIndex(0)),
1372 mEnd(aTable.slotForIndex(aTable.capacity()))
1373 #ifdef DEBUG
1375 mTable(aTable),
1376 mMutationCount(aTable.mMutationCount),
1377 mGeneration(aTable.generation()),
1378 mValidEntry(true)
1379 #endif
1381 if (!done() && !mCur.isLive()) {
1382 moveToNextLiveEntry();
1386 Slot mCur;
1387 Slot mEnd;
1388 #ifdef DEBUG
1389 const HashTable& mTable;
1390 uint64_t mMutationCount;
1391 Generation mGeneration;
1392 bool mValidEntry;
1393 #endif
1395 public:
1396 bool done() const {
1397 MOZ_ASSERT(mGeneration == mTable.generation());
1398 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1399 return mCur == mEnd;
1402 T& get() const {
1403 MOZ_ASSERT(!done());
1404 MOZ_ASSERT(mValidEntry);
1405 MOZ_ASSERT(mGeneration == mTable.generation());
1406 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1407 return mCur.get();
1410 void next() {
1411 MOZ_ASSERT(!done());
1412 MOZ_ASSERT(mGeneration == mTable.generation());
1413 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1414 moveToNextLiveEntry();
1415 #ifdef DEBUG
1416 mValidEntry = true;
1417 #endif
1421 // A hash table iterator that permits modification, removal and rekeying.
1422 // Since rehashing when elements were removed during enumeration would be
1423 // bad, it is postponed until the ModIterator is destructed. Since the
1424 // ModIterator's destructor touches the hash table, the user must ensure
1425 // that the hash table is still alive when the destructor runs.
1426 class ModIterator : public Iterator {
1427 friend class HashTable;
1429 HashTable& mTable;
1430 bool mRekeyed;
1431 bool mRemoved;
1433 // ModIterator is movable but not copyable.
1434 ModIterator(const ModIterator&) = delete;
1435 void operator=(const ModIterator&) = delete;
1437 protected:
1438 explicit ModIterator(HashTable& aTable)
1439 : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}
1441 public:
1442 MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
1443 : Iterator(aOther),
1444 mTable(aOther.mTable),
1445 mRekeyed(aOther.mRekeyed),
1446 mRemoved(aOther.mRemoved) {
1447 aOther.mRekeyed = false;
1448 aOther.mRemoved = false;
1451 // Removes the current element from the table, leaving |get()|
1452 // invalid until the next call to |next()|.
1453 void remove() {
1454 mTable.remove(this->mCur);
1455 mRemoved = true;
1456 #ifdef DEBUG
1457 this->mValidEntry = false;
1458 this->mMutationCount = mTable.mMutationCount;
1459 #endif
1462 NonConstT& getMutable() {
1463 MOZ_ASSERT(!this->done());
1464 MOZ_ASSERT(this->mValidEntry);
1465 MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation());
1466 MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount);
1467 return this->mCur.getMutable();
1470 // Removes the current element and re-inserts it into the table with
1471 // a new key at the new Lookup position. |get()| is invalid after
1472 // this operation until the next call to |next()|.
1473 void rekey(const Lookup& l, const Key& k) {
1474 MOZ_ASSERT(&k != &HashPolicy::getKey(this->mCur.get()));
1475 Ptr p(this->mCur, mTable);
1476 mTable.rekeyWithoutRehash(p, l, k);
1477 mRekeyed = true;
1478 #ifdef DEBUG
1479 this->mValidEntry = false;
1480 this->mMutationCount = mTable.mMutationCount;
1481 #endif
1484 void rekey(const Key& k) { rekey(k, k); }
1486 // Potentially rehashes the table.
1487 ~ModIterator() {
1488 if (mRekeyed) {
1489 mTable.mGen++;
1490 mTable.infallibleRehashIfOverloaded();
1493 if (mRemoved) {
1494 mTable.compact();
1499 // Range is similar to Iterator, but uses different terminology.
1500 class Range {
1501 friend class HashTable;
1503 Iterator mIter;
1505 protected:
1506 explicit Range(const HashTable& table) : mIter(table) {}
1508 public:
1509 bool empty() const { return mIter.done(); }
1511 T& front() const { return mIter.get(); }
1513 void popFront() { return mIter.next(); }
1516 // Enum is similar to ModIterator, but uses different terminology.
1517 class Enum {
1518 ModIterator mIter;
1520 // Enum is movable but not copyable.
1521 Enum(const Enum&) = delete;
1522 void operator=(const Enum&) = delete;
1524 public:
1525 template <class Map>
1526 explicit Enum(Map& map) : mIter(map.mImpl) {}
1528 MOZ_IMPLICIT Enum(Enum&& other) : mIter(std::move(other.mIter)) {}
1530 bool empty() const { return mIter.done(); }
1532 T& front() const { return mIter.get(); }
1534 void popFront() { return mIter.next(); }
1536 void removeFront() { mIter.remove(); }
1538 NonConstT& mutableFront() { return mIter.getMutable(); }
1540 void rekeyFront(const Lookup& aLookup, const Key& aKey) {
1541 mIter.rekey(aLookup, aKey);
1544 void rekeyFront(const Key& aKey) { mIter.rekey(aKey); }
1547 // HashTable is movable
1548 HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
1549 HashTable& operator=(HashTable&& aRhs) {
1550 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
1551 if (mTable) {
1552 destroyTable(*this, mTable, capacity());
1554 AllocPolicy::operator=(std::move(aRhs));
1555 moveFrom(aRhs);
1556 return *this;
1559 private:
1560 void moveFrom(HashTable& aRhs) {
1561 mGen = aRhs.mGen;
1562 mHashShift = aRhs.mHashShift;
1563 mTable = aRhs.mTable;
1564 mEntryCount = aRhs.mEntryCount;
1565 mRemovedCount = aRhs.mRemovedCount;
1566 #ifdef DEBUG
1567 mMutationCount = aRhs.mMutationCount;
1568 mEntered = aRhs.mEntered;
1569 #endif
1570 aRhs.mTable = nullptr;
1571 aRhs.clearAndCompact();
1574 // HashTable is not copyable or assignable
1575 HashTable(const HashTable&) = delete;
1576 void operator=(const HashTable&) = delete;
1578 static const uint32_t CAP_BITS = 30;
1580 public:
1581 uint64_t mGen : 56; // entry storage generation number
1582 uint64_t mHashShift : 8; // multiplicative hash shift
1583 char* mTable; // entry storage
1584 uint32_t mEntryCount; // number of entries in mTable
1585 uint32_t mRemovedCount; // removed entry sentinels in mTable
1587 #ifdef DEBUG
1588 uint64_t mMutationCount;
1589 mutable bool mEntered;
1590 #endif
1592 // The default initial capacity is 32 (enough to hold 16 elements), but it
1593 // can be as low as 4.
1594 static const uint32_t sDefaultLen = 16;
1595 static const uint32_t sMinCapacity = 4;
1596 // See the comments in HashTableEntry about this value.
1597 static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
1598 static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
1599 static const uint32_t sMaxCapacity = 1u << CAP_BITS;
1601 // Hash-table alpha is conceptually a fraction, but to avoid floating-point
1602 // math we implement it as a ratio of integers.
1603 static const uint8_t sAlphaDenominator = 4;
1604 static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4
1605 static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4
1607 static const HashNumber sFreeKey = Entry::sFreeKey;
1608 static const HashNumber sRemovedKey = Entry::sRemovedKey;
1609 static const HashNumber sCollisionBit = Entry::sCollisionBit;
1611 static uint32_t bestCapacity(uint32_t aLen) {
1612 static_assert(
1613 (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
1614 "multiplication in numerator below could overflow");
1615 static_assert(
1616 sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator,
1617 "numerator calculation below could potentially overflow");
1619 // Callers should ensure this is true.
1620 MOZ_ASSERT(aLen <= sMaxInit);
1622 // Compute the smallest capacity allowing |aLen| elements to be
1623 // inserted without rehashing: ceil(aLen / max-alpha). (Ceiling
1624 // integral division: <http://stackoverflow.com/a/2745086>.)
1625 uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
1626 sMaxAlphaNumerator;
1627 capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);
1629 MOZ_ASSERT(capacity >= aLen);
1630 MOZ_ASSERT(capacity <= sMaxCapacity);
1632 return capacity;
1635 static uint32_t hashShift(uint32_t aLen) {
1636 // Reject all lengths whose initial computed capacity would exceed
1637 // sMaxCapacity. Round that maximum aLen down to the nearest power of two
1638 // for speedier code.
1639 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
1640 MOZ_CRASH("initial length is too large");
1643 return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
1646 static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }
1648 static HashNumber prepareHash(HashNumber aInputHash) {
1649 HashNumber keyHash = ScrambleHashCode(aInputHash);
1651 // Avoid reserved hash codes.
1652 if (!isLiveHash(keyHash)) {
1653 keyHash -= (sRemovedKey + 1);
1655 return keyHash & ~sCollisionBit;
1658 enum FailureBehavior { DontReportFailure = false, ReportFailure = true };
1660 // Fake a struct that we're going to alloc. See the comments in
1661 // HashTableEntry about how the table is laid out, and why it's safe.
1662 struct FakeSlot {
1663 unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
1666 static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
1667 FailureBehavior aReportFailure = ReportFailure) {
1668 FakeSlot* fake =
1669 aReportFailure
1670 ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
1671 : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);
1673 MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==
1676 char* table = reinterpret_cast<char*>(fake);
1677 if (table) {
1678 forEachSlot(table, aCapacity, [&](Slot& slot) {
1679 *slot.mKeyHash = sFreeKey;
1680 new (KnownNotNull, slot.toEntry()) Entry();
1683 return table;
1686 static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1687 uint32_t aCapacity) {
1688 forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
1689 if (slot.isLive()) {
1690 slot.toEntry()->destroyStoredT();
1693 freeTable(aAllocPolicy, aOldTable, aCapacity);
1696 static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1697 uint32_t aCapacity) {
1698 FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
1699 aAllocPolicy.free_(fake, aCapacity);
1702 public:
1703 HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
1704 : AllocPolicy(std::move(aAllocPolicy)),
1705 mGen(0),
1706 mHashShift(hashShift(aLen)),
1707 mTable(nullptr),
1708 mEntryCount(0),
1709 mRemovedCount(0)
1710 #ifdef DEBUG
1712 mMutationCount(0),
1713 mEntered(false)
1714 #endif
1718 explicit HashTable(AllocPolicy aAllocPolicy)
1719 : HashTable(aAllocPolicy, sDefaultLen) {}
1721 ~HashTable() {
1722 if (mTable) {
1723 destroyTable(*this, mTable, capacity());
1727 private:
1728 HashNumber hash1(HashNumber aHash0) const { return aHash0 >> mHashShift; }
1730 struct DoubleHash {
1731 HashNumber mHash2;
1732 HashNumber mSizeMask;
1735 DoubleHash hash2(HashNumber aCurKeyHash) const {
1736 uint32_t sizeLog2 = kHashNumberBits - mHashShift;
1737 DoubleHash dh = {((aCurKeyHash << sizeLog2) >> mHashShift) | 1,
1738 (HashNumber(1) << sizeLog2) - 1};
1739 return dh;
1742 static HashNumber applyDoubleHash(HashNumber aHash1,
1743 const DoubleHash& aDoubleHash) {
1744 return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
1747 static MOZ_ALWAYS_INLINE bool match(T& aEntry, const Lookup& aLookup) {
1748 return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
1751 enum LookupReason { ForNonAdd, ForAdd };
1753 Slot slotForIndex(HashNumber aIndex) const {
1754 auto hashes = reinterpret_cast<HashNumber*>(mTable);
1755 auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
1756 return Slot(&entries[aIndex], &hashes[aIndex]);
1759 // Warning: in order for readonlyThreadsafeLookup() to be safe this
1760 // function must not modify the table in any way when Reason==ForNonAdd.
1761 template <LookupReason Reason>
1762 MOZ_ALWAYS_INLINE Slot lookup(const Lookup& aLookup,
1763 HashNumber aKeyHash) const {
1764 MOZ_ASSERT(isLiveHash(aKeyHash));
1765 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1766 MOZ_ASSERT(mTable);
1768 // Compute the primary hash address.
1769 HashNumber h1 = hash1(aKeyHash);
1770 Slot slot = slotForIndex(h1);
1772 // Miss: return space for a new entry.
1773 if (slot.isFree()) {
1774 return slot;
1777 // Hit: return entry.
1778 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1779 return slot;
1782 // Collision: double hash.
1783 DoubleHash dh = hash2(aKeyHash);
1785 // Save the first removed entry pointer so we can recycle later.
1786 Maybe<Slot> firstRemoved;
1788 while (true) {
1789 if (Reason == ForAdd && !firstRemoved) {
1790 if (MOZ_UNLIKELY(slot.isRemoved())) {
1791 firstRemoved.emplace(slot);
1792 } else {
1793 slot.setCollision();
1797 h1 = applyDoubleHash(h1, dh);
1799 slot = slotForIndex(h1);
1800 if (slot.isFree()) {
1801 return firstRemoved.refOr(slot);
1804 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1805 return slot;
1810 // This is a copy of lookup() hardcoded to the assumptions:
1811 // 1. the lookup is for an add;
1812 // 2. the key, whose |keyHash| has been passed, is not in the table.
1813 Slot findNonLiveSlot(HashNumber aKeyHash) {
1814 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1815 MOZ_ASSERT(mTable);
1817 // We assume 'aKeyHash' has already been distributed.
1819 // Compute the primary hash address.
1820 HashNumber h1 = hash1(aKeyHash);
1821 Slot slot = slotForIndex(h1);
1823 // Miss: return space for a new entry.
1824 if (!slot.isLive()) {
1825 return slot;
1828 // Collision: double hash.
1829 DoubleHash dh = hash2(aKeyHash);
1831 while (true) {
1832 slot.setCollision();
1834 h1 = applyDoubleHash(h1, dh);
1836 slot = slotForIndex(h1);
1837 if (!slot.isLive()) {
1838 return slot;
1843 enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };
1845 RebuildStatus changeTableSize(
1846 uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
1847 MOZ_ASSERT(IsPowerOfTwo(newCapacity));
1848 MOZ_ASSERT(!!mTable == !!capacity());
1850 // Look, but don't touch, until we succeed in getting new entry store.
1851 char* oldTable = mTable;
1852 uint32_t oldCapacity = capacity();
1853 uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);
1855 if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) {
1856 if (aReportFailure) {
1857 this->reportAllocOverflow();
1859 return RehashFailed;
1862 char* newTable = createTable(*this, newCapacity, aReportFailure);
1863 if (!newTable) {
1864 return RehashFailed;
1867 // We can't fail from here on, so update table parameters.
1868 mHashShift = kHashNumberBits - newLog2;
1869 mRemovedCount = 0;
1870 mGen++;
1871 mTable = newTable;
1873 // Copy only live entries, leaving removed ones behind.
1874 forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
1875 if (slot.isLive()) {
1876 HashNumber hn = slot.getKeyHash();
1877 findNonLiveSlot(hn).setLive(
1878 hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
1881 slot.clear();
1884 // All entries have been destroyed, no need to destroyTable.
1885 freeTable(*this, oldTable, oldCapacity);
1886 return Rehashed;
1889 RebuildStatus rehashIfOverloaded(
1890 FailureBehavior aReportFailure = ReportFailure) {
1891 static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator,
1892 "multiplication below could overflow");
1894 // Note: if capacity() is zero, this will always succeed, which is
1895 // what we want.
1896 bool overloaded = mEntryCount + mRemovedCount >=
1897 capacity() * sMaxAlphaNumerator / sAlphaDenominator;
1899 if (!overloaded) {
1900 return NotOverloaded;
1903 // Succeed if a quarter or more of all entries are removed. Note that this
1904 // always succeeds if capacity() == 0 (i.e. entry storage has not been
1905 // allocated), which is what we want, because it means changeTableSize()
1906 // will allocate the requested capacity rather than doubling it.
1907 bool manyRemoved = mRemovedCount >= (capacity() >> 2);
1908 uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
1909 return changeTableSize(newCapacity, aReportFailure);
1912 void infallibleRehashIfOverloaded() {
1913 if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
1914 rehashTableInPlace();
1918 void remove(Slot& aSlot) {
1919 MOZ_ASSERT(mTable);
1921 if (aSlot.hasCollision()) {
1922 aSlot.removeLive();
1923 mRemovedCount++;
1924 } else {
1925 aSlot.clearLive();
1927 mEntryCount--;
1928 #ifdef DEBUG
1929 mMutationCount++;
1930 #endif
1933 void shrinkIfUnderloaded() {
1934 static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator,
1935 "multiplication below could overflow");
1936 bool underloaded =
1937 capacity() > sMinCapacity &&
1938 mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;
1940 if (underloaded) {
1941 (void)changeTableSize(capacity() / 2, DontReportFailure);
1945 // This is identical to changeTableSize(currentSize), but without requiring
1946 // a second table. We do this by recycling the collision bits to tell us if
1947 // the element is already inserted or still waiting to be inserted. Since
1948 // already-inserted elements win any conflicts, we get the same table as we
1949 // would have gotten through random insertion order.
1950 void rehashTableInPlace() {
1951 mRemovedCount = 0;
1952 mGen++;
1953 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
1954 for (uint32_t i = 0; i < capacity();) {
1955 Slot src = slotForIndex(i);
1957 if (!src.isLive() || src.hasCollision()) {
1958 ++i;
1959 continue;
1962 HashNumber keyHash = src.getKeyHash();
1963 HashNumber h1 = hash1(keyHash);
1964 DoubleHash dh = hash2(keyHash);
1965 Slot tgt = slotForIndex(h1);
1966 while (true) {
1967 if (!tgt.hasCollision()) {
1968 src.swap(tgt);
1969 tgt.setCollision();
1970 break;
1973 h1 = applyDoubleHash(h1, dh);
1974 tgt = slotForIndex(h1);
1978 // TODO: this algorithm leaves collision bits on *all* elements, even if
1979 // they are on no collision path. We have the option of setting the
1980 // collision bits correctly on a subsequent pass or skipping the rehash
1981 // unless we are totally filled with tombstones: benchmark to find out
1982 // which approach is best.
1985 // Prefer to use putNewInfallible; this function does not check
1986 // invariants.
1987 template <typename... Args>
1988 void putNewInfallibleInternal(HashNumber aKeyHash, Args&&... aArgs) {
1989 MOZ_ASSERT(mTable);
1991 Slot slot = findNonLiveSlot(aKeyHash);
1993 if (slot.isRemoved()) {
1994 mRemovedCount--;
1995 aKeyHash |= sCollisionBit;
1998 slot.setLive(aKeyHash, std::forward<Args>(aArgs)...);
1999 mEntryCount++;
2000 #ifdef DEBUG
2001 mMutationCount++;
2002 #endif
2005 public:
2006 void clear() {
2007 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
2008 mRemovedCount = 0;
2009 mEntryCount = 0;
2010 #ifdef DEBUG
2011 mMutationCount++;
2012 #endif
2015 // Resize the table down to the smallest capacity that doesn't overload the
2016 // table. Since we call shrinkIfUnderloaded() on every remove, you only need
2017 // to call this after a bulk removal of items done without calling remove().
2018 void compact() {
2019 if (empty()) {
2020 // Free the entry storage.
2021 freeTable(*this, mTable, capacity());
2022 mGen++;
2023 mHashShift = hashShift(0); // gives minimum capacity on regrowth
2024 mTable = nullptr;
2025 mRemovedCount = 0;
2026 return;
2029 uint32_t bestCapacity = this->bestCapacity(mEntryCount);
2030 MOZ_ASSERT(bestCapacity <= capacity());
2032 if (bestCapacity < capacity()) {
2033 (void)changeTableSize(bestCapacity, DontReportFailure);
2037 void clearAndCompact() {
2038 clear();
2039 compact();
2042 [[nodiscard]] bool reserve(uint32_t aLen) {
2043 if (aLen == 0) {
2044 return true;
2047 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
2048 return false;
2051 uint32_t bestCapacity = this->bestCapacity(aLen);
2052 if (bestCapacity <= capacity()) {
2053 return true; // Capacity is already sufficient.
2056 RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
2057 MOZ_ASSERT(status != NotOverloaded);
2058 return status != RehashFailed;
2061 Iterator iter() const { return Iterator(*this); }
2063 ModIterator modIter() { return ModIterator(*this); }
2065 Range all() const { return Range(*this); }
2067 bool empty() const { return mEntryCount == 0; }
2069 uint32_t count() const { return mEntryCount; }
2071 uint32_t rawCapacity() const { return 1u << (kHashNumberBits - mHashShift); }
2073 uint32_t capacity() const { return mTable ? rawCapacity() : 0; }
2075 Generation generation() const { return Generation(mGen); }
2077 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2078 return aMallocSizeOf(mTable);
2081 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2082 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
2085 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
2086 if (empty()) {
2087 return Ptr();
2090 HashNumber inputHash;
2091 if (!MaybeGetHash<HashPolicy>(aLookup, &inputHash)) {
2092 return Ptr();
2095 HashNumber keyHash = prepareHash(inputHash);
2096 return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
2099 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
2100 ReentrancyGuard g(*this);
2101 return readonlyThreadsafeLookup(aLookup);
2104 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
2105 ReentrancyGuard g(*this);
2107 HashNumber inputHash;
2108 if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
2109 return AddPtr();
2112 HashNumber keyHash = prepareHash(inputHash);
2114 if (!mTable) {
2115 return AddPtr(*this, keyHash);
2118 // Directly call the constructor in the return statement to avoid
2119 // excess copying when building with Visual Studio 2017.
2120 // See bug 1385181.
2121 return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
2124 template <typename... Args>
2125 [[nodiscard]] bool add(AddPtr& aPtr, Args&&... aArgs) {
2126 ReentrancyGuard g(*this);
2127 MOZ_ASSERT_IF(aPtr.isValid(), mTable);
2128 MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this);
2129 MOZ_ASSERT(!aPtr.found());
2130 MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit));
2132 // Check for error from ensureHash() here.
2133 if (!aPtr.isLive()) {
2134 return false;
2137 MOZ_ASSERT(aPtr.mGeneration == generation());
2138 #ifdef DEBUG
2139 MOZ_ASSERT(aPtr.mMutationCount == mMutationCount);
2140 #endif
2142 if (!aPtr.isValid()) {
2143 MOZ_ASSERT(!mTable && mEntryCount == 0);
2144 uint32_t newCapacity = rawCapacity();
2145 RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
2146 MOZ_ASSERT(status != NotOverloaded);
2147 if (status == RehashFailed) {
2148 return false;
2150 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2152 } else if (aPtr.mSlot.isRemoved()) {
2153 // Changing an entry from removed to live does not affect whether we are
2154 // overloaded and can be handled separately.
2155 if (!this->checkSimulatedOOM()) {
2156 return false;
2158 mRemovedCount--;
2159 aPtr.mKeyHash |= sCollisionBit;
2161 } else {
2162 // Preserve the validity of |aPtr.mSlot|.
2163 RebuildStatus status = rehashIfOverloaded();
2164 if (status == RehashFailed) {
2165 return false;
2167 if (status == NotOverloaded && !this->checkSimulatedOOM()) {
2168 return false;
2170 if (status == Rehashed) {
2171 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2175 aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
2176 mEntryCount++;
2177 #ifdef DEBUG
2178 mMutationCount++;
2179 aPtr.mGeneration = generation();
2180 aPtr.mMutationCount = mMutationCount;
2181 #endif
2182 return true;
2185 // Note: |aLookup| may reference pieces of arguments in |aArgs|, so this
2186 // function must take care not to use |aLookup| after moving |aArgs|.
2187 template <typename... Args>
2188 void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
2189 MOZ_ASSERT(!lookup(aLookup).found());
2190 ReentrancyGuard g(*this);
2191 HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
2192 putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
2195 // Note: |aLookup| may alias arguments in |aArgs|, so this function must take
2196 // care not to use |aLookup| after moving |aArgs|.
2197 template <typename... Args>
2198 [[nodiscard]] bool putNew(const Lookup& aLookup, Args&&... aArgs) {
2199 MOZ_ASSERT(!lookup(aLookup).found());
2200 ReentrancyGuard g(*this);
2201 if (!this->checkSimulatedOOM()) {
2202 return false;
2204 HashNumber inputHash;
2205 if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
2206 return false;
2208 HashNumber keyHash = prepareHash(inputHash);
2209 if (rehashIfOverloaded() == RehashFailed) {
2210 return false;
2212 putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
2213 return true;
2216 // Note: |aLookup| may be a reference pieces of arguments in |aArgs|, so this
2217 // function must take care not to use |aLookup| after moving |aArgs|.
2218 template <typename... Args>
2219 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
2220 Args&&... aArgs) {
2221 // Check for error from ensureHash() here.
2222 if (!aPtr.isLive()) {
2223 return false;
2225 #ifdef DEBUG
2226 aPtr.mGeneration = generation();
2227 aPtr.mMutationCount = mMutationCount;
2228 #endif
2229 if (mTable) {
2230 ReentrancyGuard g(*this);
2231 // Check that aLookup has not been destroyed.
2232 MOZ_ASSERT(prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash);
2233 aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
2234 if (aPtr.found()) {
2235 return true;
2237 } else {
2238 // Clear aPtr so it's invalid; add() will allocate storage and redo the
2239 // lookup.
2240 aPtr.mSlot = Slot(nullptr, nullptr);
2242 return add(aPtr, std::forward<Args>(aArgs)...);
2245 void remove(Ptr aPtr) {
2246 MOZ_ASSERT(mTable);
2247 ReentrancyGuard g(*this);
2248 MOZ_ASSERT(aPtr.found());
2249 MOZ_ASSERT(aPtr.mGeneration == generation());
2250 remove(aPtr.mSlot);
2251 shrinkIfUnderloaded();
2254 void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2255 MOZ_ASSERT(mTable);
2256 ReentrancyGuard g(*this);
2257 MOZ_ASSERT(aPtr.found());
2258 MOZ_ASSERT(aPtr.mGeneration == generation());
2259 typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
2260 HashPolicy::setKey(t, const_cast<Key&>(aKey));
2261 remove(aPtr.mSlot);
2262 HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
2263 putNewInfallibleInternal(keyHash, std::move(t));
2266 void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2267 rekeyWithoutRehash(aPtr, aLookup, aKey);
2268 infallibleRehashIfOverloaded();
2272 } // namespace detail
2273 } // namespace mozilla
2275 #endif /* mozilla_HashTable_h */