2 * Copyright (C) 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 David Levin <levin@chromium.org>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
22 #ifndef WTF_HashTable_h
23 #define WTF_HashTable_h
25 #include "Alignment.h"
26 #include "Assertions.h"
27 #include "FastMalloc.h"
28 #include "HashTraits.h"
29 #include "StdLibExtras.h"
30 #include "Threading.h"
31 #include "ValueCheck.h"
35 #define DUMP_HASHTABLE_STATS 0
36 // Enables internal WTF consistency checks that are invoked automatically. Non-WTF callers can call checkTableConsistency() even if internal checks are disabled.
37 #define CHECK_HASHTABLE_CONSISTENCY 0
40 #define CHECK_HASHTABLE_ITERATORS 0
41 #define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 0
43 #define CHECK_HASHTABLE_ITERATORS 1
44 #define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 1
47 #if DUMP_HASHTABLE_STATS
49 struct HashTableStats {
51 // All of the variables are accessed in ~HashTableStats when the static struct is destroyed.
53 // The following variables are all atomically incremented when modified.
54 static int numAccesses;
55 static int numRehashes;
56 static int numRemoves;
57 static int numReinserts;
59 // The following variables are only modified in the recordCollisionAtCount method within a mutex.
60 static int maxCollisions;
61 static int numCollisions;
62 static int collisionGraph[4096];
64 static void recordCollisionAtCount(int count);
69 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
71 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
72 class HashTableIterator;
73 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
74 class HashTableConstIterator;
76 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
77 void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
78 HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
80 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
81 void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
83 #if !CHECK_HASHTABLE_ITERATORS
85 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
86 inline void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
87 HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
89 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
90 inline void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
94 typedef enum { HashItemKnownGood } HashItemKnownGoodTag;
96 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
97 class HashTableConstIterator {
99 typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
100 typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
101 typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
102 typedef Value ValueType;
103 typedef const ValueType& ReferenceType;
104 typedef const ValueType* PointerType;
106 friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
107 friend class HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
109 void skipEmptyBuckets()
111 while (m_position != m_endPosition && HashTableType::isEmptyOrDeletedBucket(*m_position))
115 HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition)
116 : m_position(position), m_endPosition(endPosition)
118 addIterator(table, this);
122 HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition, HashItemKnownGoodTag)
123 : m_position(position), m_endPosition(endPosition)
125 addIterator(table, this);
129 HashTableConstIterator()
131 addIterator(static_cast<const HashTableType*>(0), this);
134 // default copy, assignment and destructor are OK if CHECK_HASHTABLE_ITERATORS is 0
136 #if CHECK_HASHTABLE_ITERATORS
137 ~HashTableConstIterator()
139 removeIterator(this);
142 HashTableConstIterator(const const_iterator& other)
143 : m_position(other.m_position), m_endPosition(other.m_endPosition)
145 addIterator(other.m_table, this);
148 const_iterator& operator=(const const_iterator& other)
150 m_position = other.m_position;
151 m_endPosition = other.m_endPosition;
153 removeIterator(this);
154 addIterator(other.m_table, this);
160 PointerType get() const
165 ReferenceType operator*() const { return *get(); }
166 PointerType operator->() const { return get(); }
168 const_iterator& operator++()
171 ASSERT(m_position != m_endPosition);
177 // postfix ++ intentionally omitted
180 bool operator==(const const_iterator& other) const
182 checkValidity(other);
183 return m_position == other.m_position;
185 bool operator!=(const const_iterator& other) const
187 checkValidity(other);
188 return m_position != other.m_position;
192 void checkValidity() const
194 #if CHECK_HASHTABLE_ITERATORS
200 #if CHECK_HASHTABLE_ITERATORS
201 void checkValidity(const const_iterator& other) const
204 ASSERT_UNUSED(other, other.m_table);
205 ASSERT(m_table == other.m_table);
208 void checkValidity(const const_iterator&) const { }
211 PointerType m_position;
212 PointerType m_endPosition;
214 #if CHECK_HASHTABLE_ITERATORS
216 // Any modifications of the m_next or m_previous of an iterator that is in a linked list of a HashTable::m_iterator,
217 // should be guarded with m_table->m_mutex.
218 mutable const HashTableType* m_table;
219 mutable const_iterator* m_next;
220 mutable const_iterator* m_previous;
224 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
225 class HashTableIterator {
227 typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
228 typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
229 typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
230 typedef Value ValueType;
231 typedef ValueType& ReferenceType;
232 typedef ValueType* PointerType;
234 friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
236 HashTableIterator(HashTableType* table, PointerType pos, PointerType end) : m_iterator(table, pos, end) { }
237 HashTableIterator(HashTableType* table, PointerType pos, PointerType end, HashItemKnownGoodTag tag) : m_iterator(table, pos, end, tag) { }
240 HashTableIterator() { }
242 // default copy, assignment and destructor are OK
244 PointerType get() const { return const_cast<PointerType>(m_iterator.get()); }
245 ReferenceType operator*() const { return *get(); }
246 PointerType operator->() const { return get(); }
248 iterator& operator++() { ++m_iterator; return *this; }
250 // postfix ++ intentionally omitted
253 bool operator==(const iterator& other) const { return m_iterator == other.m_iterator; }
254 bool operator!=(const iterator& other) const { return m_iterator != other.m_iterator; }
256 operator const_iterator() const { return m_iterator; }
259 const_iterator m_iterator;
264 // Work around MSVC's standard library, whose swap for pairs does not swap by component.
265 template<typename T> inline void hashTableSwap(T& a, T& b)
270 // Swap pairs by component, in case of pair members that specialize swap.
271 template<typename T, typename U> inline void hashTableSwap(pair<T, U>& a, pair<T, U>& b)
273 swap(a.first, b.first);
274 swap(a.second, b.second);
277 template<typename T, bool useSwap> struct Mover;
278 template<typename T> struct Mover<T, true> { static void move(T& from, T& to) { hashTableSwap(from, to); } };
279 template<typename T> struct Mover<T, false> { static void move(T& from, T& to) { to = from; } };
281 template<typename Key, typename Value, typename HashFunctions> class IdentityHashTranslator {
283 static unsigned hash(const Key& key) { return HashFunctions::hash(key); }
284 static bool equal(const Key& a, const Key& b) { return HashFunctions::equal(a, b); }
285 static void translate(Value& location, const Key&, const Value& value) { location = value; }
288 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
291 typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
292 typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
293 typedef Traits ValueTraits;
295 typedef Value ValueType;
296 typedef IdentityHashTranslator<Key, Value, HashFunctions> IdentityTranslatorType;
301 invalidateIterators();
302 deallocateTable(m_table, m_tableSize);
303 #if CHECK_HASHTABLE_USE_AFTER_DESTRUCTION
304 m_table = (ValueType*)(uintptr_t)0xbbadbeef;
308 HashTable(const HashTable&);
309 void swap(HashTable&);
310 HashTable& operator=(const HashTable&);
312 iterator begin() { return makeIterator(m_table); }
313 iterator end() { return makeKnownGoodIterator(m_table + m_tableSize); }
314 const_iterator begin() const { return makeConstIterator(m_table); }
315 const_iterator end() const { return makeKnownGoodConstIterator(m_table + m_tableSize); }
317 int size() const { return m_keyCount; }
318 int capacity() const { return m_tableSize; }
319 bool isEmpty() const { return !m_keyCount; }
321 pair<iterator, bool> add(const ValueType& value) { return add<KeyType, ValueType, IdentityTranslatorType>(Extractor::extract(value), value); }
323 // A special version of add() that finds the object by hashing and comparing
324 // with some other type, to avoid the cost of type conversion if the object is already
326 template<typename T, typename Extra, typename HashTranslator> pair<iterator, bool> add(const T& key, const Extra&);
327 template<typename T, typename Extra, typename HashTranslator> pair<iterator, bool> addPassingHashCode(const T& key, const Extra&);
329 iterator find(const KeyType& key) { return find<KeyType, IdentityTranslatorType>(key); }
330 const_iterator find(const KeyType& key) const { return find<KeyType, IdentityTranslatorType>(key); }
331 bool contains(const KeyType& key) const { return contains<KeyType, IdentityTranslatorType>(key); }
333 template <typename T, typename HashTranslator> iterator find(const T&);
334 template <typename T, typename HashTranslator> const_iterator find(const T&) const;
335 template <typename T, typename HashTranslator> bool contains(const T&) const;
337 void remove(const KeyType&);
338 void remove(iterator);
339 void removeWithoutEntryConsistencyCheck(iterator);
340 void removeWithoutEntryConsistencyCheck(const_iterator);
343 static bool isEmptyBucket(const ValueType& value) { return Extractor::extract(value) == KeyTraits::emptyValue(); }
344 static bool isDeletedBucket(const ValueType& value) { return KeyTraits::isDeletedValue(Extractor::extract(value)); }
345 static bool isEmptyOrDeletedBucket(const ValueType& value) { return isEmptyBucket(value) || isDeletedBucket(value); }
347 ValueType* lookup(const Key& key) { return lookup<Key, IdentityTranslatorType>(key); }
348 template<typename T, typename HashTranslator> ValueType* lookup(const T&);
351 void checkTableConsistency() const;
353 static void checkTableConsistency() { }
355 #if CHECK_HASHTABLE_CONSISTENCY
356 void internalCheckTableConsistency() const { checkTableConsistency(); }
357 void internalCheckTableConsistencyExceptSize() const { checkTableConsistencyExceptSize(); }
359 static void internalCheckTableConsistencyExceptSize() { }
360 static void internalCheckTableConsistency() { }
364 static ValueType* allocateTable(int size);
365 static void deallocateTable(ValueType* table, int size);
367 typedef pair<ValueType*, bool> LookupType;
368 typedef pair<LookupType, unsigned> FullLookupType;
370 LookupType lookupForWriting(const Key& key) { return lookupForWriting<Key, IdentityTranslatorType>(key); };
371 template<typename T, typename HashTranslator> FullLookupType fullLookupForWriting(const T&);
372 template<typename T, typename HashTranslator> LookupType lookupForWriting(const T&);
374 template<typename T, typename HashTranslator> void checkKey(const T&);
376 void removeAndInvalidateWithoutEntryConsistencyCheck(ValueType*);
377 void removeAndInvalidate(ValueType*);
378 void remove(ValueType*);
380 bool shouldExpand() const { return (m_keyCount + m_deletedCount) * m_maxLoad >= m_tableSize; }
381 bool mustRehashInPlace() const { return m_keyCount * m_minLoad < m_tableSize * 2; }
382 bool shouldShrink() const { return m_keyCount * m_minLoad < m_tableSize && m_tableSize > KeyTraits::minimumTableSize; }
384 void shrink() { rehash(m_tableSize / 2); }
386 void rehash(int newTableSize);
387 void reinsert(ValueType&);
389 static void initializeBucket(ValueType& bucket);
390 static void deleteBucket(ValueType& bucket) { bucket.~ValueType(); Traits::constructDeletedValue(bucket); }
392 FullLookupType makeLookupResult(ValueType* position, bool found, unsigned hash)
393 { return FullLookupType(LookupType(position, found), hash); }
395 iterator makeIterator(ValueType* pos) { return iterator(this, pos, m_table + m_tableSize); }
396 const_iterator makeConstIterator(ValueType* pos) const { return const_iterator(this, pos, m_table + m_tableSize); }
397 iterator makeKnownGoodIterator(ValueType* pos) { return iterator(this, pos, m_table + m_tableSize, HashItemKnownGood); }
398 const_iterator makeKnownGoodConstIterator(ValueType* pos) const { return const_iterator(this, pos, m_table + m_tableSize, HashItemKnownGood); }
401 void checkTableConsistencyExceptSize() const;
403 static void checkTableConsistencyExceptSize() { }
406 #if CHECK_HASHTABLE_ITERATORS
407 void invalidateIterators();
409 static void invalidateIterators() { }
412 static const int m_maxLoad = 2;
413 static const int m_minLoad = 6;
421 #if CHECK_HASHTABLE_ITERATORS
423 // All access to m_iterators should be guarded with m_mutex.
424 mutable const_iterator* m_iterators;
425 mutable Mutex m_mutex;
429 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
430 inline HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::HashTable()
436 #if CHECK_HASHTABLE_ITERATORS
442 inline unsigned doubleHash(unsigned key)
444 key = ~key + (key >> 23);
454 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
455 template<typename T, typename HashTranslator>
456 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkKey(const T&)
462 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
463 template<typename T, typename HashTranslator>
464 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkKey(const T& key)
466 if (!HashFunctions::safeToCompareToEmptyOrDeleted)
468 ASSERT(!HashTranslator::equal(KeyTraits::emptyValue(), key));
469 AlignedBuffer<sizeof(ValueType), WTF_ALIGN_OF(ValueType)> deletedValueBuffer;
470 ValueType& deletedValue = *reinterpret_cast_ptr<ValueType*>(deletedValueBuffer.buffer);
471 Traits::constructDeletedValue(deletedValue);
472 ASSERT(!HashTranslator::equal(Extractor::extract(deletedValue), key));
477 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
478 template<typename T, typename HashTranslator>
479 inline Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::lookup(const T& key)
481 checkKey<T, HashTranslator>(key);
484 int sizeMask = m_tableSizeMask;
485 ValueType* table = m_table;
486 unsigned h = HashTranslator::hash(key);
487 int i = h & sizeMask;
492 #if DUMP_HASHTABLE_STATS
493 atomicIncrement(&HashTableStats::numAccesses);
498 ValueType* entry = table + i;
500 // we count on the compiler to optimize out this branch
501 if (HashFunctions::safeToCompareToEmptyOrDeleted) {
502 if (HashTranslator::equal(Extractor::extract(*entry), key))
505 if (isEmptyBucket(*entry))
508 if (isEmptyBucket(*entry))
511 if (!isDeletedBucket(*entry) && HashTranslator::equal(Extractor::extract(*entry), key))
514 #if DUMP_HASHTABLE_STATS
516 HashTableStats::recordCollisionAtCount(probeCount);
519 k = 1 | doubleHash(h);
520 i = (i + k) & sizeMask;
524 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
525 template<typename T, typename HashTranslator>
526 inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::LookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::lookupForWriting(const T& key)
529 checkKey<T, HashTranslator>(key);
532 ValueType* table = m_table;
533 int sizeMask = m_tableSizeMask;
534 unsigned h = HashTranslator::hash(key);
535 int i = h & sizeMask;
537 #if DUMP_HASHTABLE_STATS
538 atomicIncrement(&HashTableStats::numAccesses);
542 ValueType* deletedEntry = 0;
545 ValueType* entry = table + i;
547 // we count on the compiler to optimize out this branch
548 if (HashFunctions::safeToCompareToEmptyOrDeleted) {
549 if (isEmptyBucket(*entry))
550 return LookupType(deletedEntry ? deletedEntry : entry, false);
552 if (HashTranslator::equal(Extractor::extract(*entry), key))
553 return LookupType(entry, true);
555 if (isDeletedBucket(*entry))
556 deletedEntry = entry;
558 if (isEmptyBucket(*entry))
559 return LookupType(deletedEntry ? deletedEntry : entry, false);
561 if (isDeletedBucket(*entry))
562 deletedEntry = entry;
563 else if (HashTranslator::equal(Extractor::extract(*entry), key))
564 return LookupType(entry, true);
566 #if DUMP_HASHTABLE_STATS
568 HashTableStats::recordCollisionAtCount(probeCount);
571 k = 1 | doubleHash(h);
572 i = (i + k) & sizeMask;
576 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
577 template<typename T, typename HashTranslator>
578 inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::FullLookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::fullLookupForWriting(const T& key)
581 checkKey<T, HashTranslator>(key);
584 ValueType* table = m_table;
585 int sizeMask = m_tableSizeMask;
586 unsigned h = HashTranslator::hash(key);
587 int i = h & sizeMask;
589 #if DUMP_HASHTABLE_STATS
590 atomicIncrement(&HashTableStats::numAccesses);
594 ValueType* deletedEntry = 0;
597 ValueType* entry = table + i;
599 // we count on the compiler to optimize out this branch
600 if (HashFunctions::safeToCompareToEmptyOrDeleted) {
601 if (isEmptyBucket(*entry))
602 return makeLookupResult(deletedEntry ? deletedEntry : entry, false, h);
604 if (HashTranslator::equal(Extractor::extract(*entry), key))
605 return makeLookupResult(entry, true, h);
607 if (isDeletedBucket(*entry))
608 deletedEntry = entry;
610 if (isEmptyBucket(*entry))
611 return makeLookupResult(deletedEntry ? deletedEntry : entry, false, h);
613 if (isDeletedBucket(*entry))
614 deletedEntry = entry;
615 else if (HashTranslator::equal(Extractor::extract(*entry), key))
616 return makeLookupResult(entry, true, h);
618 #if DUMP_HASHTABLE_STATS
620 HashTableStats::recordCollisionAtCount(probeCount);
623 k = 1 | doubleHash(h);
624 i = (i + k) & sizeMask;
628 template<bool emptyValueIsZero> struct HashTableBucketInitializer;
630 template<> struct HashTableBucketInitializer<false> {
631 template<typename Traits, typename Value> static void initialize(Value& bucket)
633 new (&bucket) Value(Traits::emptyValue());
637 template<> struct HashTableBucketInitializer<true> {
638 template<typename Traits, typename Value> static void initialize(Value& bucket)
640 // This initializes the bucket without copying the empty value.
641 // That makes it possible to use this with types that don't support copying.
642 // The memset to 0 looks like a slow operation but is optimized by the compilers.
643 memset(&bucket, 0, sizeof(bucket));
647 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
648 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::initializeBucket(ValueType& bucket)
650 HashTableBucketInitializer<Traits::emptyValueIsZero>::template initialize<Traits>(bucket);
653 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
654 template<typename T, typename Extra, typename HashTranslator>
655 inline pair<typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::iterator, bool> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::add(const T& key, const Extra& extra)
657 checkKey<T, HashTranslator>(key);
659 invalidateIterators();
664 internalCheckTableConsistency();
669 ValueType* table = m_table;
670 int sizeMask = m_tableSizeMask;
671 unsigned h = HashTranslator::hash(key);
672 int i = h & sizeMask;
674 #if DUMP_HASHTABLE_STATS
675 atomicIncrement(&HashTableStats::numAccesses);
679 ValueType* deletedEntry = 0;
684 // we count on the compiler to optimize out this branch
685 if (HashFunctions::safeToCompareToEmptyOrDeleted) {
686 if (isEmptyBucket(*entry))
689 if (HashTranslator::equal(Extractor::extract(*entry), key))
690 return std::make_pair(makeKnownGoodIterator(entry), false);
692 if (isDeletedBucket(*entry))
693 deletedEntry = entry;
695 if (isEmptyBucket(*entry))
698 if (isDeletedBucket(*entry))
699 deletedEntry = entry;
700 else if (HashTranslator::equal(Extractor::extract(*entry), key))
701 return std::make_pair(makeKnownGoodIterator(entry), false);
703 #if DUMP_HASHTABLE_STATS
705 HashTableStats::recordCollisionAtCount(probeCount);
708 k = 1 | doubleHash(h);
709 i = (i + k) & sizeMask;
713 initializeBucket(*deletedEntry);
714 entry = deletedEntry;
718 HashTranslator::translate(*entry, key, extra);
722 if (shouldExpand()) {
723 // FIXME: This makes an extra copy on expand. Probably not that bad since
724 // expand is rare, but would be better to have a version of expand that can
725 // follow a pivot entry and return the new position.
726 KeyType enteredKey = Extractor::extract(*entry);
728 pair<iterator, bool> p = std::make_pair(find(enteredKey), true);
729 ASSERT(p.first != end());
733 internalCheckTableConsistency();
735 return std::make_pair(makeKnownGoodIterator(entry), true);
738 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
739 template<typename T, typename Extra, typename HashTranslator>
740 inline pair<typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::iterator, bool> HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::addPassingHashCode(const T& key, const Extra& extra)
742 checkKey<T, HashTranslator>(key);
744 invalidateIterators();
749 internalCheckTableConsistency();
751 FullLookupType lookupResult = fullLookupForWriting<T, HashTranslator>(key);
753 ValueType* entry = lookupResult.first.first;
754 bool found = lookupResult.first.second;
755 unsigned h = lookupResult.second;
758 return std::make_pair(makeKnownGoodIterator(entry), false);
760 if (isDeletedBucket(*entry)) {
761 initializeBucket(*entry);
765 HashTranslator::translate(*entry, key, extra, h);
767 if (shouldExpand()) {
768 // FIXME: This makes an extra copy on expand. Probably not that bad since
769 // expand is rare, but would be better to have a version of expand that can
770 // follow a pivot entry and return the new position.
771 KeyType enteredKey = Extractor::extract(*entry);
773 pair<iterator, bool> p = std::make_pair(find(enteredKey), true);
774 ASSERT(p.first != end());
778 internalCheckTableConsistency();
780 return std::make_pair(makeKnownGoodIterator(entry), true);
783 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
784 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::reinsert(ValueType& entry)
787 ASSERT(!lookupForWriting(Extractor::extract(entry)).second);
788 ASSERT(!isDeletedBucket(*(lookupForWriting(Extractor::extract(entry)).first)));
789 #if DUMP_HASHTABLE_STATS
790 atomicIncrement(&HashTableStats::numReinserts);
793 Mover<ValueType, Traits::needsDestruction>::move(entry, *lookupForWriting(Extractor::extract(entry)).first);
796 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
797 template <typename T, typename HashTranslator>
798 typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::find(const T& key)
803 ValueType* entry = lookup<T, HashTranslator>(key);
807 return makeKnownGoodIterator(entry);
810 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
811 template <typename T, typename HashTranslator>
812 typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::const_iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::find(const T& key) const
817 ValueType* entry = const_cast<HashTable*>(this)->lookup<T, HashTranslator>(key);
821 return makeKnownGoodConstIterator(entry);
824 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
825 template <typename T, typename HashTranslator>
826 bool HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::contains(const T& key) const
831 return const_cast<HashTable*>(this)->lookup<T, HashTranslator>(key);
834 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
835 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeAndInvalidateWithoutEntryConsistencyCheck(ValueType* pos)
837 invalidateIterators();
841 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
842 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeAndInvalidate(ValueType* pos)
844 invalidateIterators();
845 internalCheckTableConsistency();
849 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
850 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(ValueType* pos)
852 #if DUMP_HASHTABLE_STATS
853 atomicIncrement(&HashTableStats::numRemoves);
863 internalCheckTableConsistency();
866 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
867 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(iterator it)
872 removeAndInvalidate(const_cast<ValueType*>(it.m_iterator.m_position));
875 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
876 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeWithoutEntryConsistencyCheck(iterator it)
881 removeAndInvalidateWithoutEntryConsistencyCheck(const_cast<ValueType*>(it.m_iterator.m_position));
884 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
885 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeWithoutEntryConsistencyCheck(const_iterator it)
890 removeAndInvalidateWithoutEntryConsistencyCheck(const_cast<ValueType*>(it.m_position));
893 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
894 inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(const KeyType& key)
899 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
900 Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::allocateTable(int size)
902 // would use a template member function with explicit specializations here, but
903 // gcc doesn't appear to support that
904 if (Traits::emptyValueIsZero)
905 return static_cast<ValueType*>(fastZeroedMalloc(size * sizeof(ValueType)));
906 ValueType* result = static_cast<ValueType*>(fastMalloc(size * sizeof(ValueType)));
907 for (int i = 0; i < size; i++)
908 initializeBucket(result[i]);
912 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
913 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::deallocateTable(ValueType* table, int size)
915 if (Traits::needsDestruction) {
916 for (int i = 0; i < size; ++i) {
917 if (!isDeletedBucket(table[i]))
918 table[i].~ValueType();
924 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
925 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::expand()
928 if (m_tableSize == 0)
929 newSize = KeyTraits::minimumTableSize;
930 else if (mustRehashInPlace())
931 newSize = m_tableSize;
933 newSize = m_tableSize * 2;
938 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
939 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::rehash(int newTableSize)
941 internalCheckTableConsistencyExceptSize();
943 int oldTableSize = m_tableSize;
944 ValueType* oldTable = m_table;
946 #if DUMP_HASHTABLE_STATS
947 if (oldTableSize != 0)
948 atomicIncrement(&HashTableStats::numRehashes);
951 m_tableSize = newTableSize;
952 m_tableSizeMask = newTableSize - 1;
953 m_table = allocateTable(newTableSize);
955 for (int i = 0; i != oldTableSize; ++i)
956 if (!isEmptyOrDeletedBucket(oldTable[i]))
957 reinsert(oldTable[i]);
961 deallocateTable(oldTable, oldTableSize);
963 internalCheckTableConsistency();
966 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
967 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::clear()
969 invalidateIterators();
970 deallocateTable(m_table, m_tableSize);
977 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
978 HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::HashTable(const HashTable& other)
984 #if CHECK_HASHTABLE_ITERATORS
988 // Copy the hash table the dumb way, by adding each element to the new table.
989 // It might be more efficient to copy the table slots, but it's not clear that efficiency is needed.
990 const_iterator end = other.end();
991 for (const_iterator it = other.begin(); it != end; ++it)
995 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
996 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::swap(HashTable& other)
998 invalidateIterators();
999 other.invalidateIterators();
1001 ValueType* tmp_table = m_table;
1002 m_table = other.m_table;
1003 other.m_table = tmp_table;
1005 int tmp_tableSize = m_tableSize;
1006 m_tableSize = other.m_tableSize;
1007 other.m_tableSize = tmp_tableSize;
1009 int tmp_tableSizeMask = m_tableSizeMask;
1010 m_tableSizeMask = other.m_tableSizeMask;
1011 other.m_tableSizeMask = tmp_tableSizeMask;
1013 int tmp_keyCount = m_keyCount;
1014 m_keyCount = other.m_keyCount;
1015 other.m_keyCount = tmp_keyCount;
1017 int tmp_deletedCount = m_deletedCount;
1018 m_deletedCount = other.m_deletedCount;
1019 other.m_deletedCount = tmp_deletedCount;
1022 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1023 HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>& HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::operator=(const HashTable& other)
1025 HashTable tmp(other);
1030 #if !ASSERT_DISABLED
1032 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1033 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkTableConsistency() const
1035 checkTableConsistencyExceptSize();
1036 ASSERT(!m_table || !shouldExpand());
1037 ASSERT(!shouldShrink());
1040 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1041 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkTableConsistencyExceptSize() const
1047 int deletedCount = 0;
1048 for (int j = 0; j < m_tableSize; ++j) {
1049 ValueType* entry = m_table + j;
1050 if (isEmptyBucket(*entry))
1053 if (isDeletedBucket(*entry)) {
1058 const_iterator it = find(Extractor::extract(*entry));
1059 ASSERT(entry == it.m_position);
1062 ValueCheck<Key>::checkConsistency(it->first);
1065 ASSERT(count == m_keyCount);
1066 ASSERT(deletedCount == m_deletedCount);
1067 ASSERT(m_tableSize >= KeyTraits::minimumTableSize);
1068 ASSERT(m_tableSizeMask);
1069 ASSERT(m_tableSize == m_tableSizeMask + 1);
1072 #endif // ASSERT_DISABLED
1074 #if CHECK_HASHTABLE_ITERATORS
1076 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1077 void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::invalidateIterators()
1079 MutexLocker lock(m_mutex);
1080 const_iterator* next;
1081 for (const_iterator* p = m_iterators; p; p = next) {
1090 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1091 void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* table,
1092 HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* it)
1094 it->m_table = table;
1097 // Insert iterator at head of doubly-linked list of iterators.
1101 MutexLocker lock(table->m_mutex);
1102 ASSERT(table->m_iterators != it);
1103 it->m_next = table->m_iterators;
1104 table->m_iterators = it;
1106 ASSERT(!it->m_next->m_previous);
1107 it->m_next->m_previous = it;
1112 template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
1113 void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* it)
1115 typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
1116 typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
1118 // Delete iterator from doubly-linked list of iterators.
1120 ASSERT(!it->m_next);
1121 ASSERT(!it->m_previous);
1123 MutexLocker lock(it->m_table->m_mutex);
1125 ASSERT(it->m_next->m_previous == it);
1126 it->m_next->m_previous = it->m_previous;
1128 if (it->m_previous) {
1129 ASSERT(it->m_table->m_iterators != it);
1130 ASSERT(it->m_previous->m_next == it);
1131 it->m_previous->m_next = it->m_next;
1133 ASSERT(it->m_table->m_iterators == it);
1134 it->m_table->m_iterators = it->m_next;
1143 #endif // CHECK_HASHTABLE_ITERATORS
1145 // iterator adapters
1147 template<typename HashTableType, typename ValueType> struct HashTableConstIteratorAdapter {
1148 HashTableConstIteratorAdapter() {}
1149 HashTableConstIteratorAdapter(const typename HashTableType::const_iterator& impl) : m_impl(impl) {}
1151 const ValueType* get() const { return (const ValueType*)m_impl.get(); }
1152 const ValueType& operator*() const { return *get(); }
1153 const ValueType* operator->() const { return get(); }
1155 HashTableConstIteratorAdapter& operator++() { ++m_impl; return *this; }
1156 // postfix ++ intentionally omitted
1158 typename HashTableType::const_iterator m_impl;
1161 template<typename HashTableType, typename ValueType> struct HashTableIteratorAdapter {
1162 HashTableIteratorAdapter() {}
1163 HashTableIteratorAdapter(const typename HashTableType::iterator& impl) : m_impl(impl) {}
1165 ValueType* get() const { return (ValueType*)m_impl.get(); }
1166 ValueType& operator*() const { return *get(); }
1167 ValueType* operator->() const { return get(); }
1169 HashTableIteratorAdapter& operator++() { ++m_impl; return *this; }
1170 // postfix ++ intentionally omitted
1172 operator HashTableConstIteratorAdapter<HashTableType, ValueType>() {
1173 typename HashTableType::const_iterator i = m_impl;
1177 typename HashTableType::iterator m_impl;
1180 template<typename T, typename U>
1181 inline bool operator==(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
1183 return a.m_impl == b.m_impl;
1186 template<typename T, typename U>
1187 inline bool operator!=(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
1189 return a.m_impl != b.m_impl;
1192 template<typename T, typename U>
1193 inline bool operator==(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
1195 return a.m_impl == b.m_impl;
1198 template<typename T, typename U>
1199 inline bool operator!=(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
1201 return a.m_impl != b.m_impl;
1206 #include "HashIterators.h"
1208 #endif // WTF_HashTable_h