Bug 1700051: part 30) Narrow scope of `newOffset`. r=smaug
[gecko.git] / mfbt / HashTable.h
blobc841e84da38e7d7a3426f09cf35027ba3660b8a2
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. Does
214 // nothing if the map already has sufficient capacity.
215 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
217 // -- Lookups --------------------------------------------------------------
219 // Does the map contain a key/value matching |aLookup|?
220 bool has(const Lookup& aLookup) const {
221 return mImpl.lookup(aLookup).found();
224 // Return a Ptr indicating whether a key/value matching |aLookup| is
225 // present in the map. E.g.:
227 // using HM = HashMap<int,char>;
228 // HM h;
229 // if (HM::Ptr p = h.lookup(3)) {
230 // assert(p->key() == 3);
231 // char val = p->value();
232 // }
234 using Ptr = typename Impl::Ptr;
235 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
236 return mImpl.lookup(aLookup);
239 // Like lookup(), but does not assert if two threads call it at the same
240 // time. Only use this method when none of the threads will modify the map.
241 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
242 return mImpl.readonlyThreadsafeLookup(aLookup);
245 // -- Insertions -----------------------------------------------------------
247 // Overwrite existing value with |aValue|, or add it if not present. Returns
248 // false on OOM.
249 template <typename KeyInput, typename ValueInput>
250 [[nodiscard]] bool put(KeyInput&& aKey, ValueInput&& aValue) {
251 AddPtr p = lookupForAdd(aKey);
252 if (p) {
253 p->value() = std::forward<ValueInput>(aValue);
254 return true;
256 return add(p, std::forward<KeyInput>(aKey),
257 std::forward<ValueInput>(aValue));
260 // Like put(), but slightly faster. Must only be used when the given key is
261 // not already present. (In debug builds, assertions check this.)
262 template <typename KeyInput, typename ValueInput>
263 [[nodiscard]] bool putNew(KeyInput&& aKey, ValueInput&& aValue) {
264 return mImpl.putNew(aKey, std::forward<KeyInput>(aKey),
265 std::forward<ValueInput>(aValue));
268 template <typename KeyInput, typename ValueInput>
269 [[nodiscard]] bool putNew(const Lookup& aLookup, KeyInput&& aKey,
270 ValueInput&& aValue) {
271 return mImpl.putNew(aLookup, std::forward<KeyInput>(aKey),
272 std::forward<ValueInput>(aValue));
275 // Like putNew(), but should be only used when the table is known to be big
276 // enough for the insertion, and hashing cannot fail. Typically this is used
277 // to populate an empty map with known-unique keys after reserving space with
278 // reserve(), e.g.
280 // using HM = HashMap<int,char>;
281 // HM h;
282 // if (!h.reserve(3)) {
283 // MOZ_CRASH("OOM");
284 // }
285 // h.putNewInfallible(1, 'a'); // unique key
286 // h.putNewInfallible(2, 'b'); // unique key
287 // h.putNewInfallible(3, 'c'); // unique key
289 template <typename KeyInput, typename ValueInput>
290 void putNewInfallible(KeyInput&& aKey, ValueInput&& aValue) {
291 mImpl.putNewInfallible(aKey, std::forward<KeyInput>(aKey),
292 std::forward<ValueInput>(aValue));
295 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
296 // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using
297 // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new key/value. E.g.:
299 // using HM = HashMap<int,char>;
300 // HM h;
301 // HM::AddPtr p = h.lookupForAdd(3);
302 // if (!p) {
303 // if (!h.add(p, 3, 'a')) {
304 // return false;
305 // }
306 // }
307 // assert(p->key() == 3);
308 // char val = p->value();
310 // N.B. The caller must ensure that no mutating hash table operations occur
311 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
312 // key a second time, the caller may use the more efficient relookupOrAdd()
313 // method. This method reuses part of the hashing computation to more
314 // efficiently insert the key if it has not been added. For example, a
315 // mutation-handling version of the previous example:
317 // HM::AddPtr p = h.lookupForAdd(3);
318 // if (!p) {
319 // call_that_may_mutate_h();
320 // if (!h.relookupOrAdd(p, 3, 'a')) {
321 // return false;
322 // }
323 // }
324 // assert(p->key() == 3);
325 // char val = p->value();
327 using AddPtr = typename Impl::AddPtr;
328 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
329 return mImpl.lookupForAdd(aLookup);
332 // Add a key/value. Returns false on OOM.
333 template <typename KeyInput, typename ValueInput>
334 [[nodiscard]] bool add(AddPtr& aPtr, KeyInput&& aKey, ValueInput&& aValue) {
335 return mImpl.add(aPtr, std::forward<KeyInput>(aKey),
336 std::forward<ValueInput>(aValue));
339 // See the comment above lookupForAdd() for details.
340 template <typename KeyInput, typename ValueInput>
341 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, KeyInput&& aKey,
342 ValueInput&& aValue) {
343 return mImpl.relookupOrAdd(aPtr, aKey, std::forward<KeyInput>(aKey),
344 std::forward<ValueInput>(aValue));
347 // -- Removal --------------------------------------------------------------
349 // Lookup and remove the key/value matching |aLookup|, if present.
350 void remove(const Lookup& aLookup) {
351 if (Ptr p = lookup(aLookup)) {
352 remove(p);
356 // Remove a previously found key/value (assuming aPtr.found()). The map must
357 // not have been mutated in the interim.
358 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
360 // Remove all keys/values without changing the capacity.
361 void clear() { mImpl.clear(); }
363 // Like clear() followed by compact().
364 void clearAndCompact() { mImpl.clearAndCompact(); }
366 // -- Rekeying -------------------------------------------------------------
368 // Infallibly rekey one entry, if necessary. Requires that template
369 // parameters Key and HashPolicy::Lookup are the same type.
370 void rekeyIfMoved(const Key& aOldKey, const Key& aNewKey) {
371 if (aOldKey != aNewKey) {
372 rekeyAs(aOldKey, aNewKey, aNewKey);
376 // Infallibly rekey one entry if present, and return whether that happened.
377 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
378 const Key& aNewKey) {
379 if (Ptr p = lookup(aOldLookup)) {
380 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewKey);
381 return true;
383 return false;
386 // -- Iteration ------------------------------------------------------------
388 // |iter()| returns an Iterator:
390 // HashMap<int, char> h;
391 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
392 // char c = iter.get().value();
393 // }
395 using Iterator = typename Impl::Iterator;
396 Iterator iter() const { return mImpl.iter(); }
398 // |modIter()| returns a ModIterator:
400 // HashMap<int, char> h;
401 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
402 // if (iter.get().value() == 'l') {
403 // iter.remove();
404 // }
405 // }
407 // Table resize may occur in ModIterator's destructor.
408 using ModIterator = typename Impl::ModIterator;
409 ModIterator modIter() { return mImpl.modIter(); }
411 // These are similar to Iterator/ModIterator/iter(), but use different
412 // terminology.
413 using Range = typename Impl::Range;
414 using Enum = typename Impl::Enum;
415 Range all() const { return mImpl.all(); }
418 //---------------------------------------------------------------------------
419 // HashSet
420 //---------------------------------------------------------------------------
422 // HashSet is a fast hash-based set of values.
424 // Template parameter requirements:
425 // - T: movable, destructible, assignable.
426 // - HashPolicy: see the "Hash Policy" section below.
427 // - AllocPolicy: see AllocPolicy.h
429 // Note:
430 // - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by
431 // HashSet must not call back into the same HashSet object.
433 template <class T, class HashPolicy = DefaultHasher<T>,
434 class AllocPolicy = MallocAllocPolicy>
435 class HashSet {
436 // -- Implementation details -----------------------------------------------
438 // HashSet is not copyable or assignable.
439 HashSet(const HashSet& hs) = delete;
440 HashSet& operator=(const HashSet& hs) = delete;
442 struct SetHashPolicy : HashPolicy {
443 using Base = HashPolicy;
444 using KeyType = T;
446 static const KeyType& getKey(const T& aT) { return aT; }
448 static void setKey(T& aT, KeyType& aKey) { HashPolicy::rekey(aT, aKey); }
451 using Impl = detail::HashTable<const T, SetHashPolicy, AllocPolicy>;
452 Impl mImpl;
454 friend class Impl::Enum;
456 public:
457 using Lookup = typename HashPolicy::Lookup;
458 using Entry = T;
460 // -- Initialization -------------------------------------------------------
462 explicit HashSet(AllocPolicy aAllocPolicy = AllocPolicy(),
463 uint32_t aLen = Impl::sDefaultLen)
464 : mImpl(std::move(aAllocPolicy), aLen) {}
466 explicit HashSet(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
468 // HashSet is movable.
469 HashSet(HashSet&& aRhs) = default;
470 HashSet& operator=(HashSet&& aRhs) = default;
472 // -- Status and sizing ----------------------------------------------------
474 // The set's current generation.
475 Generation generation() const { return mImpl.generation(); }
477 // Is the set empty?
478 bool empty() const { return mImpl.empty(); }
480 // Number of elements in the set.
481 uint32_t count() const { return mImpl.count(); }
483 // Number of element slots in the set. Note: resize will happen well before
484 // count() == capacity().
485 uint32_t capacity() const { return mImpl.capacity(); }
487 // The size of the set's entry storage, in bytes. If the elements contain
488 // pointers to other heap blocks, you must iterate over the set and measure
489 // them separately; hence the "shallow" prefix.
490 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
491 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
493 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
494 return aMallocSizeOf(this) +
495 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
498 // Attempt to minimize the capacity(). If the table is empty, this will free
499 // the empty storage and upon regrowth it will be given the minimum capacity.
500 void compact() { mImpl.compact(); }
502 // Attempt to reserve enough space to fit at least |aLen| elements. Does
503 // nothing if the map already has sufficient capacity.
504 [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
506 // -- Lookups --------------------------------------------------------------
508 // Does the set contain an element matching |aLookup|?
509 bool has(const Lookup& aLookup) const {
510 return mImpl.lookup(aLookup).found();
513 // Return a Ptr indicating whether an element matching |aLookup| is present
514 // in the set. E.g.:
516 // using HS = HashSet<int>;
517 // HS h;
518 // if (HS::Ptr p = h.lookup(3)) {
519 // assert(*p == 3); // p acts like a pointer to int
520 // }
522 using Ptr = typename Impl::Ptr;
523 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
524 return mImpl.lookup(aLookup);
527 // Like lookup(), but does not assert if two threads call it at the same
528 // time. Only use this method when none of the threads will modify the set.
529 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
530 return mImpl.readonlyThreadsafeLookup(aLookup);
533 // -- Insertions -----------------------------------------------------------
535 // Add |aU| if it is not present already. Returns false on OOM.
536 template <typename U>
537 [[nodiscard]] bool put(U&& aU) {
538 AddPtr p = lookupForAdd(aU);
539 return p ? true : add(p, std::forward<U>(aU));
542 // Like put(), but slightly faster. Must only be used when the given element
543 // is not already present. (In debug builds, assertions check this.)
544 template <typename U>
545 [[nodiscard]] bool putNew(U&& aU) {
546 return mImpl.putNew(aU, std::forward<U>(aU));
549 // Like the other putNew(), but for when |Lookup| is different to |T|.
550 template <typename U>
551 [[nodiscard]] bool putNew(const Lookup& aLookup, U&& aU) {
552 return mImpl.putNew(aLookup, std::forward<U>(aU));
555 // Like putNew(), but should be only used when the table is known to be big
556 // enough for the insertion, and hashing cannot fail. Typically this is used
557 // to populate an empty set with known-unique elements after reserving space
558 // with reserve(), e.g.
560 // using HS = HashMap<int>;
561 // HS h;
562 // if (!h.reserve(3)) {
563 // MOZ_CRASH("OOM");
564 // }
565 // h.putNewInfallible(1); // unique element
566 // h.putNewInfallible(2); // unique element
567 // h.putNewInfallible(3); // unique element
569 template <typename U>
570 void putNewInfallible(const Lookup& aLookup, U&& aU) {
571 mImpl.putNewInfallible(aLookup, std::forward<U>(aU));
574 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
575 // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using
576 // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.:
578 // using HS = HashSet<int>;
579 // HS h;
580 // HS::AddPtr p = h.lookupForAdd(3);
581 // if (!p) {
582 // if (!h.add(p, 3)) {
583 // return false;
584 // }
585 // }
586 // assert(*p == 3); // p acts like a pointer to int
588 // N.B. The caller must ensure that no mutating hash table operations occur
589 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
590 // key a second time, the caller may use the more efficient relookupOrAdd()
591 // method. This method reuses part of the hashing computation to more
592 // efficiently insert the key if it has not been added. For example, a
593 // mutation-handling version of the previous example:
595 // HS::AddPtr p = h.lookupForAdd(3);
596 // if (!p) {
597 // call_that_may_mutate_h();
598 // if (!h.relookupOrAdd(p, 3, 3)) {
599 // return false;
600 // }
601 // }
602 // assert(*p == 3);
604 // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the
605 // entry |t|, where the caller ensures match(l,t).
606 using AddPtr = typename Impl::AddPtr;
607 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
608 return mImpl.lookupForAdd(aLookup);
611 // Add an element. Returns false on OOM.
612 template <typename U>
613 [[nodiscard]] bool add(AddPtr& aPtr, U&& aU) {
614 return mImpl.add(aPtr, std::forward<U>(aU));
617 // See the comment above lookupForAdd() for details.
618 template <typename U>
619 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
620 U&& aU) {
621 return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
624 // -- Removal --------------------------------------------------------------
626 // Lookup and remove the element matching |aLookup|, if present.
627 void remove(const Lookup& aLookup) {
628 if (Ptr p = lookup(aLookup)) {
629 remove(p);
633 // Remove a previously found element (assuming aPtr.found()). The set must
634 // not have been mutated in the interim.
635 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
637 // Remove all keys/values without changing the capacity.
638 void clear() { mImpl.clear(); }
640 // Like clear() followed by compact().
641 void clearAndCompact() { mImpl.clearAndCompact(); }
643 // -- Rekeying -------------------------------------------------------------
645 // Infallibly rekey one entry, if present. Requires that template parameters
646 // T and HashPolicy::Lookup are the same type.
647 void rekeyIfMoved(const Lookup& aOldValue, const T& aNewValue) {
648 if (aOldValue != aNewValue) {
649 rekeyAs(aOldValue, aNewValue, aNewValue);
653 // Infallibly rekey one entry if present, and return whether that happened.
654 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
655 const T& aNewValue) {
656 if (Ptr p = lookup(aOldLookup)) {
657 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewValue);
658 return true;
660 return false;
663 // Infallibly replace the current key at |aPtr| with an equivalent key.
664 // Specifically, both HashPolicy::hash and HashPolicy::match must return
665 // identical results for the new and old key when applied against all
666 // possible matching values.
667 void replaceKey(Ptr aPtr, const T& aNewValue) {
668 MOZ_ASSERT(aPtr.found());
669 MOZ_ASSERT(*aPtr != aNewValue);
670 MOZ_ASSERT(HashPolicy::hash(*aPtr) == HashPolicy::hash(aNewValue));
671 MOZ_ASSERT(HashPolicy::match(*aPtr, aNewValue));
672 const_cast<T&>(*aPtr) = aNewValue;
675 // -- Iteration ------------------------------------------------------------
677 // |iter()| returns an Iterator:
679 // HashSet<int> h;
680 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
681 // int i = iter.get();
682 // }
684 using Iterator = typename Impl::Iterator;
685 Iterator iter() const { return mImpl.iter(); }
687 // |modIter()| returns a ModIterator:
689 // HashSet<int> h;
690 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
691 // if (iter.get() == 42) {
692 // iter.remove();
693 // }
694 // }
696 // Table resize may occur in ModIterator's destructor.
697 using ModIterator = typename Impl::ModIterator;
698 ModIterator modIter() { return mImpl.modIter(); }
700 // These are similar to Iterator/ModIterator/iter(), but use different
701 // terminology.
702 using Range = typename Impl::Range;
703 using Enum = typename Impl::Enum;
704 Range all() const { return mImpl.all(); }
707 //---------------------------------------------------------------------------
708 // Hash Policy
709 //---------------------------------------------------------------------------
711 // A hash policy |HP| for a hash table with key-type |Key| must provide:
713 // - a type |HP::Lookup| to use to lookup table entries;
715 // - a static member function |HP::hash| that hashes lookup values:
717 // static mozilla::HashNumber hash(const Lookup&);
719 // - a static member function |HP::match| that tests equality of key and
720 // lookup values:
722 // static bool match(const Key&, const Lookup&);
724 // Normally, Lookup = Key. In general, though, different values and types of
725 // values can be used to lookup and store. If a Lookup value |l| is not equal
726 // to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
727 // true. E.g.:
729 // mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
730 // if (!p) {
731 // assert(HP::match(k, l)); // must hold
732 // h.add(p, k);
733 // }
735 // A pointer hashing policy that uses HashGeneric() to create good hashes for
736 // pointers. Note that we don't shift out the lowest k bits because we don't
737 // want to assume anything about the alignment of the pointers.
738 template <typename Key>
739 struct PointerHasher {
740 using Lookup = Key;
742 static HashNumber hash(const Lookup& aLookup) {
743 size_t word = reinterpret_cast<size_t>(aLookup);
744 return HashGeneric(word);
747 static bool match(const Key& aKey, const Lookup& aLookup) {
748 return aKey == aLookup;
751 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
754 // The default hash policy, which only works with integers.
755 template <class Key, typename>
756 struct DefaultHasher {
757 using Lookup = Key;
759 static HashNumber hash(const Lookup& aLookup) {
760 // Just convert the integer to a HashNumber and use that as is. (This
761 // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
762 // subsequently called on the value to improve the distribution.
763 return aLookup;
766 static bool match(const Key& aKey, const Lookup& aLookup) {
767 // Use builtin or overloaded operator==.
768 return aKey == aLookup;
771 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
774 // A DefaultHasher specialization for enums.
775 template <class T>
776 struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
777 using Key = T;
778 using Lookup = Key;
780 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
782 static bool match(const Key& aKey, const Lookup& aLookup) {
783 // Use builtin or overloaded operator==.
784 return aKey == static_cast<Key>(aLookup);
787 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
790 // A DefaultHasher specialization for pointers.
791 template <class T>
792 struct DefaultHasher<T*> : PointerHasher<T*> {};
794 // A DefaultHasher specialization for mozilla::UniquePtr.
795 template <class T, class D>
796 struct DefaultHasher<UniquePtr<T, D>> {
797 using Key = UniquePtr<T, D>;
798 using Lookup = Key;
799 using PtrHasher = PointerHasher<T*>;
801 static HashNumber hash(const Lookup& aLookup) {
802 return PtrHasher::hash(aLookup.get());
805 static bool match(const Key& aKey, const Lookup& aLookup) {
806 return PtrHasher::match(aKey.get(), aLookup.get());
809 static void rekey(UniquePtr<T, D>& aKey, UniquePtr<T, D>&& aNewKey) {
810 aKey = std::move(aNewKey);
814 // A DefaultHasher specialization for doubles.
815 template <>
816 struct DefaultHasher<double> {
817 using Key = double;
818 using Lookup = Key;
820 static HashNumber hash(const Lookup& aLookup) {
821 // Just xor the high bits with the low bits, and then treat the bits of the
822 // result as a uint32_t.
823 static_assert(sizeof(HashNumber) == 4,
824 "subsequent code assumes a four-byte hash");
825 uint64_t u = BitwiseCast<uint64_t>(aLookup);
826 return HashNumber(u ^ (u >> 32));
829 static bool match(const Key& aKey, const Lookup& aLookup) {
830 return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
834 // A DefaultHasher specialization for floats.
835 template <>
836 struct DefaultHasher<float> {
837 using Key = float;
838 using Lookup = Key;
840 static HashNumber hash(const Lookup& aLookup) {
841 // Just use the value as if its bits form an integer. ScrambleHashCode() is
842 // subsequently called on the value to improve the distribution.
843 static_assert(sizeof(HashNumber) == 4,
844 "subsequent code assumes a four-byte hash");
845 return HashNumber(BitwiseCast<uint32_t>(aLookup));
848 static bool match(const Key& aKey, const Lookup& aLookup) {
849 return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
853 // A hash policy for C strings.
854 struct CStringHasher {
855 using Key = const char*;
856 using Lookup = const char*;
858 static HashNumber hash(const Lookup& aLookup) { return HashString(aLookup); }
860 static bool match(const Key& aKey, const Lookup& aLookup) {
861 return strcmp(aKey, aLookup) == 0;
865 //---------------------------------------------------------------------------
866 // Fallible Hashing Interface
867 //---------------------------------------------------------------------------
869 // Most of the time generating a hash code is infallible so this class provides
870 // default methods that always succeed. Specialize this class for your own hash
871 // policy to provide fallible hashing.
873 // This is used by MovableCellHasher to handle the fact that generating a unique
874 // ID for cell pointer may fail due to OOM.
875 template <typename HashPolicy>
876 struct FallibleHashMethods {
877 // Return true if a hashcode is already available for its argument. Once
878 // this returns true for a specific argument it must continue to do so.
879 template <typename Lookup>
880 static bool hasHash(Lookup&& aLookup) {
881 return true;
884 // Fallible method to ensure a hashcode exists for its argument and create
885 // one if not. Returns false on error, e.g. out of memory.
886 template <typename Lookup>
887 static bool ensureHash(Lookup&& aLookup) {
888 return true;
892 template <typename HashPolicy, typename Lookup>
893 static bool HasHash(Lookup&& aLookup) {
894 return FallibleHashMethods<typename HashPolicy::Base>::hasHash(
895 std::forward<Lookup>(aLookup));
898 template <typename HashPolicy, typename Lookup>
899 static bool EnsureHash(Lookup&& aLookup) {
900 return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
901 std::forward<Lookup>(aLookup));
904 //---------------------------------------------------------------------------
905 // Implementation Details (HashMapEntry, HashTableEntry, HashTable)
906 //---------------------------------------------------------------------------
908 // Both HashMap and HashSet are implemented by a single HashTable that is even
909 // more heavily parameterized than the other two. This leaves HashTable gnarly
910 // and extremely coupled to HashMap and HashSet; thus code should not use
911 // HashTable directly.
913 template <class Key, class Value>
914 class HashMapEntry {
915 Key key_;
916 Value value_;
918 template <class, class, class>
919 friend class detail::HashTable;
920 template <class>
921 friend class detail::HashTableEntry;
922 template <class, class, class, class>
923 friend class HashMap;
925 public:
926 template <typename KeyInput, typename ValueInput>
927 HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
928 : key_(std::forward<KeyInput>(aKey)),
929 value_(std::forward<ValueInput>(aValue)) {}
931 HashMapEntry(HashMapEntry&& aRhs) = default;
932 HashMapEntry& operator=(HashMapEntry&& aRhs) = default;
934 using KeyType = Key;
935 using ValueType = Value;
937 const Key& key() const { return key_; }
939 // Use this method with caution! If the key is changed such that its hash
940 // value also changes, the map will be left in an invalid state.
941 Key& mutableKey() { return key_; }
943 const Value& value() const { return value_; }
944 Value& value() { return value_; }
946 private:
947 HashMapEntry(const HashMapEntry&) = delete;
948 void operator=(const HashMapEntry&) = delete;
951 namespace detail {
953 template <class T, class HashPolicy, class AllocPolicy>
954 class HashTable;
956 template <typename T>
957 class EntrySlot;
959 template <typename T>
960 class HashTableEntry {
961 private:
962 using NonConstT = std::remove_const_t<T>;
964 // Instead of having a hash table entry store that looks like this:
966 // +--------+--------+--------+--------+
967 // | entry0 | entry1 | .... | entryN |
968 // +--------+--------+--------+--------+
970 // where the entries contained their cached hash code, we're going to lay out
971 // the entry store thusly:
973 // +-------+-------+-------+-------+--------+--------+--------+--------+
974 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
975 // +-------+-------+-------+-------+--------+--------+--------+--------+
977 // with all the cached hashes prior to the actual entries themselves.
979 // We do this because implementing the first strategy requires us to make
980 // HashTableEntry look roughly like:
982 // template <typename T>
983 // class HashTableEntry {
984 // HashNumber mKeyHash;
985 // T mValue;
986 // };
988 // The problem with this setup is that, depending on the layout of `T`, there
989 // may be platform ABI-mandated padding between `mKeyHash` and the first
990 // member of `T`. This ABI-mandated padding is wasted space, and can be
991 // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
992 // In such cases, we're throwing away a quarter of our entry store on padding,
993 // which is undesirable.
995 // The second layout above, namely:
997 // +-------+-------+-------+-------+--------+--------+--------+--------+
998 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
999 // +-------+-------+-------+-------+--------+--------+--------+--------+
1001 // means there is no wasted space between the hashes themselves, and no wasted
1002 // space between the entries themselves. However, we would also like there to
1003 // be no gap between the last hash and the first entry. The memory allocator
1004 // guarantees the alignment of the start of the hashes. The use of a
1005 // power-of-two capacity of at least 4 guarantees that the alignment of the
1006 // *end* of the hash array is no less than the alignment of the start.
1007 // Finally, the static_asserts here guarantee that the entries themselves
1008 // don't need to be any more aligned than the alignment of the entry store
1009 // itself.
1011 // This assertion is safe for 32-bit builds because on both Windows and Linux
1012 // (including Android), the minimum alignment for allocations larger than 8
1013 // bytes is 8 bytes, and the actual data for entries in our entry store is
1014 // guaranteed to have that alignment as well, thanks to the power-of-two
1015 // number of cached hash values stored prior to the entry data.
1017 // The allocation policy must allocate a table with at least this much
1018 // alignment.
1019 static constexpr size_t kMinimumAlignment = 8;
1021 static_assert(alignof(HashNumber) <= kMinimumAlignment,
1022 "[N*2 hashes, N*2 T values] allocation's alignment must be "
1023 "enough to align each hash");
1024 static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
1025 "subsequent N*2 T values must not require more than an even "
1026 "number of HashNumbers provides");
1028 static const HashNumber sFreeKey = 0;
1029 static const HashNumber sRemovedKey = 1;
1030 static const HashNumber sCollisionBit = 1;
1032 alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];
1034 private:
1035 template <class, class, class>
1036 friend class HashTable;
1037 template <typename>
1038 friend class EntrySlot;
1040 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
1041 // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
1042 // through |void*|. Placing the latter cast in these separate functions
1043 // breaks the chain such that affected GCC versions no longer warn/error.
1044 void* rawValuePtr() { return mValueData; }
1046 static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }
1048 HashTableEntry(const HashTableEntry&) = delete;
1049 void operator=(const HashTableEntry&) = delete;
1051 NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }
1053 void destroyStoredT() {
1054 NonConstT* ptr = valuePtr();
1055 ptr->~T();
1056 MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr));
1059 public:
1060 HashTableEntry() = default;
1062 ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this)); }
1064 void destroy() { destroyStoredT(); }
1066 void swap(HashTableEntry* aOther, bool aIsLive) {
1067 // This allows types to use Argument-Dependent-Lookup, and thus use a custom
1068 // std::swap, which is needed by types like JS::Heap and such.
1069 using std::swap;
1071 if (this == aOther) {
1072 return;
1074 if (aIsLive) {
1075 swap(*valuePtr(), *aOther->valuePtr());
1076 } else {
1077 *aOther->valuePtr() = std::move(*valuePtr());
1078 destroy();
1082 T& get() { return *valuePtr(); }
1084 NonConstT& getMutable() { return *valuePtr(); }
1087 // A slot represents a cached hash value and its associated entry stored
1088 // in the hash table. These two things are not stored in contiguous memory.
1089 template <class T>
1090 class EntrySlot {
1091 using NonConstT = std::remove_const_t<T>;
1093 using Entry = HashTableEntry<T>;
1095 Entry* mEntry;
1096 HashNumber* mKeyHash;
1098 template <class, class, class>
1099 friend class HashTable;
1101 EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
1102 : mEntry(aEntry), mKeyHash(aKeyHash) {}
1104 public:
1105 static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }
1107 EntrySlot(const EntrySlot&) = default;
1108 EntrySlot(EntrySlot&& aOther) = default;
1110 EntrySlot& operator=(const EntrySlot&) = default;
1111 EntrySlot& operator=(EntrySlot&&) = default;
1113 bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }
1115 bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }
1117 EntrySlot& operator++() {
1118 ++mEntry;
1119 ++mKeyHash;
1120 return *this;
1123 void destroy() { mEntry->destroy(); }
1125 void swap(EntrySlot& aOther) {
1126 mEntry->swap(aOther.mEntry, aOther.isLive());
1127 std::swap(*mKeyHash, *aOther.mKeyHash);
1130 T& get() const { return mEntry->get(); }
1132 NonConstT& getMutable() { return mEntry->getMutable(); }
1134 bool isFree() const { return *mKeyHash == Entry::sFreeKey; }
1136 void clearLive() {
1137 MOZ_ASSERT(isLive());
1138 *mKeyHash = Entry::sFreeKey;
1139 mEntry->destroyStoredT();
1142 void clear() {
1143 if (isLive()) {
1144 mEntry->destroyStoredT();
1146 MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry));
1147 *mKeyHash = Entry::sFreeKey;
1150 bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }
1152 void removeLive() {
1153 MOZ_ASSERT(isLive());
1154 *mKeyHash = Entry::sRemovedKey;
1155 mEntry->destroyStoredT();
1158 bool isLive() const { return isLiveHash(*mKeyHash); }
1160 void setCollision() {
1161 MOZ_ASSERT(isLive());
1162 *mKeyHash |= Entry::sCollisionBit;
1164 void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
1165 bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
1166 bool matchHash(HashNumber hn) {
1167 return (*mKeyHash & ~Entry::sCollisionBit) == hn;
1169 HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }
1171 template <typename... Args>
1172 void setLive(HashNumber aHashNumber, Args&&... aArgs) {
1173 MOZ_ASSERT(!isLive());
1174 *mKeyHash = aHashNumber;
1175 new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
1176 MOZ_ASSERT(isLive());
1179 Entry* toEntry() const { return mEntry; }
1182 template <class T, class HashPolicy, class AllocPolicy>
1183 class HashTable : private AllocPolicy {
1184 friend class mozilla::ReentrancyGuard;
1186 using NonConstT = std::remove_const_t<T>;
1187 using Key = typename HashPolicy::KeyType;
1188 using Lookup = typename HashPolicy::Lookup;
1190 public:
1191 using Entry = HashTableEntry<T>;
1192 using Slot = EntrySlot<T>;
1194 template <typename F>
1195 static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
1196 auto hashes = reinterpret_cast<HashNumber*>(aTable);
1197 auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
1198 Slot slot(entries, hashes);
1199 for (size_t i = 0; i < size_t(aCapacity); ++i) {
1200 f(slot);
1201 ++slot;
1205 // A nullable pointer to a hash table element. A Ptr |p| can be tested
1206 // either explicitly |if (p.found()) p->...| or using boolean conversion
1207 // |if (p) p->...|. Ptr objects must not be used after any mutating hash
1208 // table operations unless |generation()| is tested.
1209 class Ptr {
1210 friend class HashTable;
1212 Slot mSlot;
1213 #ifdef DEBUG
1214 const HashTable* mTable;
1215 Generation mGeneration;
1216 #endif
1218 protected:
1219 Ptr(Slot aSlot, const HashTable& aTable)
1220 : mSlot(aSlot)
1221 #ifdef DEBUG
1223 mTable(&aTable),
1224 mGeneration(aTable.generation())
1225 #endif
1229 // This constructor is used only by AddPtr() within lookupForAdd().
1230 explicit Ptr(const HashTable& aTable)
1231 : mSlot(nullptr, nullptr)
1232 #ifdef DEBUG
1234 mTable(&aTable),
1235 mGeneration(aTable.generation())
1236 #endif
1240 bool isValid() const { return !!mSlot.toEntry(); }
1242 public:
1243 Ptr()
1244 : mSlot(nullptr, nullptr)
1245 #ifdef DEBUG
1247 mTable(nullptr),
1248 mGeneration(0)
1249 #endif
1253 bool found() const {
1254 if (!isValid()) {
1255 return false;
1257 #ifdef DEBUG
1258 MOZ_ASSERT(mGeneration == mTable->generation());
1259 #endif
1260 return mSlot.isLive();
1263 explicit operator bool() const { return found(); }
1265 bool operator==(const Ptr& aRhs) const {
1266 MOZ_ASSERT(found() && aRhs.found());
1267 return mSlot == aRhs.mSlot;
1270 bool operator!=(const Ptr& aRhs) const {
1271 #ifdef DEBUG
1272 MOZ_ASSERT(mGeneration == mTable->generation());
1273 #endif
1274 return !(*this == aRhs);
1277 T& operator*() const {
1278 #ifdef DEBUG
1279 MOZ_ASSERT(found());
1280 MOZ_ASSERT(mGeneration == mTable->generation());
1281 #endif
1282 return mSlot.get();
1285 T* operator->() const {
1286 #ifdef DEBUG
1287 MOZ_ASSERT(found());
1288 MOZ_ASSERT(mGeneration == mTable->generation());
1289 #endif
1290 return &mSlot.get();
1294 // A Ptr that can be used to add a key after a failed lookup.
1295 class AddPtr : public Ptr {
1296 friend class HashTable;
1298 HashNumber mKeyHash;
1299 #ifdef DEBUG
1300 uint64_t mMutationCount;
1301 #endif
1303 AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
1304 : Ptr(aSlot, aTable),
1305 mKeyHash(aHashNumber)
1306 #ifdef DEBUG
1308 mMutationCount(aTable.mMutationCount)
1309 #endif
1313 // This constructor is used when lookupForAdd() is performed on a table
1314 // lacking entry storage; it leaves mSlot null but initializes everything
1315 // else.
1316 AddPtr(const HashTable& aTable, HashNumber aHashNumber)
1317 : Ptr(aTable),
1318 mKeyHash(aHashNumber)
1319 #ifdef DEBUG
1321 mMutationCount(aTable.mMutationCount)
1322 #endif
1324 MOZ_ASSERT(isLive());
1327 bool isLive() const { return isLiveHash(mKeyHash); }
1329 public:
1330 AddPtr() : mKeyHash(0) {}
1333 // A hash table iterator that (mostly) doesn't allow table modifications.
1334 // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
1335 // hash table operation unless the |generation()| is tested.
1336 class Iterator {
1337 void moveToNextLiveEntry() {
1338 while (++mCur < mEnd && !mCur.isLive()) {
1339 continue;
1343 protected:
1344 friend class HashTable;
1346 explicit Iterator(const HashTable& aTable)
1347 : mCur(aTable.slotForIndex(0)),
1348 mEnd(aTable.slotForIndex(aTable.capacity()))
1349 #ifdef DEBUG
1351 mTable(aTable),
1352 mMutationCount(aTable.mMutationCount),
1353 mGeneration(aTable.generation()),
1354 mValidEntry(true)
1355 #endif
1357 if (!done() && !mCur.isLive()) {
1358 moveToNextLiveEntry();
1362 Slot mCur;
1363 Slot mEnd;
1364 #ifdef DEBUG
1365 const HashTable& mTable;
1366 uint64_t mMutationCount;
1367 Generation mGeneration;
1368 bool mValidEntry;
1369 #endif
1371 public:
1372 bool done() const {
1373 MOZ_ASSERT(mGeneration == mTable.generation());
1374 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1375 return mCur == mEnd;
1378 T& get() const {
1379 MOZ_ASSERT(!done());
1380 MOZ_ASSERT(mValidEntry);
1381 MOZ_ASSERT(mGeneration == mTable.generation());
1382 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1383 return mCur.get();
1386 void next() {
1387 MOZ_ASSERT(!done());
1388 MOZ_ASSERT(mGeneration == mTable.generation());
1389 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1390 moveToNextLiveEntry();
1391 #ifdef DEBUG
1392 mValidEntry = true;
1393 #endif
1397 // A hash table iterator that permits modification, removal and rekeying.
1398 // Since rehashing when elements were removed during enumeration would be
1399 // bad, it is postponed until the ModIterator is destructed. Since the
1400 // ModIterator's destructor touches the hash table, the user must ensure
1401 // that the hash table is still alive when the destructor runs.
1402 class ModIterator : public Iterator {
1403 friend class HashTable;
1405 HashTable& mTable;
1406 bool mRekeyed;
1407 bool mRemoved;
1409 // ModIterator is movable but not copyable.
1410 ModIterator(const ModIterator&) = delete;
1411 void operator=(const ModIterator&) = delete;
1413 protected:
1414 explicit ModIterator(HashTable& aTable)
1415 : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}
1417 public:
1418 MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
1419 : Iterator(aOther),
1420 mTable(aOther.mTable),
1421 mRekeyed(aOther.mRekeyed),
1422 mRemoved(aOther.mRemoved) {
1423 aOther.mRekeyed = false;
1424 aOther.mRemoved = false;
1427 // Removes the current element from the table, leaving |get()|
1428 // invalid until the next call to |next()|.
1429 void remove() {
1430 mTable.remove(this->mCur);
1431 mRemoved = true;
1432 #ifdef DEBUG
1433 this->mValidEntry = false;
1434 this->mMutationCount = mTable.mMutationCount;
1435 #endif
1438 NonConstT& getMutable() {
1439 MOZ_ASSERT(!this->done());
1440 MOZ_ASSERT(this->mValidEntry);
1441 MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation());
1442 MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount);
1443 return this->mCur.getMutable();
1446 // Removes the current element and re-inserts it into the table with
1447 // a new key at the new Lookup position. |get()| is invalid after
1448 // this operation until the next call to |next()|.
1449 void rekey(const Lookup& l, const Key& k) {
1450 MOZ_ASSERT(&k != &HashPolicy::getKey(this->mCur.get()));
1451 Ptr p(this->mCur, mTable);
1452 mTable.rekeyWithoutRehash(p, l, k);
1453 mRekeyed = true;
1454 #ifdef DEBUG
1455 this->mValidEntry = false;
1456 this->mMutationCount = mTable.mMutationCount;
1457 #endif
1460 void rekey(const Key& k) { rekey(k, k); }
1462 // Potentially rehashes the table.
1463 ~ModIterator() {
1464 if (mRekeyed) {
1465 mTable.mGen++;
1466 mTable.infallibleRehashIfOverloaded();
1469 if (mRemoved) {
1470 mTable.compact();
1475 // Range is similar to Iterator, but uses different terminology.
1476 class Range {
1477 friend class HashTable;
1479 Iterator mIter;
1481 protected:
1482 explicit Range(const HashTable& table) : mIter(table) {}
1484 public:
1485 bool empty() const { return mIter.done(); }
1487 T& front() const { return mIter.get(); }
1489 void popFront() { return mIter.next(); }
1492 // Enum is similar to ModIterator, but uses different terminology.
1493 class Enum {
1494 ModIterator mIter;
1496 // Enum is movable but not copyable.
1497 Enum(const Enum&) = delete;
1498 void operator=(const Enum&) = delete;
1500 public:
1501 template <class Map>
1502 explicit Enum(Map& map) : mIter(map.mImpl) {}
1504 MOZ_IMPLICIT Enum(Enum&& other) : mIter(std::move(other.mIter)) {}
1506 bool empty() const { return mIter.done(); }
1508 T& front() const { return mIter.get(); }
1510 void popFront() { return mIter.next(); }
1512 void removeFront() { mIter.remove(); }
1514 NonConstT& mutableFront() { return mIter.getMutable(); }
1516 void rekeyFront(const Lookup& aLookup, const Key& aKey) {
1517 mIter.rekey(aLookup, aKey);
1520 void rekeyFront(const Key& aKey) { mIter.rekey(aKey); }
1523 // HashTable is movable
1524 HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
1525 HashTable& operator=(HashTable&& aRhs) {
1526 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
1527 if (mTable) {
1528 destroyTable(*this, mTable, capacity());
1530 AllocPolicy::operator=(std::move(aRhs));
1531 moveFrom(aRhs);
1532 return *this;
1535 private:
1536 void moveFrom(HashTable& aRhs) {
1537 mGen = aRhs.mGen;
1538 mHashShift = aRhs.mHashShift;
1539 mTable = aRhs.mTable;
1540 mEntryCount = aRhs.mEntryCount;
1541 mRemovedCount = aRhs.mRemovedCount;
1542 #ifdef DEBUG
1543 mMutationCount = aRhs.mMutationCount;
1544 mEntered = aRhs.mEntered;
1545 #endif
1546 aRhs.mTable = nullptr;
1547 aRhs.clearAndCompact();
1550 // HashTable is not copyable or assignable
1551 HashTable(const HashTable&) = delete;
1552 void operator=(const HashTable&) = delete;
1554 static const uint32_t CAP_BITS = 30;
1556 public:
1557 uint64_t mGen : 56; // entry storage generation number
1558 uint64_t mHashShift : 8; // multiplicative hash shift
1559 char* mTable; // entry storage
1560 uint32_t mEntryCount; // number of entries in mTable
1561 uint32_t mRemovedCount; // removed entry sentinels in mTable
1563 #ifdef DEBUG
1564 uint64_t mMutationCount;
1565 mutable bool mEntered;
1566 #endif
1568 // The default initial capacity is 32 (enough to hold 16 elements), but it
1569 // can be as low as 4.
1570 static const uint32_t sDefaultLen = 16;
1571 static const uint32_t sMinCapacity = 4;
1572 // See the comments in HashTableEntry about this value.
1573 static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
1574 static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
1575 static const uint32_t sMaxCapacity = 1u << CAP_BITS;
1577 // Hash-table alpha is conceptually a fraction, but to avoid floating-point
1578 // math we implement it as a ratio of integers.
1579 static const uint8_t sAlphaDenominator = 4;
1580 static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4
1581 static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4
1583 static const HashNumber sFreeKey = Entry::sFreeKey;
1584 static const HashNumber sRemovedKey = Entry::sRemovedKey;
1585 static const HashNumber sCollisionBit = Entry::sCollisionBit;
1587 static uint32_t bestCapacity(uint32_t aLen) {
1588 static_assert(
1589 (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
1590 "multiplication in numerator below could overflow");
1591 static_assert(
1592 sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator,
1593 "numerator calculation below could potentially overflow");
1595 // Callers should ensure this is true.
1596 MOZ_ASSERT(aLen <= sMaxInit);
1598 // Compute the smallest capacity allowing |aLen| elements to be
1599 // inserted without rehashing: ceil(aLen / max-alpha). (Ceiling
1600 // integral division: <http://stackoverflow.com/a/2745086>.)
1601 uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
1602 sMaxAlphaNumerator;
1603 capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);
1605 MOZ_ASSERT(capacity >= aLen);
1606 MOZ_ASSERT(capacity <= sMaxCapacity);
1608 return capacity;
1611 static uint32_t hashShift(uint32_t aLen) {
1612 // Reject all lengths whose initial computed capacity would exceed
1613 // sMaxCapacity. Round that maximum aLen down to the nearest power of two
1614 // for speedier code.
1615 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
1616 MOZ_CRASH("initial length is too large");
1619 return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
1622 static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }
1624 static HashNumber prepareHash(const Lookup& aLookup) {
1625 HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(aLookup));
1627 // Avoid reserved hash codes.
1628 if (!isLiveHash(keyHash)) {
1629 keyHash -= (sRemovedKey + 1);
1631 return keyHash & ~sCollisionBit;
1634 enum FailureBehavior { DontReportFailure = false, ReportFailure = true };
1636 // Fake a struct that we're going to alloc. See the comments in
1637 // HashTableEntry about how the table is laid out, and why it's safe.
1638 struct FakeSlot {
1639 unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
1642 static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
1643 FailureBehavior aReportFailure = ReportFailure) {
1644 FakeSlot* fake =
1645 aReportFailure
1646 ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
1647 : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);
1649 MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==
1652 char* table = reinterpret_cast<char*>(fake);
1653 if (table) {
1654 forEachSlot(table, aCapacity, [&](Slot& slot) {
1655 *slot.mKeyHash = sFreeKey;
1656 new (KnownNotNull, slot.toEntry()) Entry();
1659 return table;
1662 static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1663 uint32_t aCapacity) {
1664 forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
1665 if (slot.isLive()) {
1666 slot.toEntry()->destroyStoredT();
1669 freeTable(aAllocPolicy, aOldTable, aCapacity);
1672 static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1673 uint32_t aCapacity) {
1674 FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
1675 aAllocPolicy.free_(fake, aCapacity);
1678 public:
1679 HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
1680 : AllocPolicy(std::move(aAllocPolicy)),
1681 mGen(0),
1682 mHashShift(hashShift(aLen)),
1683 mTable(nullptr),
1684 mEntryCount(0),
1685 mRemovedCount(0)
1686 #ifdef DEBUG
1688 mMutationCount(0),
1689 mEntered(false)
1690 #endif
1694 explicit HashTable(AllocPolicy aAllocPolicy)
1695 : HashTable(aAllocPolicy, sDefaultLen) {}
1697 ~HashTable() {
1698 if (mTable) {
1699 destroyTable(*this, mTable, capacity());
1703 private:
1704 HashNumber hash1(HashNumber aHash0) const { return aHash0 >> mHashShift; }
1706 struct DoubleHash {
1707 HashNumber mHash2;
1708 HashNumber mSizeMask;
1711 DoubleHash hash2(HashNumber aCurKeyHash) const {
1712 uint32_t sizeLog2 = kHashNumberBits - mHashShift;
1713 DoubleHash dh = {((aCurKeyHash << sizeLog2) >> mHashShift) | 1,
1714 (HashNumber(1) << sizeLog2) - 1};
1715 return dh;
1718 static HashNumber applyDoubleHash(HashNumber aHash1,
1719 const DoubleHash& aDoubleHash) {
1720 return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
1723 static MOZ_ALWAYS_INLINE bool match(T& aEntry, const Lookup& aLookup) {
1724 return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
1727 enum LookupReason { ForNonAdd, ForAdd };
1729 Slot slotForIndex(HashNumber aIndex) const {
1730 auto hashes = reinterpret_cast<HashNumber*>(mTable);
1731 auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
1732 return Slot(&entries[aIndex], &hashes[aIndex]);
1735 // Warning: in order for readonlyThreadsafeLookup() to be safe this
1736 // function must not modify the table in any way when Reason==ForNonAdd.
1737 template <LookupReason Reason>
1738 MOZ_ALWAYS_INLINE Slot lookup(const Lookup& aLookup,
1739 HashNumber aKeyHash) const {
1740 MOZ_ASSERT(isLiveHash(aKeyHash));
1741 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1742 MOZ_ASSERT(mTable);
1744 // Compute the primary hash address.
1745 HashNumber h1 = hash1(aKeyHash);
1746 Slot slot = slotForIndex(h1);
1748 // Miss: return space for a new entry.
1749 if (slot.isFree()) {
1750 return slot;
1753 // Hit: return entry.
1754 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1755 return slot;
1758 // Collision: double hash.
1759 DoubleHash dh = hash2(aKeyHash);
1761 // Save the first removed entry pointer so we can recycle later.
1762 Maybe<Slot> firstRemoved;
1764 while (true) {
1765 if (Reason == ForAdd && !firstRemoved) {
1766 if (MOZ_UNLIKELY(slot.isRemoved())) {
1767 firstRemoved.emplace(slot);
1768 } else {
1769 slot.setCollision();
1773 h1 = applyDoubleHash(h1, dh);
1775 slot = slotForIndex(h1);
1776 if (slot.isFree()) {
1777 return firstRemoved.refOr(slot);
1780 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1781 return slot;
1786 // This is a copy of lookup() hardcoded to the assumptions:
1787 // 1. the lookup is for an add;
1788 // 2. the key, whose |keyHash| has been passed, is not in the table.
1789 Slot findNonLiveSlot(HashNumber aKeyHash) {
1790 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1791 MOZ_ASSERT(mTable);
1793 // We assume 'aKeyHash' has already been distributed.
1795 // Compute the primary hash address.
1796 HashNumber h1 = hash1(aKeyHash);
1797 Slot slot = slotForIndex(h1);
1799 // Miss: return space for a new entry.
1800 if (!slot.isLive()) {
1801 return slot;
1804 // Collision: double hash.
1805 DoubleHash dh = hash2(aKeyHash);
1807 while (true) {
1808 slot.setCollision();
1810 h1 = applyDoubleHash(h1, dh);
1812 slot = slotForIndex(h1);
1813 if (!slot.isLive()) {
1814 return slot;
1819 enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };
1821 RebuildStatus changeTableSize(
1822 uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
1823 MOZ_ASSERT(IsPowerOfTwo(newCapacity));
1824 MOZ_ASSERT(!!mTable == !!capacity());
1826 // Look, but don't touch, until we succeed in getting new entry store.
1827 char* oldTable = mTable;
1828 uint32_t oldCapacity = capacity();
1829 uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);
1831 if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) {
1832 if (aReportFailure) {
1833 this->reportAllocOverflow();
1835 return RehashFailed;
1838 char* newTable = createTable(*this, newCapacity, aReportFailure);
1839 if (!newTable) {
1840 return RehashFailed;
1843 // We can't fail from here on, so update table parameters.
1844 mHashShift = kHashNumberBits - newLog2;
1845 mRemovedCount = 0;
1846 mGen++;
1847 mTable = newTable;
1849 // Copy only live entries, leaving removed ones behind.
1850 forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
1851 if (slot.isLive()) {
1852 HashNumber hn = slot.getKeyHash();
1853 findNonLiveSlot(hn).setLive(
1854 hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
1857 slot.clear();
1860 // All entries have been destroyed, no need to destroyTable.
1861 freeTable(*this, oldTable, oldCapacity);
1862 return Rehashed;
1865 RebuildStatus rehashIfOverloaded(
1866 FailureBehavior aReportFailure = ReportFailure) {
1867 static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator,
1868 "multiplication below could overflow");
1870 // Note: if capacity() is zero, this will always succeed, which is
1871 // what we want.
1872 bool overloaded = mEntryCount + mRemovedCount >=
1873 capacity() * sMaxAlphaNumerator / sAlphaDenominator;
1875 if (!overloaded) {
1876 return NotOverloaded;
1879 // Succeed if a quarter or more of all entries are removed. Note that this
1880 // always succeeds if capacity() == 0 (i.e. entry storage has not been
1881 // allocated), which is what we want, because it means changeTableSize()
1882 // will allocate the requested capacity rather than doubling it.
1883 bool manyRemoved = mRemovedCount >= (capacity() >> 2);
1884 uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
1885 return changeTableSize(newCapacity, aReportFailure);
1888 void infallibleRehashIfOverloaded() {
1889 if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
1890 rehashTableInPlace();
1894 void remove(Slot& aSlot) {
1895 MOZ_ASSERT(mTable);
1897 if (aSlot.hasCollision()) {
1898 aSlot.removeLive();
1899 mRemovedCount++;
1900 } else {
1901 aSlot.clearLive();
1903 mEntryCount--;
1904 #ifdef DEBUG
1905 mMutationCount++;
1906 #endif
1909 void shrinkIfUnderloaded() {
1910 static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator,
1911 "multiplication below could overflow");
1912 bool underloaded =
1913 capacity() > sMinCapacity &&
1914 mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;
1916 if (underloaded) {
1917 (void)changeTableSize(capacity() / 2, DontReportFailure);
1921 // This is identical to changeTableSize(currentSize), but without requiring
1922 // a second table. We do this by recycling the collision bits to tell us if
1923 // the element is already inserted or still waiting to be inserted. Since
1924 // already-inserted elements win any conflicts, we get the same table as we
1925 // would have gotten through random insertion order.
1926 void rehashTableInPlace() {
1927 mRemovedCount = 0;
1928 mGen++;
1929 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
1930 for (uint32_t i = 0; i < capacity();) {
1931 Slot src = slotForIndex(i);
1933 if (!src.isLive() || src.hasCollision()) {
1934 ++i;
1935 continue;
1938 HashNumber keyHash = src.getKeyHash();
1939 HashNumber h1 = hash1(keyHash);
1940 DoubleHash dh = hash2(keyHash);
1941 Slot tgt = slotForIndex(h1);
1942 while (true) {
1943 if (!tgt.hasCollision()) {
1944 src.swap(tgt);
1945 tgt.setCollision();
1946 break;
1949 h1 = applyDoubleHash(h1, dh);
1950 tgt = slotForIndex(h1);
1954 // TODO: this algorithm leaves collision bits on *all* elements, even if
1955 // they are on no collision path. We have the option of setting the
1956 // collision bits correctly on a subsequent pass or skipping the rehash
1957 // unless we are totally filled with tombstones: benchmark to find out
1958 // which approach is best.
1961 // Note: |aLookup| may be a reference to a piece of |u|, so this function
1962 // must take care not to use |aLookup| after moving |u|.
1964 // Prefer to use putNewInfallible; this function does not check
1965 // invariants.
1966 template <typename... Args>
1967 void putNewInfallibleInternal(const Lookup& aLookup, Args&&... aArgs) {
1968 MOZ_ASSERT(mTable);
1970 HashNumber keyHash = prepareHash(aLookup);
1971 Slot slot = findNonLiveSlot(keyHash);
1973 if (slot.isRemoved()) {
1974 mRemovedCount--;
1975 keyHash |= sCollisionBit;
1978 slot.setLive(keyHash, std::forward<Args>(aArgs)...);
1979 mEntryCount++;
1980 #ifdef DEBUG
1981 mMutationCount++;
1982 #endif
1985 public:
1986 void clear() {
1987 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
1988 mRemovedCount = 0;
1989 mEntryCount = 0;
1990 #ifdef DEBUG
1991 mMutationCount++;
1992 #endif
1995 // Resize the table down to the smallest capacity that doesn't overload the
1996 // table. Since we call shrinkIfUnderloaded() on every remove, you only need
1997 // to call this after a bulk removal of items done without calling remove().
1998 void compact() {
1999 if (empty()) {
2000 // Free the entry storage.
2001 freeTable(*this, mTable, capacity());
2002 mGen++;
2003 mHashShift = hashShift(0); // gives minimum capacity on regrowth
2004 mTable = nullptr;
2005 mRemovedCount = 0;
2006 return;
2009 uint32_t bestCapacity = this->bestCapacity(mEntryCount);
2010 MOZ_ASSERT(bestCapacity <= capacity());
2012 if (bestCapacity < capacity()) {
2013 (void)changeTableSize(bestCapacity, DontReportFailure);
2017 void clearAndCompact() {
2018 clear();
2019 compact();
2022 [[nodiscard]] bool reserve(uint32_t aLen) {
2023 if (aLen == 0) {
2024 return true;
2027 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
2028 return false;
2031 uint32_t bestCapacity = this->bestCapacity(aLen);
2032 if (bestCapacity <= capacity()) {
2033 return true; // Capacity is already sufficient.
2036 RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
2037 MOZ_ASSERT(status != NotOverloaded);
2038 return status != RehashFailed;
2041 Iterator iter() const { return Iterator(*this); }
2043 ModIterator modIter() { return ModIterator(*this); }
2045 Range all() const { return Range(*this); }
2047 bool empty() const { return mEntryCount == 0; }
2049 uint32_t count() const { return mEntryCount; }
2051 uint32_t rawCapacity() const { return 1u << (kHashNumberBits - mHashShift); }
2053 uint32_t capacity() const { return mTable ? rawCapacity() : 0; }
2055 Generation generation() const { return Generation(mGen); }
2057 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2058 return aMallocSizeOf(mTable);
2061 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2062 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
2065 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
2066 if (empty() || !HasHash<HashPolicy>(aLookup)) {
2067 return Ptr();
2069 HashNumber keyHash = prepareHash(aLookup);
2070 return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
2073 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
2074 ReentrancyGuard g(*this);
2075 return readonlyThreadsafeLookup(aLookup);
2078 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
2079 ReentrancyGuard g(*this);
2080 if (!EnsureHash<HashPolicy>(aLookup)) {
2081 return AddPtr();
2084 HashNumber keyHash = prepareHash(aLookup);
2086 if (!mTable) {
2087 return AddPtr(*this, keyHash);
2090 // Directly call the constructor in the return statement to avoid
2091 // excess copying when building with Visual Studio 2017.
2092 // See bug 1385181.
2093 return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
2096 template <typename... Args>
2097 [[nodiscard]] bool add(AddPtr& aPtr, Args&&... aArgs) {
2098 ReentrancyGuard g(*this);
2099 MOZ_ASSERT_IF(aPtr.isValid(), mTable);
2100 MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this);
2101 MOZ_ASSERT(!aPtr.found());
2102 MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit));
2104 // Check for error from ensureHash() here.
2105 if (!aPtr.isLive()) {
2106 return false;
2109 MOZ_ASSERT(aPtr.mGeneration == generation());
2110 #ifdef DEBUG
2111 MOZ_ASSERT(aPtr.mMutationCount == mMutationCount);
2112 #endif
2114 if (!aPtr.isValid()) {
2115 MOZ_ASSERT(!mTable && mEntryCount == 0);
2116 uint32_t newCapacity = rawCapacity();
2117 RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
2118 MOZ_ASSERT(status != NotOverloaded);
2119 if (status == RehashFailed) {
2120 return false;
2122 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2124 } else if (aPtr.mSlot.isRemoved()) {
2125 // Changing an entry from removed to live does not affect whether we are
2126 // overloaded and can be handled separately.
2127 if (!this->checkSimulatedOOM()) {
2128 return false;
2130 mRemovedCount--;
2131 aPtr.mKeyHash |= sCollisionBit;
2133 } else {
2134 // Preserve the validity of |aPtr.mSlot|.
2135 RebuildStatus status = rehashIfOverloaded();
2136 if (status == RehashFailed) {
2137 return false;
2139 if (status == NotOverloaded && !this->checkSimulatedOOM()) {
2140 return false;
2142 if (status == Rehashed) {
2143 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2147 aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
2148 mEntryCount++;
2149 #ifdef DEBUG
2150 mMutationCount++;
2151 aPtr.mGeneration = generation();
2152 aPtr.mMutationCount = mMutationCount;
2153 #endif
2154 return true;
2157 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2158 // must take care not to use |aLookup| after moving |u|.
2159 template <typename... Args>
2160 void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
2161 MOZ_ASSERT(!lookup(aLookup).found());
2162 ReentrancyGuard g(*this);
2163 putNewInfallibleInternal(aLookup, std::forward<Args>(aArgs)...);
2166 // Note: |aLookup| may be alias arguments in |aArgs|, so this function must
2167 // take care not to use |aLookup| after moving |aArgs|.
2168 template <typename... Args>
2169 [[nodiscard]] bool putNew(const Lookup& aLookup, Args&&... aArgs) {
2170 if (!this->checkSimulatedOOM()) {
2171 return false;
2173 if (!EnsureHash<HashPolicy>(aLookup)) {
2174 return false;
2176 if (rehashIfOverloaded() == RehashFailed) {
2177 return false;
2179 putNewInfallible(aLookup, std::forward<Args>(aArgs)...);
2180 return true;
2183 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2184 // must take care not to use |aLookup| after moving |u|.
2185 template <typename... Args>
2186 [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
2187 Args&&... aArgs) {
2188 // Check for error from ensureHash() here.
2189 if (!aPtr.isLive()) {
2190 return false;
2192 #ifdef DEBUG
2193 aPtr.mGeneration = generation();
2194 aPtr.mMutationCount = mMutationCount;
2195 #endif
2196 if (mTable) {
2197 ReentrancyGuard g(*this);
2198 // Check that aLookup has not been destroyed.
2199 MOZ_ASSERT(prepareHash(aLookup) == aPtr.mKeyHash);
2200 aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
2201 if (aPtr.found()) {
2202 return true;
2204 } else {
2205 // Clear aPtr so it's invalid; add() will allocate storage and redo the
2206 // lookup.
2207 aPtr.mSlot = Slot(nullptr, nullptr);
2209 return add(aPtr, std::forward<Args>(aArgs)...);
2212 void remove(Ptr aPtr) {
2213 MOZ_ASSERT(mTable);
2214 ReentrancyGuard g(*this);
2215 MOZ_ASSERT(aPtr.found());
2216 MOZ_ASSERT(aPtr.mGeneration == generation());
2217 remove(aPtr.mSlot);
2218 shrinkIfUnderloaded();
2221 void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2222 MOZ_ASSERT(mTable);
2223 ReentrancyGuard g(*this);
2224 MOZ_ASSERT(aPtr.found());
2225 MOZ_ASSERT(aPtr.mGeneration == generation());
2226 typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
2227 HashPolicy::setKey(t, const_cast<Key&>(aKey));
2228 remove(aPtr.mSlot);
2229 putNewInfallibleInternal(aLookup, std::move(t));
2232 void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2233 rekeyWithoutRehash(aPtr, aLookup, aKey);
2234 infallibleRehashIfOverloaded();
2238 } // namespace detail
2239 } // namespace mozilla
2241 #endif /* mozilla_HashTable_h */