Bug 1687227 [wpt PR 27213] - [TablesNG] Fix background painting for COLGROUP/COL...
[gecko.git] / mfbt / HashTable.h
blobb6bf6c1c54dc2e964ef1b891fcb499781f0e9164
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 // Like putNew(), but should be only used when the table is known to be big
269 // enough for the insertion, and hashing cannot fail. Typically this is used
270 // to populate an empty map with known-unique keys after reserving space with
271 // reserve(), e.g.
273 // using HM = HashMap<int,char>;
274 // HM h;
275 // if (!h.reserve(3)) {
276 // MOZ_CRASH("OOM");
277 // }
278 // h.putNewInfallible(1, 'a'); // unique key
279 // h.putNewInfallible(2, 'b'); // unique key
280 // h.putNewInfallible(3, 'c'); // unique key
282 template <typename KeyInput, typename ValueInput>
283 void putNewInfallible(KeyInput&& aKey, ValueInput&& aValue) {
284 mImpl.putNewInfallible(aKey, std::forward<KeyInput>(aKey),
285 std::forward<ValueInput>(aValue));
288 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
289 // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using
290 // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new key/value. E.g.:
292 // using HM = HashMap<int,char>;
293 // HM h;
294 // HM::AddPtr p = h.lookupForAdd(3);
295 // if (!p) {
296 // if (!h.add(p, 3, 'a')) {
297 // return false;
298 // }
299 // }
300 // assert(p->key() == 3);
301 // char val = p->value();
303 // N.B. The caller must ensure that no mutating hash table operations occur
304 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
305 // key a second time, the caller may use the more efficient relookupOrAdd()
306 // method. This method reuses part of the hashing computation to more
307 // efficiently insert the key if it has not been added. For example, a
308 // mutation-handling version of the previous example:
310 // HM::AddPtr p = h.lookupForAdd(3);
311 // if (!p) {
312 // call_that_may_mutate_h();
313 // if (!h.relookupOrAdd(p, 3, 'a')) {
314 // return false;
315 // }
316 // }
317 // assert(p->key() == 3);
318 // char val = p->value();
320 using AddPtr = typename Impl::AddPtr;
321 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
322 return mImpl.lookupForAdd(aLookup);
325 // Add a key/value. Returns false on OOM.
326 template <typename KeyInput, typename ValueInput>
327 MOZ_MUST_USE bool add(AddPtr& aPtr, KeyInput&& aKey, ValueInput&& aValue) {
328 return mImpl.add(aPtr, std::forward<KeyInput>(aKey),
329 std::forward<ValueInput>(aValue));
332 // See the comment above lookupForAdd() for details.
333 template <typename KeyInput, typename ValueInput>
334 MOZ_MUST_USE bool relookupOrAdd(AddPtr& aPtr, KeyInput&& aKey,
335 ValueInput&& aValue) {
336 return mImpl.relookupOrAdd(aPtr, aKey, std::forward<KeyInput>(aKey),
337 std::forward<ValueInput>(aValue));
340 // -- Removal --------------------------------------------------------------
342 // Lookup and remove the key/value matching |aLookup|, if present.
343 void remove(const Lookup& aLookup) {
344 if (Ptr p = lookup(aLookup)) {
345 remove(p);
349 // Remove a previously found key/value (assuming aPtr.found()). The map must
350 // not have been mutated in the interim.
351 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
353 // Remove all keys/values without changing the capacity.
354 void clear() { mImpl.clear(); }
356 // Like clear() followed by compact().
357 void clearAndCompact() { mImpl.clearAndCompact(); }
359 // -- Rekeying -------------------------------------------------------------
361 // Infallibly rekey one entry, if necessary. Requires that template
362 // parameters Key and HashPolicy::Lookup are the same type.
363 void rekeyIfMoved(const Key& aOldKey, const Key& aNewKey) {
364 if (aOldKey != aNewKey) {
365 rekeyAs(aOldKey, aNewKey, aNewKey);
369 // Infallibly rekey one entry if present, and return whether that happened.
370 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
371 const Key& aNewKey) {
372 if (Ptr p = lookup(aOldLookup)) {
373 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewKey);
374 return true;
376 return false;
379 // -- Iteration ------------------------------------------------------------
381 // |iter()| returns an Iterator:
383 // HashMap<int, char> h;
384 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
385 // char c = iter.get().value();
386 // }
388 using Iterator = typename Impl::Iterator;
389 Iterator iter() const { return mImpl.iter(); }
391 // |modIter()| returns a ModIterator:
393 // HashMap<int, char> h;
394 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
395 // if (iter.get().value() == 'l') {
396 // iter.remove();
397 // }
398 // }
400 // Table resize may occur in ModIterator's destructor.
401 using ModIterator = typename Impl::ModIterator;
402 ModIterator modIter() { return mImpl.modIter(); }
404 // These are similar to Iterator/ModIterator/iter(), but use different
405 // terminology.
406 using Range = typename Impl::Range;
407 using Enum = typename Impl::Enum;
408 Range all() const { return mImpl.all(); }
411 //---------------------------------------------------------------------------
412 // HashSet
413 //---------------------------------------------------------------------------
415 // HashSet is a fast hash-based set of values.
417 // Template parameter requirements:
418 // - T: movable, destructible, assignable.
419 // - HashPolicy: see the "Hash Policy" section below.
420 // - AllocPolicy: see AllocPolicy.h
422 // Note:
423 // - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by
424 // HashSet must not call back into the same HashSet object.
426 template <class T, class HashPolicy = DefaultHasher<T>,
427 class AllocPolicy = MallocAllocPolicy>
428 class HashSet {
429 // -- Implementation details -----------------------------------------------
431 // HashSet is not copyable or assignable.
432 HashSet(const HashSet& hs) = delete;
433 HashSet& operator=(const HashSet& hs) = delete;
435 struct SetHashPolicy : HashPolicy {
436 using Base = HashPolicy;
437 using KeyType = T;
439 static const KeyType& getKey(const T& aT) { return aT; }
441 static void setKey(T& aT, KeyType& aKey) { HashPolicy::rekey(aT, aKey); }
444 using Impl = detail::HashTable<const T, SetHashPolicy, AllocPolicy>;
445 Impl mImpl;
447 friend class Impl::Enum;
449 public:
450 using Lookup = typename HashPolicy::Lookup;
451 using Entry = T;
453 // -- Initialization -------------------------------------------------------
455 explicit HashSet(AllocPolicy aAllocPolicy = AllocPolicy(),
456 uint32_t aLen = Impl::sDefaultLen)
457 : mImpl(std::move(aAllocPolicy), aLen) {}
459 explicit HashSet(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}
461 // HashSet is movable.
462 HashSet(HashSet&& aRhs) = default;
463 HashSet& operator=(HashSet&& aRhs) = default;
465 // -- Status and sizing ----------------------------------------------------
467 // The set's current generation.
468 Generation generation() const { return mImpl.generation(); }
470 // Is the set empty?
471 bool empty() const { return mImpl.empty(); }
473 // Number of elements in the set.
474 uint32_t count() const { return mImpl.count(); }
476 // Number of element slots in the set. Note: resize will happen well before
477 // count() == capacity().
478 uint32_t capacity() const { return mImpl.capacity(); }
480 // The size of the set's entry storage, in bytes. If the elements contain
481 // pointers to other heap blocks, you must iterate over the set and measure
482 // them separately; hence the "shallow" prefix.
483 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
484 return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
486 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
487 return aMallocSizeOf(this) +
488 mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
491 // Attempt to minimize the capacity(). If the table is empty, this will free
492 // the empty storage and upon regrowth it will be given the minimum capacity.
493 void compact() { mImpl.compact(); }
495 // Attempt to reserve enough space to fit at least |aLen| elements. Does
496 // nothing if the map already has sufficient capacity.
497 MOZ_MUST_USE bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }
499 // -- Lookups --------------------------------------------------------------
501 // Does the set contain an element matching |aLookup|?
502 bool has(const Lookup& aLookup) const {
503 return mImpl.lookup(aLookup).found();
506 // Return a Ptr indicating whether an element matching |aLookup| is present
507 // in the set. E.g.:
509 // using HS = HashSet<int>;
510 // HS h;
511 // if (HS::Ptr p = h.lookup(3)) {
512 // assert(*p == 3); // p acts like a pointer to int
513 // }
515 using Ptr = typename Impl::Ptr;
516 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
517 return mImpl.lookup(aLookup);
520 // Like lookup(), but does not assert if two threads call it at the same
521 // time. Only use this method when none of the threads will modify the set.
522 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
523 return mImpl.readonlyThreadsafeLookup(aLookup);
526 // -- Insertions -----------------------------------------------------------
528 // Add |aU| if it is not present already. Returns false on OOM.
529 template <typename U>
530 MOZ_MUST_USE bool put(U&& aU) {
531 AddPtr p = lookupForAdd(aU);
532 return p ? true : add(p, std::forward<U>(aU));
535 // Like put(), but slightly faster. Must only be used when the given element
536 // is not already present. (In debug builds, assertions check this.)
537 template <typename U>
538 MOZ_MUST_USE bool putNew(U&& aU) {
539 return mImpl.putNew(aU, std::forward<U>(aU));
542 // Like the other putNew(), but for when |Lookup| is different to |T|.
543 template <typename U>
544 MOZ_MUST_USE bool putNew(const Lookup& aLookup, U&& aU) {
545 return mImpl.putNew(aLookup, std::forward<U>(aU));
548 // Like putNew(), but should be only used when the table is known to be big
549 // enough for the insertion, and hashing cannot fail. Typically this is used
550 // to populate an empty set with known-unique elements after reserving space
551 // with reserve(), e.g.
553 // using HS = HashMap<int>;
554 // HS h;
555 // if (!h.reserve(3)) {
556 // MOZ_CRASH("OOM");
557 // }
558 // h.putNewInfallible(1); // unique element
559 // h.putNewInfallible(2); // unique element
560 // h.putNewInfallible(3); // unique element
562 template <typename U>
563 void putNewInfallible(const Lookup& aLookup, U&& aU) {
564 mImpl.putNewInfallible(aLookup, std::forward<U>(aU));
567 // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
568 // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using
569 // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.:
571 // using HS = HashSet<int>;
572 // HS h;
573 // HS::AddPtr p = h.lookupForAdd(3);
574 // if (!p) {
575 // if (!h.add(p, 3)) {
576 // return false;
577 // }
578 // }
579 // assert(*p == 3); // p acts like a pointer to int
581 // N.B. The caller must ensure that no mutating hash table operations occur
582 // between a pair of lookupForAdd() and add() calls. To avoid looking up the
583 // key a second time, the caller may use the more efficient relookupOrAdd()
584 // method. This method reuses part of the hashing computation to more
585 // efficiently insert the key if it has not been added. For example, a
586 // mutation-handling version of the previous example:
588 // HS::AddPtr p = h.lookupForAdd(3);
589 // if (!p) {
590 // call_that_may_mutate_h();
591 // if (!h.relookupOrAdd(p, 3, 3)) {
592 // return false;
593 // }
594 // }
595 // assert(*p == 3);
597 // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the
598 // entry |t|, where the caller ensures match(l,t).
599 using AddPtr = typename Impl::AddPtr;
600 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
601 return mImpl.lookupForAdd(aLookup);
604 // Add an element. Returns false on OOM.
605 template <typename U>
606 MOZ_MUST_USE bool add(AddPtr& aPtr, U&& aU) {
607 return mImpl.add(aPtr, std::forward<U>(aU));
610 // See the comment above lookupForAdd() for details.
611 template <typename U>
612 MOZ_MUST_USE bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup, U&& aU) {
613 return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
616 // -- Removal --------------------------------------------------------------
618 // Lookup and remove the element matching |aLookup|, if present.
619 void remove(const Lookup& aLookup) {
620 if (Ptr p = lookup(aLookup)) {
621 remove(p);
625 // Remove a previously found element (assuming aPtr.found()). The set must
626 // not have been mutated in the interim.
627 void remove(Ptr aPtr) { mImpl.remove(aPtr); }
629 // Remove all keys/values without changing the capacity.
630 void clear() { mImpl.clear(); }
632 // Like clear() followed by compact().
633 void clearAndCompact() { mImpl.clearAndCompact(); }
635 // -- Rekeying -------------------------------------------------------------
637 // Infallibly rekey one entry, if present. Requires that template parameters
638 // T and HashPolicy::Lookup are the same type.
639 void rekeyIfMoved(const Lookup& aOldValue, const T& aNewValue) {
640 if (aOldValue != aNewValue) {
641 rekeyAs(aOldValue, aNewValue, aNewValue);
645 // Infallibly rekey one entry if present, and return whether that happened.
646 bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
647 const T& aNewValue) {
648 if (Ptr p = lookup(aOldLookup)) {
649 mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewValue);
650 return true;
652 return false;
655 // Infallibly replace the current key at |aPtr| with an equivalent key.
656 // Specifically, both HashPolicy::hash and HashPolicy::match must return
657 // identical results for the new and old key when applied against all
658 // possible matching values.
659 void replaceKey(Ptr aPtr, const T& aNewValue) {
660 MOZ_ASSERT(aPtr.found());
661 MOZ_ASSERT(*aPtr != aNewValue);
662 MOZ_ASSERT(HashPolicy::hash(*aPtr) == HashPolicy::hash(aNewValue));
663 MOZ_ASSERT(HashPolicy::match(*aPtr, aNewValue));
664 const_cast<T&>(*aPtr) = aNewValue;
667 // -- Iteration ------------------------------------------------------------
669 // |iter()| returns an Iterator:
671 // HashSet<int> h;
672 // for (auto iter = h.iter(); !iter.done(); iter.next()) {
673 // int i = iter.get();
674 // }
676 using Iterator = typename Impl::Iterator;
677 Iterator iter() const { return mImpl.iter(); }
679 // |modIter()| returns a ModIterator:
681 // HashSet<int> h;
682 // for (auto iter = h.modIter(); !iter.done(); iter.next()) {
683 // if (iter.get() == 42) {
684 // iter.remove();
685 // }
686 // }
688 // Table resize may occur in ModIterator's destructor.
689 using ModIterator = typename Impl::ModIterator;
690 ModIterator modIter() { return mImpl.modIter(); }
692 // These are similar to Iterator/ModIterator/iter(), but use different
693 // terminology.
694 using Range = typename Impl::Range;
695 using Enum = typename Impl::Enum;
696 Range all() const { return mImpl.all(); }
699 //---------------------------------------------------------------------------
700 // Hash Policy
701 //---------------------------------------------------------------------------
703 // A hash policy |HP| for a hash table with key-type |Key| must provide:
705 // - a type |HP::Lookup| to use to lookup table entries;
707 // - a static member function |HP::hash| that hashes lookup values:
709 // static mozilla::HashNumber hash(const Lookup&);
711 // - a static member function |HP::match| that tests equality of key and
712 // lookup values:
714 // static bool match(const Key&, const Lookup&);
716 // Normally, Lookup = Key. In general, though, different values and types of
717 // values can be used to lookup and store. If a Lookup value |l| is not equal
718 // to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
719 // true. E.g.:
721 // mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
722 // if (!p) {
723 // assert(HP::match(k, l)); // must hold
724 // h.add(p, k);
725 // }
727 // A pointer hashing policy that uses HashGeneric() to create good hashes for
728 // pointers. Note that we don't shift out the lowest k bits because we don't
729 // want to assume anything about the alignment of the pointers.
730 template <typename Key>
731 struct PointerHasher {
732 using Lookup = Key;
734 static HashNumber hash(const Lookup& aLookup) {
735 size_t word = reinterpret_cast<size_t>(aLookup);
736 return HashGeneric(word);
739 static bool match(const Key& aKey, const Lookup& aLookup) {
740 return aKey == aLookup;
743 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
746 // The default hash policy, which only works with integers.
747 template <class Key, typename>
748 struct DefaultHasher {
749 using Lookup = Key;
751 static HashNumber hash(const Lookup& aLookup) {
752 // Just convert the integer to a HashNumber and use that as is. (This
753 // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
754 // subsequently called on the value to improve the distribution.
755 return aLookup;
758 static bool match(const Key& aKey, const Lookup& aLookup) {
759 // Use builtin or overloaded operator==.
760 return aKey == aLookup;
763 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
766 // A DefaultHasher specialization for enums.
767 template <class T>
768 struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
769 using Key = T;
770 using Lookup = Key;
772 static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }
774 static bool match(const Key& aKey, const Lookup& aLookup) {
775 // Use builtin or overloaded operator==.
776 return aKey == static_cast<Key>(aLookup);
779 static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
782 // A DefaultHasher specialization for pointers.
783 template <class T>
784 struct DefaultHasher<T*> : PointerHasher<T*> {};
786 // A DefaultHasher specialization for mozilla::UniquePtr.
787 template <class T, class D>
788 struct DefaultHasher<UniquePtr<T, D>> {
789 using Key = UniquePtr<T, D>;
790 using Lookup = Key;
791 using PtrHasher = PointerHasher<T*>;
793 static HashNumber hash(const Lookup& aLookup) {
794 return PtrHasher::hash(aLookup.get());
797 static bool match(const Key& aKey, const Lookup& aLookup) {
798 return PtrHasher::match(aKey.get(), aLookup.get());
801 static void rekey(UniquePtr<T, D>& aKey, UniquePtr<T, D>&& aNewKey) {
802 aKey = std::move(aNewKey);
806 // A DefaultHasher specialization for doubles.
807 template <>
808 struct DefaultHasher<double> {
809 using Key = double;
810 using Lookup = Key;
812 static HashNumber hash(const Lookup& aLookup) {
813 // Just xor the high bits with the low bits, and then treat the bits of the
814 // result as a uint32_t.
815 static_assert(sizeof(HashNumber) == 4,
816 "subsequent code assumes a four-byte hash");
817 uint64_t u = BitwiseCast<uint64_t>(aLookup);
818 return HashNumber(u ^ (u >> 32));
821 static bool match(const Key& aKey, const Lookup& aLookup) {
822 return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
826 // A DefaultHasher specialization for floats.
827 template <>
828 struct DefaultHasher<float> {
829 using Key = float;
830 using Lookup = Key;
832 static HashNumber hash(const Lookup& aLookup) {
833 // Just use the value as if its bits form an integer. ScrambleHashCode() is
834 // subsequently called on the value to improve the distribution.
835 static_assert(sizeof(HashNumber) == 4,
836 "subsequent code assumes a four-byte hash");
837 return HashNumber(BitwiseCast<uint32_t>(aLookup));
840 static bool match(const Key& aKey, const Lookup& aLookup) {
841 return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
845 // A hash policy for C strings.
846 struct CStringHasher {
847 using Key = const char*;
848 using Lookup = const char*;
850 static HashNumber hash(const Lookup& aLookup) { return HashString(aLookup); }
852 static bool match(const Key& aKey, const Lookup& aLookup) {
853 return strcmp(aKey, aLookup) == 0;
857 //---------------------------------------------------------------------------
858 // Fallible Hashing Interface
859 //---------------------------------------------------------------------------
861 // Most of the time generating a hash code is infallible so this class provides
862 // default methods that always succeed. Specialize this class for your own hash
863 // policy to provide fallible hashing.
865 // This is used by MovableCellHasher to handle the fact that generating a unique
866 // ID for cell pointer may fail due to OOM.
867 template <typename HashPolicy>
868 struct FallibleHashMethods {
869 // Return true if a hashcode is already available for its argument. Once
870 // this returns true for a specific argument it must continue to do so.
871 template <typename Lookup>
872 static bool hasHash(Lookup&& aLookup) {
873 return true;
876 // Fallible method to ensure a hashcode exists for its argument and create
877 // one if not. Returns false on error, e.g. out of memory.
878 template <typename Lookup>
879 static bool ensureHash(Lookup&& aLookup) {
880 return true;
884 template <typename HashPolicy, typename Lookup>
885 static bool HasHash(Lookup&& aLookup) {
886 return FallibleHashMethods<typename HashPolicy::Base>::hasHash(
887 std::forward<Lookup>(aLookup));
890 template <typename HashPolicy, typename Lookup>
891 static bool EnsureHash(Lookup&& aLookup) {
892 return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
893 std::forward<Lookup>(aLookup));
896 //---------------------------------------------------------------------------
897 // Implementation Details (HashMapEntry, HashTableEntry, HashTable)
898 //---------------------------------------------------------------------------
900 // Both HashMap and HashSet are implemented by a single HashTable that is even
901 // more heavily parameterized than the other two. This leaves HashTable gnarly
902 // and extremely coupled to HashMap and HashSet; thus code should not use
903 // HashTable directly.
905 template <class Key, class Value>
906 class HashMapEntry {
907 Key key_;
908 Value value_;
910 template <class, class, class>
911 friend class detail::HashTable;
912 template <class>
913 friend class detail::HashTableEntry;
914 template <class, class, class, class>
915 friend class HashMap;
917 public:
918 template <typename KeyInput, typename ValueInput>
919 HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
920 : key_(std::forward<KeyInput>(aKey)),
921 value_(std::forward<ValueInput>(aValue)) {}
923 HashMapEntry(HashMapEntry&& aRhs) = default;
924 HashMapEntry& operator=(HashMapEntry&& aRhs) = default;
926 using KeyType = Key;
927 using ValueType = Value;
929 const Key& key() const { return key_; }
931 // Use this method with caution! If the key is changed such that its hash
932 // value also changes, the map will be left in an invalid state.
933 Key& mutableKey() { return key_; }
935 const Value& value() const { return value_; }
936 Value& value() { return value_; }
938 private:
939 HashMapEntry(const HashMapEntry&) = delete;
940 void operator=(const HashMapEntry&) = delete;
943 namespace detail {
945 template <class T, class HashPolicy, class AllocPolicy>
946 class HashTable;
948 template <typename T>
949 class EntrySlot;
951 template <typename T>
952 class HashTableEntry {
953 private:
954 using NonConstT = std::remove_const_t<T>;
956 // Instead of having a hash table entry store that looks like this:
958 // +--------+--------+--------+--------+
959 // | entry0 | entry1 | .... | entryN |
960 // +--------+--------+--------+--------+
962 // where the entries contained their cached hash code, we're going to lay out
963 // the entry store thusly:
965 // +-------+-------+-------+-------+--------+--------+--------+--------+
966 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
967 // +-------+-------+-------+-------+--------+--------+--------+--------+
969 // with all the cached hashes prior to the actual entries themselves.
971 // We do this because implementing the first strategy requires us to make
972 // HashTableEntry look roughly like:
974 // template <typename T>
975 // class HashTableEntry {
976 // HashNumber mKeyHash;
977 // T mValue;
978 // };
980 // The problem with this setup is that, depending on the layout of `T`, there
981 // may be platform ABI-mandated padding between `mKeyHash` and the first
982 // member of `T`. This ABI-mandated padding is wasted space, and can be
983 // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
984 // In such cases, we're throwing away a quarter of our entry store on padding,
985 // which is undesirable.
987 // The second layout above, namely:
989 // +-------+-------+-------+-------+--------+--------+--------+--------+
990 // | hash0 | hash1 | ... | hashN | entry0 | entry1 | .... | entryN |
991 // +-------+-------+-------+-------+--------+--------+--------+--------+
993 // means there is no wasted space between the hashes themselves, and no wasted
994 // space between the entries themselves. However, we would also like there to
995 // be no gap between the last hash and the first entry. The memory allocator
996 // guarantees the alignment of the start of the hashes. The use of a
997 // power-of-two capacity of at least 4 guarantees that the alignment of the
998 // *end* of the hash array is no less than the alignment of the start.
999 // Finally, the static_asserts here guarantee that the entries themselves
1000 // don't need to be any more aligned than the alignment of the entry store
1001 // itself.
1003 // This assertion is safe for 32-bit builds because on both Windows and Linux
1004 // (including Android), the minimum alignment for allocations larger than 8
1005 // bytes is 8 bytes, and the actual data for entries in our entry store is
1006 // guaranteed to have that alignment as well, thanks to the power-of-two
1007 // number of cached hash values stored prior to the entry data.
1009 // The allocation policy must allocate a table with at least this much
1010 // alignment.
1011 static constexpr size_t kMinimumAlignment = 8;
1013 static_assert(alignof(HashNumber) <= kMinimumAlignment,
1014 "[N*2 hashes, N*2 T values] allocation's alignment must be "
1015 "enough to align each hash");
1016 static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
1017 "subsequent N*2 T values must not require more than an even "
1018 "number of HashNumbers provides");
1020 static const HashNumber sFreeKey = 0;
1021 static const HashNumber sRemovedKey = 1;
1022 static const HashNumber sCollisionBit = 1;
1024 alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];
1026 private:
1027 template <class, class, class>
1028 friend class HashTable;
1029 template <typename>
1030 friend class EntrySlot;
1032 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
1033 // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
1034 // through |void*|. Placing the latter cast in these separate functions
1035 // breaks the chain such that affected GCC versions no longer warn/error.
1036 void* rawValuePtr() { return mValueData; }
1038 static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }
1040 HashTableEntry(const HashTableEntry&) = delete;
1041 void operator=(const HashTableEntry&) = delete;
1043 NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }
1045 void destroyStoredT() {
1046 NonConstT* ptr = valuePtr();
1047 ptr->~T();
1048 MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr));
1051 public:
1052 HashTableEntry() = default;
1054 ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this)); }
1056 void destroy() { destroyStoredT(); }
1058 void swap(HashTableEntry* aOther, bool aIsLive) {
1059 // This allows types to use Argument-Dependent-Lookup, and thus use a custom
1060 // std::swap, which is needed by types like JS::Heap and such.
1061 using std::swap;
1063 if (this == aOther) {
1064 return;
1066 if (aIsLive) {
1067 swap(*valuePtr(), *aOther->valuePtr());
1068 } else {
1069 *aOther->valuePtr() = std::move(*valuePtr());
1070 destroy();
1074 T& get() { return *valuePtr(); }
1076 NonConstT& getMutable() { return *valuePtr(); }
1079 // A slot represents a cached hash value and its associated entry stored
1080 // in the hash table. These two things are not stored in contiguous memory.
1081 template <class T>
1082 class EntrySlot {
1083 using NonConstT = std::remove_const_t<T>;
1085 using Entry = HashTableEntry<T>;
1087 Entry* mEntry;
1088 HashNumber* mKeyHash;
1090 template <class, class, class>
1091 friend class HashTable;
1093 EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
1094 : mEntry(aEntry), mKeyHash(aKeyHash) {}
1096 public:
1097 static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }
1099 EntrySlot(const EntrySlot&) = default;
1100 EntrySlot(EntrySlot&& aOther) = default;
1102 EntrySlot& operator=(const EntrySlot&) = default;
1103 EntrySlot& operator=(EntrySlot&&) = default;
1105 bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }
1107 bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }
1109 EntrySlot& operator++() {
1110 ++mEntry;
1111 ++mKeyHash;
1112 return *this;
1115 void destroy() { mEntry->destroy(); }
1117 void swap(EntrySlot& aOther) {
1118 mEntry->swap(aOther.mEntry, aOther.isLive());
1119 std::swap(*mKeyHash, *aOther.mKeyHash);
1122 T& get() const { return mEntry->get(); }
1124 NonConstT& getMutable() { return mEntry->getMutable(); }
1126 bool isFree() const { return *mKeyHash == Entry::sFreeKey; }
1128 void clearLive() {
1129 MOZ_ASSERT(isLive());
1130 *mKeyHash = Entry::sFreeKey;
1131 mEntry->destroyStoredT();
1134 void clear() {
1135 if (isLive()) {
1136 mEntry->destroyStoredT();
1138 MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry));
1139 *mKeyHash = Entry::sFreeKey;
1142 bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }
1144 void removeLive() {
1145 MOZ_ASSERT(isLive());
1146 *mKeyHash = Entry::sRemovedKey;
1147 mEntry->destroyStoredT();
1150 bool isLive() const { return isLiveHash(*mKeyHash); }
1152 void setCollision() {
1153 MOZ_ASSERT(isLive());
1154 *mKeyHash |= Entry::sCollisionBit;
1156 void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
1157 bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
1158 bool matchHash(HashNumber hn) {
1159 return (*mKeyHash & ~Entry::sCollisionBit) == hn;
1161 HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }
1163 template <typename... Args>
1164 void setLive(HashNumber aHashNumber, Args&&... aArgs) {
1165 MOZ_ASSERT(!isLive());
1166 *mKeyHash = aHashNumber;
1167 new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
1168 MOZ_ASSERT(isLive());
1171 Entry* toEntry() const { return mEntry; }
1174 template <class T, class HashPolicy, class AllocPolicy>
1175 class HashTable : private AllocPolicy {
1176 friend class mozilla::ReentrancyGuard;
1178 using NonConstT = std::remove_const_t<T>;
1179 using Key = typename HashPolicy::KeyType;
1180 using Lookup = typename HashPolicy::Lookup;
1182 public:
1183 using Entry = HashTableEntry<T>;
1184 using Slot = EntrySlot<T>;
1186 template <typename F>
1187 static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
1188 auto hashes = reinterpret_cast<HashNumber*>(aTable);
1189 auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
1190 Slot slot(entries, hashes);
1191 for (size_t i = 0; i < size_t(aCapacity); ++i) {
1192 f(slot);
1193 ++slot;
1197 // A nullable pointer to a hash table element. A Ptr |p| can be tested
1198 // either explicitly |if (p.found()) p->...| or using boolean conversion
1199 // |if (p) p->...|. Ptr objects must not be used after any mutating hash
1200 // table operations unless |generation()| is tested.
1201 class Ptr {
1202 friend class HashTable;
1204 Slot mSlot;
1205 #ifdef DEBUG
1206 const HashTable* mTable;
1207 Generation mGeneration;
1208 #endif
1210 protected:
1211 Ptr(Slot aSlot, const HashTable& aTable)
1212 : mSlot(aSlot)
1213 #ifdef DEBUG
1215 mTable(&aTable),
1216 mGeneration(aTable.generation())
1217 #endif
1221 // This constructor is used only by AddPtr() within lookupForAdd().
1222 explicit Ptr(const HashTable& aTable)
1223 : mSlot(nullptr, nullptr)
1224 #ifdef DEBUG
1226 mTable(&aTable),
1227 mGeneration(aTable.generation())
1228 #endif
1232 bool isValid() const { return !!mSlot.toEntry(); }
1234 public:
1235 Ptr()
1236 : mSlot(nullptr, nullptr)
1237 #ifdef DEBUG
1239 mTable(nullptr),
1240 mGeneration(0)
1241 #endif
1245 bool found() const {
1246 if (!isValid()) {
1247 return false;
1249 #ifdef DEBUG
1250 MOZ_ASSERT(mGeneration == mTable->generation());
1251 #endif
1252 return mSlot.isLive();
1255 explicit operator bool() const { return found(); }
1257 bool operator==(const Ptr& aRhs) const {
1258 MOZ_ASSERT(found() && aRhs.found());
1259 return mSlot == aRhs.mSlot;
1262 bool operator!=(const Ptr& aRhs) const {
1263 #ifdef DEBUG
1264 MOZ_ASSERT(mGeneration == mTable->generation());
1265 #endif
1266 return !(*this == aRhs);
1269 T& operator*() const {
1270 #ifdef DEBUG
1271 MOZ_ASSERT(found());
1272 MOZ_ASSERT(mGeneration == mTable->generation());
1273 #endif
1274 return mSlot.get();
1277 T* operator->() const {
1278 #ifdef DEBUG
1279 MOZ_ASSERT(found());
1280 MOZ_ASSERT(mGeneration == mTable->generation());
1281 #endif
1282 return &mSlot.get();
1286 // A Ptr that can be used to add a key after a failed lookup.
1287 class AddPtr : public Ptr {
1288 friend class HashTable;
1290 HashNumber mKeyHash;
1291 #ifdef DEBUG
1292 uint64_t mMutationCount;
1293 #endif
1295 AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
1296 : Ptr(aSlot, aTable),
1297 mKeyHash(aHashNumber)
1298 #ifdef DEBUG
1300 mMutationCount(aTable.mMutationCount)
1301 #endif
1305 // This constructor is used when lookupForAdd() is performed on a table
1306 // lacking entry storage; it leaves mSlot null but initializes everything
1307 // else.
1308 AddPtr(const HashTable& aTable, HashNumber aHashNumber)
1309 : Ptr(aTable),
1310 mKeyHash(aHashNumber)
1311 #ifdef DEBUG
1313 mMutationCount(aTable.mMutationCount)
1314 #endif
1316 MOZ_ASSERT(isLive());
1319 bool isLive() const { return isLiveHash(mKeyHash); }
1321 public:
1322 AddPtr() : mKeyHash(0) {}
1325 // A hash table iterator that (mostly) doesn't allow table modifications.
1326 // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
1327 // hash table operation unless the |generation()| is tested.
1328 class Iterator {
1329 void moveToNextLiveEntry() {
1330 while (++mCur < mEnd && !mCur.isLive()) {
1331 continue;
1335 protected:
1336 friend class HashTable;
1338 explicit Iterator(const HashTable& aTable)
1339 : mCur(aTable.slotForIndex(0)),
1340 mEnd(aTable.slotForIndex(aTable.capacity()))
1341 #ifdef DEBUG
1343 mTable(aTable),
1344 mMutationCount(aTable.mMutationCount),
1345 mGeneration(aTable.generation()),
1346 mValidEntry(true)
1347 #endif
1349 if (!done() && !mCur.isLive()) {
1350 moveToNextLiveEntry();
1354 Slot mCur;
1355 Slot mEnd;
1356 #ifdef DEBUG
1357 const HashTable& mTable;
1358 uint64_t mMutationCount;
1359 Generation mGeneration;
1360 bool mValidEntry;
1361 #endif
1363 public:
1364 bool done() const {
1365 MOZ_ASSERT(mGeneration == mTable.generation());
1366 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1367 return mCur == mEnd;
1370 T& get() const {
1371 MOZ_ASSERT(!done());
1372 MOZ_ASSERT(mValidEntry);
1373 MOZ_ASSERT(mGeneration == mTable.generation());
1374 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1375 return mCur.get();
1378 void next() {
1379 MOZ_ASSERT(!done());
1380 MOZ_ASSERT(mGeneration == mTable.generation());
1381 MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
1382 moveToNextLiveEntry();
1383 #ifdef DEBUG
1384 mValidEntry = true;
1385 #endif
1389 // A hash table iterator that permits modification, removal and rekeying.
1390 // Since rehashing when elements were removed during enumeration would be
1391 // bad, it is postponed until the ModIterator is destructed. Since the
1392 // ModIterator's destructor touches the hash table, the user must ensure
1393 // that the hash table is still alive when the destructor runs.
1394 class ModIterator : public Iterator {
1395 friend class HashTable;
1397 HashTable& mTable;
1398 bool mRekeyed;
1399 bool mRemoved;
1401 // ModIterator is movable but not copyable.
1402 ModIterator(const ModIterator&) = delete;
1403 void operator=(const ModIterator&) = delete;
1405 protected:
1406 explicit ModIterator(HashTable& aTable)
1407 : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}
1409 public:
1410 MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
1411 : Iterator(aOther),
1412 mTable(aOther.mTable),
1413 mRekeyed(aOther.mRekeyed),
1414 mRemoved(aOther.mRemoved) {
1415 aOther.mRekeyed = false;
1416 aOther.mRemoved = false;
1419 // Removes the current element from the table, leaving |get()|
1420 // invalid until the next call to |next()|.
1421 void remove() {
1422 mTable.remove(this->mCur);
1423 mRemoved = true;
1424 #ifdef DEBUG
1425 this->mValidEntry = false;
1426 this->mMutationCount = mTable.mMutationCount;
1427 #endif
1430 NonConstT& getMutable() {
1431 MOZ_ASSERT(!this->done());
1432 MOZ_ASSERT(this->mValidEntry);
1433 MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation());
1434 MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount);
1435 return this->mCur.getMutable();
1438 // Removes the current element and re-inserts it into the table with
1439 // a new key at the new Lookup position. |get()| is invalid after
1440 // this operation until the next call to |next()|.
1441 void rekey(const Lookup& l, const Key& k) {
1442 MOZ_ASSERT(&k != &HashPolicy::getKey(this->mCur.get()));
1443 Ptr p(this->mCur, mTable);
1444 mTable.rekeyWithoutRehash(p, l, k);
1445 mRekeyed = true;
1446 #ifdef DEBUG
1447 this->mValidEntry = false;
1448 this->mMutationCount = mTable.mMutationCount;
1449 #endif
1452 void rekey(const Key& k) { rekey(k, k); }
1454 // Potentially rehashes the table.
1455 ~ModIterator() {
1456 if (mRekeyed) {
1457 mTable.mGen++;
1458 mTable.infallibleRehashIfOverloaded();
1461 if (mRemoved) {
1462 mTable.compact();
1467 // Range is similar to Iterator, but uses different terminology.
1468 class Range {
1469 friend class HashTable;
1471 Iterator mIter;
1473 protected:
1474 explicit Range(const HashTable& table) : mIter(table) {}
1476 public:
1477 bool empty() const { return mIter.done(); }
1479 T& front() const { return mIter.get(); }
1481 void popFront() { return mIter.next(); }
1484 // Enum is similar to ModIterator, but uses different terminology.
1485 class Enum {
1486 ModIterator mIter;
1488 // Enum is movable but not copyable.
1489 Enum(const Enum&) = delete;
1490 void operator=(const Enum&) = delete;
1492 public:
1493 template <class Map>
1494 explicit Enum(Map& map) : mIter(map.mImpl) {}
1496 MOZ_IMPLICIT Enum(Enum&& other) : mIter(std::move(other.mIter)) {}
1498 bool empty() const { return mIter.done(); }
1500 T& front() const { return mIter.get(); }
1502 void popFront() { return mIter.next(); }
1504 void removeFront() { mIter.remove(); }
1506 NonConstT& mutableFront() { return mIter.getMutable(); }
1508 void rekeyFront(const Lookup& aLookup, const Key& aKey) {
1509 mIter.rekey(aLookup, aKey);
1512 void rekeyFront(const Key& aKey) { mIter.rekey(aKey); }
1515 // HashTable is movable
1516 HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
1517 HashTable& operator=(HashTable&& aRhs) {
1518 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
1519 if (mTable) {
1520 destroyTable(*this, mTable, capacity());
1522 AllocPolicy::operator=(std::move(aRhs));
1523 moveFrom(aRhs);
1524 return *this;
1527 private:
1528 void moveFrom(HashTable& aRhs) {
1529 mGen = aRhs.mGen;
1530 mHashShift = aRhs.mHashShift;
1531 mTable = aRhs.mTable;
1532 mEntryCount = aRhs.mEntryCount;
1533 mRemovedCount = aRhs.mRemovedCount;
1534 #ifdef DEBUG
1535 mMutationCount = aRhs.mMutationCount;
1536 mEntered = aRhs.mEntered;
1537 #endif
1538 aRhs.mTable = nullptr;
1539 aRhs.clearAndCompact();
1542 // HashTable is not copyable or assignable
1543 HashTable(const HashTable&) = delete;
1544 void operator=(const HashTable&) = delete;
1546 static const uint32_t CAP_BITS = 30;
1548 public:
1549 uint64_t mGen : 56; // entry storage generation number
1550 uint64_t mHashShift : 8; // multiplicative hash shift
1551 char* mTable; // entry storage
1552 uint32_t mEntryCount; // number of entries in mTable
1553 uint32_t mRemovedCount; // removed entry sentinels in mTable
1555 #ifdef DEBUG
1556 uint64_t mMutationCount;
1557 mutable bool mEntered;
1558 #endif
1560 // The default initial capacity is 32 (enough to hold 16 elements), but it
1561 // can be as low as 4.
1562 static const uint32_t sDefaultLen = 16;
1563 static const uint32_t sMinCapacity = 4;
1564 // See the comments in HashTableEntry about this value.
1565 static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
1566 static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
1567 static const uint32_t sMaxCapacity = 1u << CAP_BITS;
1569 // Hash-table alpha is conceptually a fraction, but to avoid floating-point
1570 // math we implement it as a ratio of integers.
1571 static const uint8_t sAlphaDenominator = 4;
1572 static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4
1573 static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4
1575 static const HashNumber sFreeKey = Entry::sFreeKey;
1576 static const HashNumber sRemovedKey = Entry::sRemovedKey;
1577 static const HashNumber sCollisionBit = Entry::sCollisionBit;
1579 static uint32_t bestCapacity(uint32_t aLen) {
1580 static_assert(
1581 (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
1582 "multiplication in numerator below could overflow");
1583 static_assert(
1584 sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator,
1585 "numerator calculation below could potentially overflow");
1587 // Callers should ensure this is true.
1588 MOZ_ASSERT(aLen <= sMaxInit);
1590 // Compute the smallest capacity allowing |aLen| elements to be
1591 // inserted without rehashing: ceil(aLen / max-alpha). (Ceiling
1592 // integral division: <http://stackoverflow.com/a/2745086>.)
1593 uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
1594 sMaxAlphaNumerator;
1595 capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);
1597 MOZ_ASSERT(capacity >= aLen);
1598 MOZ_ASSERT(capacity <= sMaxCapacity);
1600 return capacity;
1603 static uint32_t hashShift(uint32_t aLen) {
1604 // Reject all lengths whose initial computed capacity would exceed
1605 // sMaxCapacity. Round that maximum aLen down to the nearest power of two
1606 // for speedier code.
1607 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
1608 MOZ_CRASH("initial length is too large");
1611 return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
1614 static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }
1616 static HashNumber prepareHash(const Lookup& aLookup) {
1617 HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(aLookup));
1619 // Avoid reserved hash codes.
1620 if (!isLiveHash(keyHash)) {
1621 keyHash -= (sRemovedKey + 1);
1623 return keyHash & ~sCollisionBit;
1626 enum FailureBehavior { DontReportFailure = false, ReportFailure = true };
1628 // Fake a struct that we're going to alloc. See the comments in
1629 // HashTableEntry about how the table is laid out, and why it's safe.
1630 struct FakeSlot {
1631 unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
1634 static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
1635 FailureBehavior aReportFailure = ReportFailure) {
1636 FakeSlot* fake =
1637 aReportFailure
1638 ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
1639 : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);
1641 MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==
1644 char* table = reinterpret_cast<char*>(fake);
1645 if (table) {
1646 forEachSlot(table, aCapacity, [&](Slot& slot) {
1647 *slot.mKeyHash = sFreeKey;
1648 new (KnownNotNull, slot.toEntry()) Entry();
1651 return table;
1654 static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1655 uint32_t aCapacity) {
1656 forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
1657 if (slot.isLive()) {
1658 slot.toEntry()->destroyStoredT();
1661 freeTable(aAllocPolicy, aOldTable, aCapacity);
1664 static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
1665 uint32_t aCapacity) {
1666 FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
1667 aAllocPolicy.free_(fake, aCapacity);
1670 public:
1671 HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
1672 : AllocPolicy(std::move(aAllocPolicy)),
1673 mGen(0),
1674 mHashShift(hashShift(aLen)),
1675 mTable(nullptr),
1676 mEntryCount(0),
1677 mRemovedCount(0)
1678 #ifdef DEBUG
1680 mMutationCount(0),
1681 mEntered(false)
1682 #endif
1686 explicit HashTable(AllocPolicy aAllocPolicy)
1687 : HashTable(aAllocPolicy, sDefaultLen) {}
1689 ~HashTable() {
1690 if (mTable) {
1691 destroyTable(*this, mTable, capacity());
1695 private:
1696 HashNumber hash1(HashNumber aHash0) const { return aHash0 >> mHashShift; }
1698 struct DoubleHash {
1699 HashNumber mHash2;
1700 HashNumber mSizeMask;
1703 DoubleHash hash2(HashNumber aCurKeyHash) const {
1704 uint32_t sizeLog2 = kHashNumberBits - mHashShift;
1705 DoubleHash dh = {((aCurKeyHash << sizeLog2) >> mHashShift) | 1,
1706 (HashNumber(1) << sizeLog2) - 1};
1707 return dh;
1710 static HashNumber applyDoubleHash(HashNumber aHash1,
1711 const DoubleHash& aDoubleHash) {
1712 return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
1715 static MOZ_ALWAYS_INLINE bool match(T& aEntry, const Lookup& aLookup) {
1716 return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
1719 enum LookupReason { ForNonAdd, ForAdd };
1721 Slot slotForIndex(HashNumber aIndex) const {
1722 auto hashes = reinterpret_cast<HashNumber*>(mTable);
1723 auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
1724 return Slot(&entries[aIndex], &hashes[aIndex]);
1727 // Warning: in order for readonlyThreadsafeLookup() to be safe this
1728 // function must not modify the table in any way when Reason==ForNonAdd.
1729 template <LookupReason Reason>
1730 MOZ_ALWAYS_INLINE Slot lookup(const Lookup& aLookup,
1731 HashNumber aKeyHash) const {
1732 MOZ_ASSERT(isLiveHash(aKeyHash));
1733 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1734 MOZ_ASSERT(mTable);
1736 // Compute the primary hash address.
1737 HashNumber h1 = hash1(aKeyHash);
1738 Slot slot = slotForIndex(h1);
1740 // Miss: return space for a new entry.
1741 if (slot.isFree()) {
1742 return slot;
1745 // Hit: return entry.
1746 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1747 return slot;
1750 // Collision: double hash.
1751 DoubleHash dh = hash2(aKeyHash);
1753 // Save the first removed entry pointer so we can recycle later.
1754 Maybe<Slot> firstRemoved;
1756 while (true) {
1757 if (Reason == ForAdd && !firstRemoved) {
1758 if (MOZ_UNLIKELY(slot.isRemoved())) {
1759 firstRemoved.emplace(slot);
1760 } else {
1761 slot.setCollision();
1765 h1 = applyDoubleHash(h1, dh);
1767 slot = slotForIndex(h1);
1768 if (slot.isFree()) {
1769 return firstRemoved.refOr(slot);
1772 if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
1773 return slot;
1778 // This is a copy of lookup() hardcoded to the assumptions:
1779 // 1. the lookup is for an add;
1780 // 2. the key, whose |keyHash| has been passed, is not in the table.
1781 Slot findNonLiveSlot(HashNumber aKeyHash) {
1782 MOZ_ASSERT(!(aKeyHash & sCollisionBit));
1783 MOZ_ASSERT(mTable);
1785 // We assume 'aKeyHash' has already been distributed.
1787 // Compute the primary hash address.
1788 HashNumber h1 = hash1(aKeyHash);
1789 Slot slot = slotForIndex(h1);
1791 // Miss: return space for a new entry.
1792 if (!slot.isLive()) {
1793 return slot;
1796 // Collision: double hash.
1797 DoubleHash dh = hash2(aKeyHash);
1799 while (true) {
1800 slot.setCollision();
1802 h1 = applyDoubleHash(h1, dh);
1804 slot = slotForIndex(h1);
1805 if (!slot.isLive()) {
1806 return slot;
1811 enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };
1813 RebuildStatus changeTableSize(
1814 uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
1815 MOZ_ASSERT(IsPowerOfTwo(newCapacity));
1816 MOZ_ASSERT(!!mTable == !!capacity());
1818 // Look, but don't touch, until we succeed in getting new entry store.
1819 char* oldTable = mTable;
1820 uint32_t oldCapacity = capacity();
1821 uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);
1823 if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) {
1824 if (aReportFailure) {
1825 this->reportAllocOverflow();
1827 return RehashFailed;
1830 char* newTable = createTable(*this, newCapacity, aReportFailure);
1831 if (!newTable) {
1832 return RehashFailed;
1835 // We can't fail from here on, so update table parameters.
1836 mHashShift = kHashNumberBits - newLog2;
1837 mRemovedCount = 0;
1838 mGen++;
1839 mTable = newTable;
1841 // Copy only live entries, leaving removed ones behind.
1842 forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
1843 if (slot.isLive()) {
1844 HashNumber hn = slot.getKeyHash();
1845 findNonLiveSlot(hn).setLive(
1846 hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
1849 slot.clear();
1852 // All entries have been destroyed, no need to destroyTable.
1853 freeTable(*this, oldTable, oldCapacity);
1854 return Rehashed;
1857 RebuildStatus rehashIfOverloaded(
1858 FailureBehavior aReportFailure = ReportFailure) {
1859 static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator,
1860 "multiplication below could overflow");
1862 // Note: if capacity() is zero, this will always succeed, which is
1863 // what we want.
1864 bool overloaded = mEntryCount + mRemovedCount >=
1865 capacity() * sMaxAlphaNumerator / sAlphaDenominator;
1867 if (!overloaded) {
1868 return NotOverloaded;
1871 // Succeed if a quarter or more of all entries are removed. Note that this
1872 // always succeeds if capacity() == 0 (i.e. entry storage has not been
1873 // allocated), which is what we want, because it means changeTableSize()
1874 // will allocate the requested capacity rather than doubling it.
1875 bool manyRemoved = mRemovedCount >= (capacity() >> 2);
1876 uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
1877 return changeTableSize(newCapacity, aReportFailure);
1880 void infallibleRehashIfOverloaded() {
1881 if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
1882 rehashTableInPlace();
1886 void remove(Slot& aSlot) {
1887 MOZ_ASSERT(mTable);
1889 if (aSlot.hasCollision()) {
1890 aSlot.removeLive();
1891 mRemovedCount++;
1892 } else {
1893 aSlot.clearLive();
1895 mEntryCount--;
1896 #ifdef DEBUG
1897 mMutationCount++;
1898 #endif
1901 void shrinkIfUnderloaded() {
1902 static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator,
1903 "multiplication below could overflow");
1904 bool underloaded =
1905 capacity() > sMinCapacity &&
1906 mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;
1908 if (underloaded) {
1909 (void)changeTableSize(capacity() / 2, DontReportFailure);
1913 // This is identical to changeTableSize(currentSize), but without requiring
1914 // a second table. We do this by recycling the collision bits to tell us if
1915 // the element is already inserted or still waiting to be inserted. Since
1916 // already-inserted elements win any conflicts, we get the same table as we
1917 // would have gotten through random insertion order.
1918 void rehashTableInPlace() {
1919 mRemovedCount = 0;
1920 mGen++;
1921 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
1922 for (uint32_t i = 0; i < capacity();) {
1923 Slot src = slotForIndex(i);
1925 if (!src.isLive() || src.hasCollision()) {
1926 ++i;
1927 continue;
1930 HashNumber keyHash = src.getKeyHash();
1931 HashNumber h1 = hash1(keyHash);
1932 DoubleHash dh = hash2(keyHash);
1933 Slot tgt = slotForIndex(h1);
1934 while (true) {
1935 if (!tgt.hasCollision()) {
1936 src.swap(tgt);
1937 tgt.setCollision();
1938 break;
1941 h1 = applyDoubleHash(h1, dh);
1942 tgt = slotForIndex(h1);
1946 // TODO: this algorithm leaves collision bits on *all* elements, even if
1947 // they are on no collision path. We have the option of setting the
1948 // collision bits correctly on a subsequent pass or skipping the rehash
1949 // unless we are totally filled with tombstones: benchmark to find out
1950 // which approach is best.
1953 // Note: |aLookup| may be a reference to a piece of |u|, so this function
1954 // must take care not to use |aLookup| after moving |u|.
1956 // Prefer to use putNewInfallible; this function does not check
1957 // invariants.
1958 template <typename... Args>
1959 void putNewInfallibleInternal(const Lookup& aLookup, Args&&... aArgs) {
1960 MOZ_ASSERT(mTable);
1962 HashNumber keyHash = prepareHash(aLookup);
1963 Slot slot = findNonLiveSlot(keyHash);
1965 if (slot.isRemoved()) {
1966 mRemovedCount--;
1967 keyHash |= sCollisionBit;
1970 slot.setLive(keyHash, std::forward<Args>(aArgs)...);
1971 mEntryCount++;
1972 #ifdef DEBUG
1973 mMutationCount++;
1974 #endif
1977 public:
1978 void clear() {
1979 forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
1980 mRemovedCount = 0;
1981 mEntryCount = 0;
1982 #ifdef DEBUG
1983 mMutationCount++;
1984 #endif
1987 // Resize the table down to the smallest capacity that doesn't overload the
1988 // table. Since we call shrinkIfUnderloaded() on every remove, you only need
1989 // to call this after a bulk removal of items done without calling remove().
1990 void compact() {
1991 if (empty()) {
1992 // Free the entry storage.
1993 freeTable(*this, mTable, capacity());
1994 mGen++;
1995 mHashShift = hashShift(0); // gives minimum capacity on regrowth
1996 mTable = nullptr;
1997 mRemovedCount = 0;
1998 return;
2001 uint32_t bestCapacity = this->bestCapacity(mEntryCount);
2002 MOZ_ASSERT(bestCapacity <= capacity());
2004 if (bestCapacity < capacity()) {
2005 (void)changeTableSize(bestCapacity, DontReportFailure);
2009 void clearAndCompact() {
2010 clear();
2011 compact();
2014 MOZ_MUST_USE bool reserve(uint32_t aLen) {
2015 if (aLen == 0) {
2016 return true;
2019 if (MOZ_UNLIKELY(aLen > sMaxInit)) {
2020 return false;
2023 uint32_t bestCapacity = this->bestCapacity(aLen);
2024 if (bestCapacity <= capacity()) {
2025 return true; // Capacity is already sufficient.
2028 RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
2029 MOZ_ASSERT(status != NotOverloaded);
2030 return status != RehashFailed;
2033 Iterator iter() const { return Iterator(*this); }
2035 ModIterator modIter() { return ModIterator(*this); }
2037 Range all() const { return Range(*this); }
2039 bool empty() const { return mEntryCount == 0; }
2041 uint32_t count() const { return mEntryCount; }
2043 uint32_t rawCapacity() const { return 1u << (kHashNumberBits - mHashShift); }
2045 uint32_t capacity() const { return mTable ? rawCapacity() : 0; }
2047 Generation generation() const { return Generation(mGen); }
2049 size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2050 return aMallocSizeOf(mTable);
2053 size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2054 return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
2057 MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
2058 if (empty() || !HasHash<HashPolicy>(aLookup)) {
2059 return Ptr();
2061 HashNumber keyHash = prepareHash(aLookup);
2062 return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
2065 MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
2066 ReentrancyGuard g(*this);
2067 return readonlyThreadsafeLookup(aLookup);
2070 MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
2071 ReentrancyGuard g(*this);
2072 if (!EnsureHash<HashPolicy>(aLookup)) {
2073 return AddPtr();
2076 HashNumber keyHash = prepareHash(aLookup);
2078 if (!mTable) {
2079 return AddPtr(*this, keyHash);
2082 // Directly call the constructor in the return statement to avoid
2083 // excess copying when building with Visual Studio 2017.
2084 // See bug 1385181.
2085 return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
2088 template <typename... Args>
2089 MOZ_MUST_USE bool add(AddPtr& aPtr, Args&&... aArgs) {
2090 ReentrancyGuard g(*this);
2091 MOZ_ASSERT_IF(aPtr.isValid(), mTable);
2092 MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this);
2093 MOZ_ASSERT(!aPtr.found());
2094 MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit));
2096 // Check for error from ensureHash() here.
2097 if (!aPtr.isLive()) {
2098 return false;
2101 MOZ_ASSERT(aPtr.mGeneration == generation());
2102 #ifdef DEBUG
2103 MOZ_ASSERT(aPtr.mMutationCount == mMutationCount);
2104 #endif
2106 if (!aPtr.isValid()) {
2107 MOZ_ASSERT(!mTable && mEntryCount == 0);
2108 uint32_t newCapacity = rawCapacity();
2109 RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
2110 MOZ_ASSERT(status != NotOverloaded);
2111 if (status == RehashFailed) {
2112 return false;
2114 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2116 } else if (aPtr.mSlot.isRemoved()) {
2117 // Changing an entry from removed to live does not affect whether we are
2118 // overloaded and can be handled separately.
2119 if (!this->checkSimulatedOOM()) {
2120 return false;
2122 mRemovedCount--;
2123 aPtr.mKeyHash |= sCollisionBit;
2125 } else {
2126 // Preserve the validity of |aPtr.mSlot|.
2127 RebuildStatus status = rehashIfOverloaded();
2128 if (status == RehashFailed) {
2129 return false;
2131 if (status == NotOverloaded && !this->checkSimulatedOOM()) {
2132 return false;
2134 if (status == Rehashed) {
2135 aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
2139 aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
2140 mEntryCount++;
2141 #ifdef DEBUG
2142 mMutationCount++;
2143 aPtr.mGeneration = generation();
2144 aPtr.mMutationCount = mMutationCount;
2145 #endif
2146 return true;
2149 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2150 // must take care not to use |aLookup| after moving |u|.
2151 template <typename... Args>
2152 void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
2153 MOZ_ASSERT(!lookup(aLookup).found());
2154 ReentrancyGuard g(*this);
2155 putNewInfallibleInternal(aLookup, std::forward<Args>(aArgs)...);
2158 // Note: |aLookup| may be alias arguments in |aArgs|, so this function must
2159 // take care not to use |aLookup| after moving |aArgs|.
2160 template <typename... Args>
2161 MOZ_MUST_USE bool putNew(const Lookup& aLookup, Args&&... aArgs) {
2162 if (!this->checkSimulatedOOM()) {
2163 return false;
2165 if (!EnsureHash<HashPolicy>(aLookup)) {
2166 return false;
2168 if (rehashIfOverloaded() == RehashFailed) {
2169 return false;
2171 putNewInfallible(aLookup, std::forward<Args>(aArgs)...);
2172 return true;
2175 // Note: |aLookup| may be a reference to a piece of |u|, so this function
2176 // must take care not to use |aLookup| after moving |u|.
2177 template <typename... Args>
2178 MOZ_MUST_USE bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
2179 Args&&... aArgs) {
2180 // Check for error from ensureHash() here.
2181 if (!aPtr.isLive()) {
2182 return false;
2184 #ifdef DEBUG
2185 aPtr.mGeneration = generation();
2186 aPtr.mMutationCount = mMutationCount;
2187 #endif
2188 if (mTable) {
2189 ReentrancyGuard g(*this);
2190 // Check that aLookup has not been destroyed.
2191 MOZ_ASSERT(prepareHash(aLookup) == aPtr.mKeyHash);
2192 aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
2193 if (aPtr.found()) {
2194 return true;
2196 } else {
2197 // Clear aPtr so it's invalid; add() will allocate storage and redo the
2198 // lookup.
2199 aPtr.mSlot = Slot(nullptr, nullptr);
2201 return add(aPtr, std::forward<Args>(aArgs)...);
2204 void remove(Ptr aPtr) {
2205 MOZ_ASSERT(mTable);
2206 ReentrancyGuard g(*this);
2207 MOZ_ASSERT(aPtr.found());
2208 MOZ_ASSERT(aPtr.mGeneration == generation());
2209 remove(aPtr.mSlot);
2210 shrinkIfUnderloaded();
2213 void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2214 MOZ_ASSERT(mTable);
2215 ReentrancyGuard g(*this);
2216 MOZ_ASSERT(aPtr.found());
2217 MOZ_ASSERT(aPtr.mGeneration == generation());
2218 typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
2219 HashPolicy::setKey(t, const_cast<Key&>(aKey));
2220 remove(aPtr.mSlot);
2221 putNewInfallibleInternal(aLookup, std::move(t));
2224 void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
2225 rekeyWithoutRehash(aPtr, aLookup, aKey);
2226 infallibleRehashIfOverloaded();
2230 } // namespace detail
2231 } // namespace mozilla
2233 #endif /* mozilla_HashTable_h */