Bug 1693862 [wpt PR 27525] - [Credentialless] WPT fetch, a=testonly
[gecko.git] / mfbt / HashTable.h
blob415255898f1a2d8ffb3be4c0ee1a318bd49d7031
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 MOZ_MUST_USE.
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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE 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 MOZ_MUST_USE bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup, U&& aU) {
620 return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
623 // -- Removal --------------------------------------------------------------
625 // Lookup and remove the element matching |aLookup|, if present.
626 void remove(const Lookup& aLookup) {
627 if (Ptr p = lookup(aLookup)) {
628 remove(p);
632 // Remove a previously found element (assuming aPtr.found()). The set must
633 // not have been mutated in the interim.
634 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
636 // Remove all keys/values without changing the capacity.
637 void clear() { mImpl.clear(); }
639 // Like clear() followed by compact().
640 void clearAndCompact() { mImpl.clearAndCompact(); }
642 // -- Rekeying -------------------------------------------------------------
644 // Infallibly rekey one entry, if present. Requires that template parameters
645 // T and HashPolicy::Lookup are the same type.
646 void rekeyIfMoved(const Lookup& aOldValue, const T& aNewValue) {
647 if (aOldValue != aNewValue) {
648 rekeyAs(aOldValue, aNewValue, aNewValue);
652 // Infallibly rekey one entry if present, and return whether that happened.
653 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
654 const T& aNewValue) {
655 if (Ptr p = lookup(aOldLookup)) {
656 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewValue);
657 return true;
659 return false;
662 // Infallibly replace the current key at |aPtr| with an equivalent key.
663 // Specifically, both HashPolicy::hash and HashPolicy::match must return
664 // identical results for the new and old key when applied against all
665 // possible matching values.
666 void replaceKey(Ptr aPtr, const T& aNewValue) {
667 MOZ_ASSERT(aPtr.found());
668 MOZ_ASSERT(*aPtr != aNewValue);
669 MOZ_ASSERT(HashPolicy::hash(*aPtr) == HashPolicy::hash(aNewValue));
670 MOZ_ASSERT(HashPolicy::match(*aPtr, aNewValue));
671 const_cast<T&>(*aPtr) = aNewValue;
674 // -- Iteration ------------------------------------------------------------
676 // |iter()| returns an Iterator:
678 // HashSet<int> h;
679 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
680 // int i = iter.get();
681 // }
683 using Iterator = typename Impl::Iterator;
684 Iterator iter() const { return mImpl.iter(); }
686 // |modIter()| returns a ModIterator:
688 // HashSet<int> h;
689 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
690 // if (iter.get() == 42) {
691 // iter.remove();
692 // }
693 // }
695 // Table resize may occur in ModIterator's destructor.
696 using ModIterator = typename Impl::ModIterator;
697 ModIterator modIter() { return mImpl.modIter(); }
699 // These are similar to Iterator/ModIterator/iter(), but use different
700 // terminology.
701 using Range = typename Impl::Range;
702 using Enum = typename Impl::Enum;
703 Range all() const { return mImpl.all(); }
706 //---------------------------------------------------------------------------
707 // Hash Policy
708 //---------------------------------------------------------------------------
710 // A hash policy |HP| for a hash table with key-type |Key| must provide:
712 // - a type |HP::Lookup| to use to lookup table entries;
714 // - a static member function |HP::hash| that hashes lookup values:
716 // static mozilla::HashNumber hash(const Lookup&);
718 // - a static member function |HP::match| that tests equality of key and
719 // lookup values:
721 // static bool match(const Key&, const Lookup&);
723 // Normally, Lookup = Key. In general, though, different values and types of
724 // values can be used to lookup and store. If a Lookup value |l| is not equal
725 // to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
726 // true. E.g.:
728 // mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
729 // if (!p) {
730 // assert(HP::match(k, l)); // must hold
731 // h.add(p, k);
732 // }
734 // A pointer hashing policy that uses HashGeneric() to create good hashes for
735 // pointers. Note that we don't shift out the lowest k bits because we don't
736 // want to assume anything about the alignment of the pointers.
737 template <typename Key>
738 struct PointerHasher {
739 using Lookup = Key;
741 static HashNumber hash(const Lookup& aLookup) {
742 size_t word = reinterpret_cast<size_t>(aLookup);
743 return HashGeneric(word);
746 static bool match(const Key& aKey, const Lookup& aLookup) {
747 return aKey == aLookup;
750 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
753 // The default hash policy, which only works with integers.
754 template <class Key, typename>
755 struct DefaultHasher {
756 using Lookup = Key;
758 static HashNumber hash(const Lookup& aLookup) {
759 // Just convert the integer to a HashNumber and use that as is. (This
760 // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
761 // subsequently called on the value to improve the distribution.
762 return aLookup;
765 static bool match(const Key& aKey, const Lookup& aLookup) {
766 // Use builtin or overloaded operator==.
767 return aKey == aLookup;
770 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
773 // A DefaultHasher specialization for enums.
774 template <class T>
775 struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
776 using Key = T;
777 using Lookup = Key;
779 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
781 static bool match(const Key& aKey, const Lookup& aLookup) {
782 // Use builtin or overloaded operator==.
783 return aKey == static_cast<Key>(aLookup);
786 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
789 // A DefaultHasher specialization for pointers.
790 template <class T>
791 struct DefaultHasher<T*> : PointerHasher<T*> {};
793 // A DefaultHasher specialization for mozilla::UniquePtr.
794 template <class T, class D>
795 struct DefaultHasher<UniquePtr<T, D>> {
796 using Key = UniquePtr<T, D>;
797 using Lookup = Key;
798 using PtrHasher = PointerHasher<T*>;
800 static HashNumber hash(const Lookup& aLookup) {
801 return PtrHasher::hash(aLookup.get());
804 static bool match(const Key& aKey, const Lookup& aLookup) {
805 return PtrHasher::match(aKey.get(), aLookup.get());
808 static void rekey(UniquePtr<T, D>& aKey, UniquePtr<T, D>&& aNewKey) {
809 aKey = std::move(aNewKey);
813 // A DefaultHasher specialization for doubles.
814 template <>
815 struct DefaultHasher<double> {
816 using Key = double;
817 using Lookup = Key;
819 static HashNumber hash(const Lookup& aLookup) {
820 // Just xor the high bits with the low bits, and then treat the bits of the
821 // result as a uint32_t.
822 static_assert(sizeof(HashNumber) == 4,
823 "subsequent code assumes a four-byte hash");
824 uint64_t u = BitwiseCast<uint64_t>(aLookup);
825 return HashNumber(u ^ (u >> 32));
828 static bool match(const Key& aKey, const Lookup& aLookup) {
829 return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
833 // A DefaultHasher specialization for floats.
834 template <>
835 struct DefaultHasher<float> {
836 using Key = float;
837 using Lookup = Key;
839 static HashNumber hash(const Lookup& aLookup) {
840 // Just use the value as if its bits form an integer. ScrambleHashCode() is
841 // subsequently called on the value to improve the distribution.
842 static_assert(sizeof(HashNumber) == 4,
843 "subsequent code assumes a four-byte hash");
844 return HashNumber(BitwiseCast<uint32_t>(aLookup));
847 static bool match(const Key& aKey, const Lookup& aLookup) {
848 return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
852 // A hash policy for C strings.
853 struct CStringHasher {
854 using Key = const char*;
855 using Lookup = const char*;
857 static HashNumber hash(const Lookup& aLookup) { return HashString(aLookup); }
859 static bool match(const Key& aKey, const Lookup& aLookup) {
860 return strcmp(aKey, aLookup) == 0;
864 //---------------------------------------------------------------------------
865 // Fallible Hashing Interface
866 //---------------------------------------------------------------------------
868 // Most of the time generating a hash code is infallible so this class provides
869 // default methods that always succeed. Specialize this class for your own hash
870 // policy to provide fallible hashing.
872 // This is used by MovableCellHasher to handle the fact that generating a unique
873 // ID for cell pointer may fail due to OOM.
874 template <typename HashPolicy>
875 struct FallibleHashMethods {
876 // Return true if a hashcode is already available for its argument. Once
877 // this returns true for a specific argument it must continue to do so.
878 template <typename Lookup>
879 static bool hasHash(Lookup&& aLookup) {
880 return true;
883 // Fallible method to ensure a hashcode exists for its argument and create
884 // one if not. Returns false on error, e.g. out of memory.
885 template <typename Lookup>
886 static bool ensureHash(Lookup&& aLookup) {
887 return true;
891 template <typename HashPolicy, typename Lookup>
892 static bool HasHash(Lookup&& aLookup) {
893 return FallibleHashMethods<typename HashPolicy::Base>::hasHash(
894 std::forward<Lookup>(aLookup));
897 template <typename HashPolicy, typename Lookup>
898 static bool EnsureHash(Lookup&& aLookup) {
899 return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
900 std::forward<Lookup>(aLookup));
903 //---------------------------------------------------------------------------
904 // Implementation Details (HashMapEntry, HashTableEntry, HashTable)
905 //---------------------------------------------------------------------------
907 // Both HashMap and HashSet are implemented by a single HashTable that is even
908 // more heavily parameterized than the other two. This leaves HashTable gnarly
909 // and extremely coupled to HashMap and HashSet; thus code should not use
910 // HashTable directly.
912 template <class Key, class Value>
913 class HashMapEntry {
914 Key key_;
915 Value value_;
917 template <class, class, class>
918 friend class detail::HashTable;
919 template <class>
920 friend class detail::HashTableEntry;
921 template <class, class, class, class>
922 friend class HashMap;
924 public:
925 template <typename KeyInput, typename ValueInput>
926 HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
927 : key_(std::forward<KeyInput>(aKey)),
928 value_(std::forward<ValueInput>(aValue)) {}
930 HashMapEntry(HashMapEntry&& aRhs) = default;
931 HashMapEntry& operator=(HashMapEntry&& aRhs) = default;
933 using KeyType = Key;
934 using ValueType = Value;
936 const Key& key() const { return key_; }
938 // Use this method with caution! If the key is changed such that its hash
939 // value also changes, the map will be left in an invalid state.
940 Key& mutableKey() { return key_; }
942 const Value& value() const { return value_; }
943 Value& value() { return value_; }
945 private:
946 HashMapEntry(const HashMapEntry&) = delete;
947 void operator=(const HashMapEntry&) = delete;
950 namespace detail {
952 template <class T, class HashPolicy, class AllocPolicy>
953 class HashTable;
955 template <typename T>
956 class EntrySlot;
958 template <typename T>
959 class HashTableEntry {
960 private:
961 using NonConstT = std::remove_const_t<T>;
963 // Instead of having a hash table entry store that looks like this:
965 // +--------+--------+--------+--------+
966 // | entry0 | entry1 | .... | entryN |
967 // +--------+--------+--------+--------+
969 // where the entries contained their cached hash code, we're going to lay out
970 // the entry store thusly:
972 // +-------+-------+-------+-------+--------+--------+--------+--------+
973 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
974 // +-------+-------+-------+-------+--------+--------+--------+--------+
976 // with all the cached hashes prior to the actual entries themselves.
978 // We do this because implementing the first strategy requires us to make
979 // HashTableEntry look roughly like:
981 // template <typename T>
982 // class HashTableEntry {
983 // HashNumber mKeyHash;
984 // T mValue;
985 // };
987 // The problem with this setup is that, depending on the layout of `T`, there
988 // may be platform ABI-mandated padding between `mKeyHash` and the first
989 // member of `T`. This ABI-mandated padding is wasted space, and can be
990 // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
991 // In such cases, we're throwing away a quarter of our entry store on padding,
992 // which is undesirable.
994 // The second layout above, namely:
996 // +-------+-------+-------+-------+--------+--------+--------+--------+
997 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
998 // +-------+-------+-------+-------+--------+--------+--------+--------+
1000 // means there is no wasted space between the hashes themselves, and no wasted
1001 // space between the entries themselves. However, we would also like there to
1002 // be no gap between the last hash and the first entry. The memory allocator
1003 // guarantees the alignment of the start of the hashes. The use of a
1004 // power-of-two capacity of at least 4 guarantees that the alignment of the
1005 // *end* of the hash array is no less than the alignment of the start.
1006 // Finally, the static_asserts here guarantee that the entries themselves
1007 // don't need to be any more aligned than the alignment of the entry store
1008 // itself.
1010 // This assertion is safe for 32-bit builds because on both Windows and Linux
1011 // (including Android), the minimum alignment for allocations larger than 8
1012 // bytes is 8 bytes, and the actual data for entries in our entry store is
1013 // guaranteed to have that alignment as well, thanks to the power-of-two
1014 // number of cached hash values stored prior to the entry data.
1016 // The allocation policy must allocate a table with at least this much
1017 // alignment.
1018 static constexpr size_t kMinimumAlignment = 8;
1020 static_assert(alignof(HashNumber) <= kMinimumAlignment,
1021 "[N*2 hashes, N*2 T values] allocation's alignment must be "
1022 "enough to align each hash");
1023 static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
1024 "subsequent N*2 T values must not require more than an even "
1025 "number of HashNumbers provides");
1027 static const HashNumber sFreeKey = 0;
1028 static const HashNumber sRemovedKey = 1;
1029 static const HashNumber sCollisionBit = 1;
1031 alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];
1033 private:
1034 template <class, class, class>
1035 friend class HashTable;
1036 template <typename>
1037 friend class EntrySlot;
1039 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
1040 // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
1041 // through |void*|. Placing the latter cast in these separate functions
1042 // breaks the chain such that affected GCC versions no longer warn/error.
1043 void* rawValuePtr() { return mValueData; }
1045 static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }
1047 HashTableEntry(const HashTableEntry&) = delete;
1048 void operator=(const HashTableEntry&) = delete;
1050 NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }
1052 void destroyStoredT() {
1053 NonConstT* ptr = valuePtr();
1054 ptr->~T();
1055 MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr));
1058 public:
1059 HashTableEntry() = default;
1061 ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this)); }
1063 void destroy() { destroyStoredT(); }
1065 void swap(HashTableEntry* aOther, bool aIsLive) {
1066 // This allows types to use Argument-Dependent-Lookup, and thus use a custom
1067 // std::swap, which is needed by types like JS::Heap and such.
1068 using std::swap;
1070 if (this == aOther) {
1071 return;
1073 if (aIsLive) {
1074 swap(*valuePtr(), *aOther->valuePtr());
1075 } else {
1076 *aOther->valuePtr() = std::move(*valuePtr());
1077 destroy();
1081 T& get() { return *valuePtr(); }
1083 NonConstT& getMutable() { return *valuePtr(); }
1086 // A slot represents a cached hash value and its associated entry stored
1087 // in the hash table. These two things are not stored in contiguous memory.
1088 template <class T>
1089 class EntrySlot {
1090 using NonConstT = std::remove_const_t<T>;
1092 using Entry = HashTableEntry<T>;
1094 Entry* mEntry;
1095 HashNumber* mKeyHash;
1097 template <class, class, class>
1098 friend class HashTable;
1100 EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
1101 : mEntry(aEntry), mKeyHash(aKeyHash) {}
1103 public:
1104 static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }
1106 EntrySlot(const EntrySlot&) = default;
1107 EntrySlot(EntrySlot&& aOther) = default;
1109 EntrySlot& operator=(const EntrySlot&) = default;
1110 EntrySlot& operator=(EntrySlot&&) = default;
1112 bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }
1114 bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }
1116 EntrySlot& operator++() {
1117 ++mEntry;
1118 ++mKeyHash;
1119 return *this;
1122 void destroy() { mEntry->destroy(); }
1124 void swap(EntrySlot& aOther) {
1125 mEntry->swap(aOther.mEntry, aOther.isLive());
1126 std::swap(*mKeyHash, *aOther.mKeyHash);
1129 T& get() const { return mEntry->get(); }
1131 NonConstT& getMutable() { return mEntry->getMutable(); }
1133 bool isFree() const { return *mKeyHash == Entry::sFreeKey; }
1135 void clearLive() {
1136 MOZ_ASSERT(isLive());
1137 *mKeyHash = Entry::sFreeKey;
1138 mEntry->destroyStoredT();
1141 void clear() {
1142 if (isLive()) {
1143 mEntry->destroyStoredT();
1145 MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry));
1146 *mKeyHash = Entry::sFreeKey;
1149 bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }
1151 void removeLive() {
1152 MOZ_ASSERT(isLive());
1153 *mKeyHash = Entry::sRemovedKey;
1154 mEntry->destroyStoredT();
1157 bool isLive() const { return isLiveHash(*mKeyHash); }
1159 void setCollision() {
1160 MOZ_ASSERT(isLive());
1161 *mKeyHash |= Entry::sCollisionBit;
1163 void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
1164 bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
1165 bool matchHash(HashNumber hn) {
1166 return (*mKeyHash & ~Entry::sCollisionBit) == hn;
1168 HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }
1170 template <typename... Args>
1171 void setLive(HashNumber aHashNumber, Args&&... aArgs) {
1172 MOZ_ASSERT(!isLive());
1173 *mKeyHash = aHashNumber;
1174 new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
1175 MOZ_ASSERT(isLive());
1178 Entry* toEntry() const { return mEntry; }
1181 template <class T, class HashPolicy, class AllocPolicy>
1182 class HashTable : private AllocPolicy {
1183 friend class mozilla::ReentrancyGuard;
1185 using NonConstT = std::remove_const_t<T>;
1186 using Key = typename HashPolicy::KeyType;
1187 using Lookup = typename HashPolicy::Lookup;
1189 public:
1190 using Entry = HashTableEntry<T>;
1191 using Slot = EntrySlot<T>;
1193 template <typename F>
1194 static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
1195 auto hashes = reinterpret_cast<HashNumber*>(aTable);
1196 auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
1197 Slot slot(entries, hashes);
1198 for (size_t i = 0; i < size_t(aCapacity); ++i) {
1199 f(slot);
1200 ++slot;
1204 // A nullable pointer to a hash table element. A Ptr |p| can be tested
1205 // either explicitly |if (p.found()) p->...| or using boolean conversion
1206 // |if (p) p->...|. Ptr objects must not be used after any mutating hash
1207 // table operations unless |generation()| is tested.
1208 class Ptr {
1209 friend class HashTable;
1211 Slot mSlot;
1212 #ifdef DEBUG
1213 const HashTable* mTable;
1214 Generation mGeneration;
1215 #endif
1217 protected:
1218 Ptr(Slot aSlot, const HashTable& aTable)
1219 : mSlot(aSlot)
1220 #ifdef DEBUG
1222 mTable(&aTable),
1223 mGeneration(aTable.generation())
1224 #endif
1228 // This constructor is used only by AddPtr() within lookupForAdd().
1229 explicit Ptr(const HashTable& aTable)
1230 : mSlot(nullptr, nullptr)
1231 #ifdef DEBUG
1233 mTable(&aTable),
1234 mGeneration(aTable.generation())
1235 #endif
1239 bool isValid() const { return !!mSlot.toEntry(); }
1241 public:
1242 Ptr()
1243 : mSlot(nullptr, nullptr)
1244 #ifdef DEBUG
1246 mTable(nullptr),
1247 mGeneration(0)
1248 #endif
1252 bool found() const {
1253 if (!isValid()) {
1254 return false;
1256 #ifdef DEBUG
1257 MOZ_ASSERT(mGeneration == mTable->generation());
1258 #endif
1259 return mSlot.isLive();
1262 explicit operator bool() const { return found(); }
1264 bool operator==(const Ptr& aRhs) const {
1265 MOZ_ASSERT(found() && aRhs.found());
1266 return mSlot == aRhs.mSlot;
1269 bool operator!=(const Ptr& aRhs) const {
1270 #ifdef DEBUG
1271 MOZ_ASSERT(mGeneration == mTable->generation());
1272 #endif
1273 return !(*this == aRhs);
1276 T& operator*() const {
1277 #ifdef DEBUG
1278 MOZ_ASSERT(found());
1279 MOZ_ASSERT(mGeneration == mTable->generation());
1280 #endif
1281 return mSlot.get();
1284 T* operator->() const {
1285 #ifdef DEBUG
1286 MOZ_ASSERT(found());
1287 MOZ_ASSERT(mGeneration == mTable->generation());
1288 #endif
1289 return &mSlot.get();
1293 // A Ptr that can be used to add a key after a failed lookup.
1294 class AddPtr : public Ptr {
1295 friend class HashTable;
1297 HashNumber mKeyHash;
1298 #ifdef DEBUG
1299 uint64_t mMutationCount;
1300 #endif
1302 AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
1303 : Ptr(aSlot, aTable),
1304 mKeyHash(aHashNumber)
1305 #ifdef DEBUG
1307 mMutationCount(aTable.mMutationCount)
1308 #endif
1312 // This constructor is used when lookupForAdd() is performed on a table
1313 // lacking entry storage; it leaves mSlot null but initializes everything
1314 // else.
1315 AddPtr(const HashTable& aTable, HashNumber aHashNumber)
1316 : Ptr(aTable),
1317 mKeyHash(aHashNumber)
1318 #ifdef DEBUG
1320 mMutationCount(aTable.mMutationCount)
1321 #endif
1323 MOZ_ASSERT(isLive());
1326 bool isLive() const { return isLiveHash(mKeyHash); }
1328 public:
1329 AddPtr() : mKeyHash(0) {}
1332 // A hash table iterator that (mostly) doesn't allow table modifications.
1333 // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
1334 // hash table operation unless the |generation()| is tested.
1335 class Iterator {
1336 void moveToNextLiveEntry() {
1337 while (++mCur < mEnd && !mCur.isLive()) {
1338 continue;
1342 protected:
1343 friend class HashTable;
1345 explicit Iterator(const HashTable& aTable)
1346 : mCur(aTable.slotForIndex(0)),
1347 mEnd(aTable.slotForIndex(aTable.capacity()))
1348 #ifdef DEBUG
1350 mTable(aTable),
1351 mMutationCount(aTable.mMutationCount),
1352 mGeneration(aTable.generation()),
1353 mValidEntry(true)
1354 #endif
1356 if (!done() && !mCur.isLive()) {
1357 moveToNextLiveEntry();
1361 Slot mCur;
1362 Slot mEnd;
1363 #ifdef DEBUG
1364 const HashTable& mTable;
1365 uint64_t mMutationCount;
1366 Generation mGeneration;
1367 bool mValidEntry;
1368 #endif
1370 public:
1371 bool done() const {
1372 MOZ_ASSERT(mGeneration == mTable.generation());
1373 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1374 return mCur == mEnd;
1377 T& get() const {
1378 MOZ_ASSERT(!done());
1379 MOZ_ASSERT(mValidEntry);
1380 MOZ_ASSERT(mGeneration == mTable.generation());
1381 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1382 return mCur.get();
1385 void next() {
1386 MOZ_ASSERT(!done());
1387 MOZ_ASSERT(mGeneration == mTable.generation());
1388 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1389 moveToNextLiveEntry();
1390 #ifdef DEBUG
1391 mValidEntry = true;
1392 #endif
1396 // A hash table iterator that permits modification, removal and rekeying.
1397 // Since rehashing when elements were removed during enumeration would be
1398 // bad, it is postponed until the ModIterator is destructed. Since the
1399 // ModIterator's destructor touches the hash table, the user must ensure
1400 // that the hash table is still alive when the destructor runs.
1401 class ModIterator : public Iterator {
1402 friend class HashTable;
1404 HashTable& mTable;
1405 bool mRekeyed;
1406 bool mRemoved;
1408 // ModIterator is movable but not copyable.
1409 ModIterator(const ModIterator&) = delete;
1410 void operator=(const ModIterator&) = delete;
1412 protected:
1413 explicit ModIterator(HashTable& aTable)
1414 : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}
1416 public:
1417 MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
1418 : Iterator(aOther),
1419 mTable(aOther.mTable),
1420 mRekeyed(aOther.mRekeyed),
1421 mRemoved(aOther.mRemoved) {
1422 aOther.mRekeyed = false;
1423 aOther.mRemoved = false;
1426 // Removes the current element from the table, leaving |get()|
1427 // invalid until the next call to |next()|.
1428 void remove() {
1429 mTable.remove(this->mCur);
1430 mRemoved = true;
1431 #ifdef DEBUG
1432 this->mValidEntry = false;
1433 this->mMutationCount = mTable.mMutationCount;
1434 #endif
1437 NonConstT& getMutable() {
1438 MOZ_ASSERT(!this->done());
1439 MOZ_ASSERT(this->mValidEntry);
1440 MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation());
1441 MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount);
1442 return this->mCur.getMutable();
1445 // Removes the current element and re-inserts it into the table with
1446 // a new key at the new Lookup position. |get()| is invalid after
1447 // this operation until the next call to |next()|.
1448 void rekey(const Lookup& l, const Key& k) {
1449 MOZ_ASSERT(&k != &HashPolicy::getKey(this->mCur.get()));
1450 Ptr p(this->mCur, mTable);
1451 mTable.rekeyWithoutRehash(p, l, k);
1452 mRekeyed = true;
1453 #ifdef DEBUG
1454 this->mValidEntry = false;
1455 this->mMutationCount = mTable.mMutationCount;
1456 #endif
1459 void rekey(const Key& k) { rekey(k, k); }
1461 // Potentially rehashes the table.
1462 ~ModIterator() {
1463 if (mRekeyed) {
1464 mTable.mGen++;
1465 mTable.infallibleRehashIfOverloaded();
1468 if (mRemoved) {
1469 mTable.compact();
1474 // Range is similar to Iterator, but uses different terminology.
1475 class Range {
1476 friend class HashTable;
1478 Iterator mIter;
1480 protected:
1481 explicit Range(const HashTable& table) : mIter(table) {}
1483 public:
1484 bool empty() const { return mIter.done(); }
1486 T& front() const { return mIter.get(); }
1488 void popFront() { return mIter.next(); }
1491 // Enum is similar to ModIterator, but uses different terminology.
1492 class Enum {
1493 ModIterator mIter;
1495 // Enum is movable but not copyable.
1496 Enum(const Enum&) = delete;
1497 void operator=(const Enum&) = delete;
1499 public:
1500 template <class Map>
1501 explicit Enum(Map& map) : mIter(map.mImpl) {}
1503 MOZ_IMPLICIT Enum(Enum&& other) : mIter(std::move(other.mIter)) {}
1505 bool empty() const { return mIter.done(); }
1507 T& front() const { return mIter.get(); }
1509 void popFront() { return mIter.next(); }
1511 void removeFront() { mIter.remove(); }
1513 NonConstT& mutableFront() { return mIter.getMutable(); }
1515 void rekeyFront(const Lookup& aLookup, const Key& aKey) {
1516 mIter.rekey(aLookup, aKey);
1519 void rekeyFront(const Key& aKey) { mIter.rekey(aKey); }
1522 // HashTable is movable
1523 HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
1524 HashTable& operator=(HashTable&& aRhs) {
1525 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
1526 if (mTable) {
1527 destroyTable(*this, mTable, capacity());
1529 AllocPolicy::operator=(std::move(aRhs));
1530 moveFrom(aRhs);
1531 return *this;
1534 private:
1535 void moveFrom(HashTable& aRhs) {
1536 mGen = aRhs.mGen;
1537 mHashShift = aRhs.mHashShift;
1538 mTable = aRhs.mTable;
1539 mEntryCount = aRhs.mEntryCount;
1540 mRemovedCount = aRhs.mRemovedCount;
1541 #ifdef DEBUG
1542 mMutationCount = aRhs.mMutationCount;
1543 mEntered = aRhs.mEntered;
1544 #endif
1545 aRhs.mTable = nullptr;
1546 aRhs.clearAndCompact();
1549 // HashTable is not copyable or assignable
1550 HashTable(const HashTable&) = delete;
1551 void operator=(const HashTable&) = delete;
1553 static const uint32_t CAP_BITS = 30;
1555 public:
1556 uint64_t mGen : 56; // entry storage generation number
1557 uint64_t mHashShift : 8; // multiplicative hash shift
1558 char* mTable; // entry storage
1559 uint32_t mEntryCount; // number of entries in mTable
1560 uint32_t mRemovedCount; // removed entry sentinels in mTable
1562 #ifdef DEBUG
1563 uint64_t mMutationCount;
1564 mutable bool mEntered;
1565 #endif
1567 // The default initial capacity is 32 (enough to hold 16 elements), but it
1568 // can be as low as 4.
1569 static const uint32_t sDefaultLen = 16;
1570 static const uint32_t sMinCapacity = 4;
1571 // See the comments in HashTableEntry about this value.
1572 static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
1573 static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
1574 static const uint32_t sMaxCapacity = 1u << CAP_BITS;
1576 // Hash-table alpha is conceptually a fraction, but to avoid floating-point
1577 // math we implement it as a ratio of integers.
1578 static const uint8_t sAlphaDenominator = 4;
1579 static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4
1580 static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4
1582 static const HashNumber sFreeKey = Entry::sFreeKey;
1583 static const HashNumber sRemovedKey = Entry::sRemovedKey;
1584 static const HashNumber sCollisionBit = Entry::sCollisionBit;
1586 static uint32_t bestCapacity(uint32_t aLen) {
1587 static_assert(
1588 (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
1589 "multiplication in numerator below could overflow");
1590 static_assert(
1591 sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator,
1592 "numerator calculation below could potentially overflow");
1594 // Callers should ensure this is true.
1595 MOZ_ASSERT(aLen <= sMaxInit);
1597 // Compute the smallest capacity allowing |aLen| elements to be
1598 // inserted without rehashing: ceil(aLen / max-alpha). (Ceiling
1599 // integral division: <http://stackoverflow.com/a/2745086>.)
1600 uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
1601 sMaxAlphaNumerator;
1602 capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);
1604 MOZ_ASSERT(capacity >= aLen);
1605 MOZ_ASSERT(capacity <= sMaxCapacity);
1607 return capacity;
1610 static uint32_t hashShift(uint32_t aLen) {
1611 // Reject all lengths whose initial computed capacity would exceed
1612 // sMaxCapacity. Round that maximum aLen down to the nearest power of two
1613 // for speedier code.
1614 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
1615 MOZ_CRASH("initial length is too large");
1618 return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
1621 static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }
1623 static HashNumber prepareHash(const Lookup& aLookup) {
1624 HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(aLookup));
1626 // Avoid reserved hash codes.
1627 if (!isLiveHash(keyHash)) {
1628 keyHash -= (sRemovedKey + 1);
1630 return keyHash & ~sCollisionBit;
1633 enum FailureBehavior { DontReportFailure = false, ReportFailure = true };
1635 // Fake a struct that we're going to alloc. See the comments in
1636 // HashTableEntry about how the table is laid out, and why it's safe.
1637 struct FakeSlot {
1638 unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
1641 static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
1642 FailureBehavior aReportFailure = ReportFailure) {
1643 FakeSlot* fake =
1644 aReportFailure
1645 ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
1646 : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);
1648 MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==
1651 char* table = reinterpret_cast<char*>(fake);
1652 if (table) {
1653 forEachSlot(table, aCapacity, [&](Slot& slot) {
1654 *slot.mKeyHash = sFreeKey;
1655 new (KnownNotNull, slot.toEntry()) Entry();
1658 return table;
1661 static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1662 uint32_t aCapacity) {
1663 forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
1664 if (slot.isLive()) {
1665 slot.toEntry()->destroyStoredT();
1668 freeTable(aAllocPolicy, aOldTable, aCapacity);
1671 static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1672 uint32_t aCapacity) {
1673 FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
1674 aAllocPolicy.free_(fake, aCapacity);
1677 public:
1678 HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
1679 : AllocPolicy(std::move(aAllocPolicy)),
1680 mGen(0),
1681 mHashShift(hashShift(aLen)),
1682 mTable(nullptr),
1683 mEntryCount(0),
1684 mRemovedCount(0)
1685 #ifdef DEBUG
1687 mMutationCount(0),
1688 mEntered(false)
1689 #endif
1693 explicit HashTable(AllocPolicy aAllocPolicy)
1694 : HashTable(aAllocPolicy, sDefaultLen) {}
1696 ~HashTable() {
1697 if (mTable) {
1698 destroyTable(*this, mTable, capacity());
1702 private:
1703 HashNumber hash1(HashNumber aHash0) const { return aHash0 >> mHashShift; }
1705 struct DoubleHash {
1706 HashNumber mHash2;
1707 HashNumber mSizeMask;
1710 DoubleHash hash2(HashNumber aCurKeyHash) const {
1711 uint32_t sizeLog2 = kHashNumberBits - mHashShift;
1712 DoubleHash dh = {((aCurKeyHash << sizeLog2) >> mHashShift) | 1,
1713 (HashNumber(1) << sizeLog2) - 1};
1714 return dh;
1717 static HashNumber applyDoubleHash(HashNumber aHash1,
1718 const DoubleHash& aDoubleHash) {
1719 return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
1722 static MOZ_ALWAYS_INLINE bool match(T& aEntry, const Lookup& aLookup) {
1723 return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
1726 enum LookupReason { ForNonAdd, ForAdd };
1728 Slot slotForIndex(HashNumber aIndex) const {
1729 auto hashes = reinterpret_cast<HashNumber*>(mTable);
1730 auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
1731 return Slot(&entries[aIndex], &hashes[aIndex]);
1734 // Warning: in order for readonlyThreadsafeLookup() to be safe this
1735 // function must not modify the table in any way when Reason==ForNonAdd.
1736 template <LookupReason Reason>
1737 MOZ_ALWAYS_INLINE Slot lookup(const Lookup& aLookup,
1738 HashNumber aKeyHash) const {
1739 MOZ_ASSERT(isLiveHash(aKeyHash));
1740 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1741 MOZ_ASSERT(mTable);
1743 // Compute the primary hash address.
1744 HashNumber h1 = hash1(aKeyHash);
1745 Slot slot = slotForIndex(h1);
1747 // Miss: return space for a new entry.
1748 if (slot.isFree()) {
1749 return slot;
1752 // Hit: return entry.
1753 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1754 return slot;
1757 // Collision: double hash.
1758 DoubleHash dh = hash2(aKeyHash);
1760 // Save the first removed entry pointer so we can recycle later.
1761 Maybe<Slot> firstRemoved;
1763 while (true) {
1764 if (Reason == ForAdd && !firstRemoved) {
1765 if (MOZ_UNLIKELY(slot.isRemoved())) {
1766 firstRemoved.emplace(slot);
1767 } else {
1768 slot.setCollision();
1772 h1 = applyDoubleHash(h1, dh);
1774 slot = slotForIndex(h1);
1775 if (slot.isFree()) {
1776 return firstRemoved.refOr(slot);
1779 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1780 return slot;
1785 // This is a copy of lookup() hardcoded to the assumptions:
1786 // 1. the lookup is for an add;
1787 // 2. the key, whose |keyHash| has been passed, is not in the table.
1788 Slot findNonLiveSlot(HashNumber aKeyHash) {
1789 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1790 MOZ_ASSERT(mTable);
1792 // We assume 'aKeyHash' has already been distributed.
1794 // Compute the primary hash address.
1795 HashNumber h1 = hash1(aKeyHash);
1796 Slot slot = slotForIndex(h1);
1798 // Miss: return space for a new entry.
1799 if (!slot.isLive()) {
1800 return slot;
1803 // Collision: double hash.
1804 DoubleHash dh = hash2(aKeyHash);
1806 while (true) {
1807 slot.setCollision();
1809 h1 = applyDoubleHash(h1, dh);
1811 slot = slotForIndex(h1);
1812 if (!slot.isLive()) {
1813 return slot;
1818 enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };
1820 RebuildStatus changeTableSize(
1821 uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
1822 MOZ_ASSERT(IsPowerOfTwo(newCapacity));
1823 MOZ_ASSERT(!!mTable == !!capacity());
1825 // Look, but don't touch, until we succeed in getting new entry store.
1826 char* oldTable = mTable;
1827 uint32_t oldCapacity = capacity();
1828 uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);
1830 if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) {
1831 if (aReportFailure) {
1832 this->reportAllocOverflow();
1834 return RehashFailed;
1837 char* newTable = createTable(*this, newCapacity, aReportFailure);
1838 if (!newTable) {
1839 return RehashFailed;
1842 // We can't fail from here on, so update table parameters.
1843 mHashShift = kHashNumberBits - newLog2;
1844 mRemovedCount = 0;
1845 mGen++;
1846 mTable = newTable;
1848 // Copy only live entries, leaving removed ones behind.
1849 forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
1850 if (slot.isLive()) {
1851 HashNumber hn = slot.getKeyHash();
1852 findNonLiveSlot(hn).setLive(
1853 hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
1856 slot.clear();
1859 // All entries have been destroyed, no need to destroyTable.
1860 freeTable(*this, oldTable, oldCapacity);
1861 return Rehashed;
1864 RebuildStatus rehashIfOverloaded(
1865 FailureBehavior aReportFailure = ReportFailure) {
1866 static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator,
1867 "multiplication below could overflow");
1869 // Note: if capacity() is zero, this will always succeed, which is
1870 // what we want.
1871 bool overloaded = mEntryCount + mRemovedCount >=
1872 capacity() * sMaxAlphaNumerator / sAlphaDenominator;
1874 if (!overloaded) {
1875 return NotOverloaded;
1878 // Succeed if a quarter or more of all entries are removed. Note that this
1879 // always succeeds if capacity() == 0 (i.e. entry storage has not been
1880 // allocated), which is what we want, because it means changeTableSize()
1881 // will allocate the requested capacity rather than doubling it.
1882 bool manyRemoved = mRemovedCount >= (capacity() >> 2);
1883 uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
1884 return changeTableSize(newCapacity, aReportFailure);
1887 void infallibleRehashIfOverloaded() {
1888 if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
1889 rehashTableInPlace();
1893 void remove(Slot& aSlot) {
1894 MOZ_ASSERT(mTable);
1896 if (aSlot.hasCollision()) {
1897 aSlot.removeLive();
1898 mRemovedCount++;
1899 } else {
1900 aSlot.clearLive();
1902 mEntryCount--;
1903 #ifdef DEBUG
1904 mMutationCount++;
1905 #endif
1908 void shrinkIfUnderloaded() {
1909 static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator,
1910 "multiplication below could overflow");
1911 bool underloaded =
1912 capacity() > sMinCapacity &&
1913 mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;
1915 if (underloaded) {
1916 (void)changeTableSize(capacity() / 2, DontReportFailure);
1920 // This is identical to changeTableSize(currentSize), but without requiring
1921 // a second table. We do this by recycling the collision bits to tell us if
1922 // the element is already inserted or still waiting to be inserted. Since
1923 // already-inserted elements win any conflicts, we get the same table as we
1924 // would have gotten through random insertion order.
1925 void rehashTableInPlace() {
1926 mRemovedCount = 0;
1927 mGen++;
1928 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
1929 for (uint32_t i = 0; i < capacity();) {
1930 Slot src = slotForIndex(i);
1932 if (!src.isLive() || src.hasCollision()) {
1933 ++i;
1934 continue;
1937 HashNumber keyHash = src.getKeyHash();
1938 HashNumber h1 = hash1(keyHash);
1939 DoubleHash dh = hash2(keyHash);
1940 Slot tgt = slotForIndex(h1);
1941 while (true) {
1942 if (!tgt.hasCollision()) {
1943 src.swap(tgt);
1944 tgt.setCollision();
1945 break;
1948 h1 = applyDoubleHash(h1, dh);
1949 tgt = slotForIndex(h1);
1953 // TODO: this algorithm leaves collision bits on *all* elements, even if
1954 // they are on no collision path. We have the option of setting the
1955 // collision bits correctly on a subsequent pass or skipping the rehash
1956 // unless we are totally filled with tombstones: benchmark to find out
1957 // which approach is best.
1960 // Note: |aLookup| may be a reference to a piece of |u|, so this function
1961 // must take care not to use |aLookup| after moving |u|.
1963 // Prefer to use putNewInfallible; this function does not check
1964 // invariants.
1965 template <typename... Args>
1966 void putNewInfallibleInternal(const Lookup& aLookup, Args&&... aArgs) {
1967 MOZ_ASSERT(mTable);
1969 HashNumber keyHash = prepareHash(aLookup);
1970 Slot slot = findNonLiveSlot(keyHash);
1972 if (slot.isRemoved()) {
1973 mRemovedCount--;
1974 keyHash |= sCollisionBit;
1977 slot.setLive(keyHash, std::forward<Args>(aArgs)...);
1978 mEntryCount++;
1979 #ifdef DEBUG
1980 mMutationCount++;
1981 #endif
1984 public:
1985 void clear() {
1986 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
1987 mRemovedCount = 0;
1988 mEntryCount = 0;
1989 #ifdef DEBUG
1990 mMutationCount++;
1991 #endif
1994 // Resize the table down to the smallest capacity that doesn't overload the
1995 // table. Since we call shrinkIfUnderloaded() on every remove, you only need
1996 // to call this after a bulk removal of items done without calling remove().
1997 void compact() {
1998 if (empty()) {
1999 // Free the entry storage.
2000 freeTable(*this, mTable, capacity());
2001 mGen++;
2002 mHashShift = hashShift(0); // gives minimum capacity on regrowth
2003 mTable = nullptr;
2004 mRemovedCount = 0;
2005 return;
2008 uint32_t bestCapacity = this->bestCapacity(mEntryCount);
2009 MOZ_ASSERT(bestCapacity <= capacity());
2011 if (bestCapacity < capacity()) {
2012 (void)changeTableSize(bestCapacity, DontReportFailure);
2016 void clearAndCompact() {
2017 clear();
2018 compact();
2021 MOZ_MUST_USE bool reserve(uint32_t aLen) {
2022 if (aLen == 0) {
2023 return true;
2026 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
2027 return false;
2030 uint32_t bestCapacity = this->bestCapacity(aLen);
2031 if (bestCapacity <= capacity()) {
2032 return true; // Capacity is already sufficient.
2035 RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
2036 MOZ_ASSERT(status != NotOverloaded);
2037 return status != RehashFailed;
2040 Iterator iter() const { return Iterator(*this); }
2042 ModIterator modIter() { return ModIterator(*this); }
2044 Range all() const { return Range(*this); }
2046 bool empty() const { return mEntryCount == 0; }
2048 uint32_t count() const { return mEntryCount; }
2050 uint32_t rawCapacity() const { return 1u << (kHashNumberBits - mHashShift); }
2052 uint32_t capacity() const { return mTable ? rawCapacity() : 0; }
2054 Generation generation() const { return Generation(mGen); }
2056 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2057 return aMallocSizeOf(mTable);
2060 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2061 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
2064 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
2065 if (empty() || !HasHash<HashPolicy>(aLookup)) {
2066 return Ptr();
2068 HashNumber keyHash = prepareHash(aLookup);
2069 return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
2072 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
2073 ReentrancyGuard g(*this);
2074 return readonlyThreadsafeLookup(aLookup);
2077 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
2078 ReentrancyGuard g(*this);
2079 if (!EnsureHash<HashPolicy>(aLookup)) {
2080 return AddPtr();
2083 HashNumber keyHash = prepareHash(aLookup);
2085 if (!mTable) {
2086 return AddPtr(*this, keyHash);
2089 // Directly call the constructor in the return statement to avoid
2090 // excess copying when building with Visual Studio 2017.
2091 // See bug 1385181.
2092 return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
2095 template <typename... Args>
2096 MOZ_MUST_USE bool add(AddPtr& aPtr, Args&&... aArgs) {
2097 ReentrancyGuard g(*this);
2098 MOZ_ASSERT_IF(aPtr.isValid(), mTable);
2099 MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this);
2100 MOZ_ASSERT(!aPtr.found());
2101 MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit));
2103 // Check for error from ensureHash() here.
2104 if (!aPtr.isLive()) {
2105 return false;
2108 MOZ_ASSERT(aPtr.mGeneration == generation());
2109 #ifdef DEBUG
2110 MOZ_ASSERT(aPtr.mMutationCount == mMutationCount);
2111 #endif
2113 if (!aPtr.isValid()) {
2114 MOZ_ASSERT(!mTable && mEntryCount == 0);
2115 uint32_t newCapacity = rawCapacity();
2116 RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
2117 MOZ_ASSERT(status != NotOverloaded);
2118 if (status == RehashFailed) {
2119 return false;
2121 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2123 } else if (aPtr.mSlot.isRemoved()) {
2124 // Changing an entry from removed to live does not affect whether we are
2125 // overloaded and can be handled separately.
2126 if (!this->checkSimulatedOOM()) {
2127 return false;
2129 mRemovedCount--;
2130 aPtr.mKeyHash |= sCollisionBit;
2132 } else {
2133 // Preserve the validity of |aPtr.mSlot|.
2134 RebuildStatus status = rehashIfOverloaded();
2135 if (status == RehashFailed) {
2136 return false;
2138 if (status == NotOverloaded && !this->checkSimulatedOOM()) {
2139 return false;
2141 if (status == Rehashed) {
2142 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2146 aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
2147 mEntryCount++;
2148 #ifdef DEBUG
2149 mMutationCount++;
2150 aPtr.mGeneration = generation();
2151 aPtr.mMutationCount = mMutationCount;
2152 #endif
2153 return true;
2156 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2157 // must take care not to use |aLookup| after moving |u|.
2158 template <typename... Args>
2159 void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
2160 MOZ_ASSERT(!lookup(aLookup).found());
2161 ReentrancyGuard g(*this);
2162 putNewInfallibleInternal(aLookup, std::forward<Args>(aArgs)...);
2165 // Note: |aLookup| may be alias arguments in |aArgs|, so this function must
2166 // take care not to use |aLookup| after moving |aArgs|.
2167 template <typename... Args>
2168 MOZ_MUST_USE bool putNew(const Lookup& aLookup, Args&&... aArgs) {
2169 if (!this->checkSimulatedOOM()) {
2170 return false;
2172 if (!EnsureHash<HashPolicy>(aLookup)) {
2173 return false;
2175 if (rehashIfOverloaded() == RehashFailed) {
2176 return false;
2178 putNewInfallible(aLookup, std::forward<Args>(aArgs)...);
2179 return true;
2182 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2183 // must take care not to use |aLookup| after moving |u|.
2184 template <typename... Args>
2185 MOZ_MUST_USE bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
2186 Args&&... aArgs) {
2187 // Check for error from ensureHash() here.
2188 if (!aPtr.isLive()) {
2189 return false;
2191 #ifdef DEBUG
2192 aPtr.mGeneration = generation();
2193 aPtr.mMutationCount = mMutationCount;
2194 #endif
2195 if (mTable) {
2196 ReentrancyGuard g(*this);
2197 // Check that aLookup has not been destroyed.
2198 MOZ_ASSERT(prepareHash(aLookup) == aPtr.mKeyHash);
2199 aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
2200 if (aPtr.found()) {
2201 return true;
2203 } else {
2204 // Clear aPtr so it's invalid; add() will allocate storage and redo the
2205 // lookup.
2206 aPtr.mSlot = Slot(nullptr, nullptr);
2208 return add(aPtr, std::forward<Args>(aArgs)...);
2211 void remove(Ptr aPtr) {
2212 MOZ_ASSERT(mTable);
2213 ReentrancyGuard g(*this);
2214 MOZ_ASSERT(aPtr.found());
2215 MOZ_ASSERT(aPtr.mGeneration == generation());
2216 remove(aPtr.mSlot);
2217 shrinkIfUnderloaded();
2220 void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2221 MOZ_ASSERT(mTable);
2222 ReentrancyGuard g(*this);
2223 MOZ_ASSERT(aPtr.found());
2224 MOZ_ASSERT(aPtr.mGeneration == generation());
2225 typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
2226 HashPolicy::setKey(t, const_cast<Key&>(aKey));
2227 remove(aPtr.mSlot);
2228 putNewInfallibleInternal(aLookup, std::move(t));
2231 void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2232 rekeyWithoutRehash(aPtr, aLookup, aKey);
2233 infallibleRehashIfOverloaded();
2237 } // namespace detail
2238 } // namespace mozilla
2240 #endif /* mozilla_HashTable_h */