HashTable.h 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  1. /*
  2. * Copyright (C) 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
  3. * Copyright (C) 2008 David Levin <levin@chromium.org>
  4. *
  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.
  9. *
  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.
  14. *
  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.
  19. *
  20. */
  21. #ifndef WTF_HashTable_h
  22. #define WTF_HashTable_h
  23. #include <wtf/Alignment.h>
  24. #include <wtf/Assertions.h>
  25. #include <wtf/FastMalloc.h>
  26. #include <wtf/HashTraits.h>
  27. #include <wtf/StdLibExtras.h>
  28. #include <wtf/Threading.h>
  29. #include <wtf/ValueCheck.h>
  30. #ifndef NDEBUG
  31. // Required for CHECK_HASHTABLE_ITERATORS.
  32. #include <wtf/OwnPtr.h>
  33. #include <wtf/PassOwnPtr.h>
  34. #endif
  35. #define DUMP_HASHTABLE_STATS 0
  36. #define DUMP_HASHTABLE_STATS_PER_TABLE 0
  37. #if DUMP_HASHTABLE_STATS_PER_TABLE
  38. #include <wtf/DataLog.h>
  39. #endif
  40. namespace WTF {
  41. // Enables internal WTF consistency checks that are invoked automatically. Non-WTF callers can call checkTableConsistency() even if internal checks are disabled.
  42. #define CHECK_HASHTABLE_CONSISTENCY 0
  43. #ifdef NDEBUG
  44. #define CHECK_HASHTABLE_ITERATORS 0
  45. #define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 0
  46. #elif OS(PSP2) || OS(ORBIS)
  47. #define CHECK_HASHTABLE_ITERATORS 0
  48. #define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 0
  49. #else
  50. #define CHECK_HASHTABLE_ITERATORS 1
  51. #define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 1
  52. #endif
  53. #if DUMP_HASHTABLE_STATS
  54. struct HashTableStats {
  55. // The following variables are all atomically incremented when modified.
  56. WTF_EXPORTDATA static int numAccesses;
  57. WTF_EXPORTDATA static int numRehashes;
  58. WTF_EXPORTDATA static int numRemoves;
  59. WTF_EXPORTDATA static int numReinserts;
  60. // The following variables are only modified in the recordCollisionAtCount method within a mutex.
  61. WTF_EXPORTDATA static int maxCollisions;
  62. WTF_EXPORTDATA static int numCollisions;
  63. WTF_EXPORTDATA static int collisionGraph[4096];
  64. WTF_EXPORT_PRIVATE static void recordCollisionAtCount(int count);
  65. WTF_EXPORT_PRIVATE static void dumpStats();
  66. };
  67. #endif
  68. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  69. class HashTable;
  70. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  71. class HashTableIterator;
  72. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  73. class HashTableConstIterator;
  74. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  75. void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
  76. HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
  77. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  78. void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
  79. #if !CHECK_HASHTABLE_ITERATORS
  80. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  81. inline void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
  82. HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
  83. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  84. inline void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
  85. #endif
  86. typedef enum { HashItemKnownGood } HashItemKnownGoodTag;
  87. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  88. class HashTableConstIterator {
  89. private:
  90. typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
  91. typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
  92. typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
  93. typedef Value ValueType;
  94. typedef const ValueType& ReferenceType;
  95. typedef const ValueType* PointerType;
  96. friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
  97. friend class HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
  98. void skipEmptyBuckets()
  99. {
  100. while (m_position != m_endPosition && HashTableType::isEmptyOrDeletedBucket(*m_position))
  101. ++m_position;
  102. }
  103. HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition)
  104. : m_position(position), m_endPosition(endPosition)
  105. {
  106. addIterator(table, this);
  107. skipEmptyBuckets();
  108. }
  109. HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition, HashItemKnownGoodTag)
  110. : m_position(position), m_endPosition(endPosition)
  111. {
  112. addIterator(table, this);
  113. }
  114. public:
  115. HashTableConstIterator()
  116. {
  117. addIterator(static_cast<const HashTableType*>(0), this);
  118. }
  119. // default copy, assignment and destructor are OK if CHECK_HASHTABLE_ITERATORS is 0
  120. #if CHECK_HASHTABLE_ITERATORS
  121. ~HashTableConstIterator()
  122. {
  123. removeIterator(this);
  124. }
  125. HashTableConstIterator(const const_iterator& other)
  126. : m_position(other.m_position), m_endPosition(other.m_endPosition)
  127. {
  128. addIterator(other.m_table, this);
  129. }
  130. const_iterator& operator=(const const_iterator& other)
  131. {
  132. m_position = other.m_position;
  133. m_endPosition = other.m_endPosition;
  134. removeIterator(this);
  135. addIterator(other.m_table, this);
  136. return *this;
  137. }
  138. #endif
  139. PointerType get() const
  140. {
  141. checkValidity();
  142. return m_position;
  143. }
  144. ReferenceType operator*() const { return *get(); }
  145. PointerType operator->() const { return get(); }
  146. const_iterator& operator++()
  147. {
  148. checkValidity();
  149. ASSERT(m_position != m_endPosition);
  150. ++m_position;
  151. skipEmptyBuckets();
  152. return *this;
  153. }
  154. // postfix ++ intentionally omitted
  155. // Comparison.
  156. bool operator==(const const_iterator& other) const
  157. {
  158. checkValidity(other);
  159. return m_position == other.m_position;
  160. }
  161. bool operator!=(const const_iterator& other) const
  162. {
  163. checkValidity(other);
  164. return m_position != other.m_position;
  165. }
  166. bool operator==(const iterator& other) const
  167. {
  168. return *this == static_cast<const_iterator>(other);
  169. }
  170. bool operator!=(const iterator& other) const
  171. {
  172. return *this != static_cast<const_iterator>(other);
  173. }
  174. private:
  175. void checkValidity() const
  176. {
  177. #if CHECK_HASHTABLE_ITERATORS
  178. ASSERT(m_table);
  179. #endif
  180. }
  181. #if CHECK_HASHTABLE_ITERATORS
  182. void checkValidity(const const_iterator& other) const
  183. {
  184. ASSERT(m_table);
  185. ASSERT_UNUSED(other, other.m_table);
  186. ASSERT(m_table == other.m_table);
  187. }
  188. #else
  189. void checkValidity(const const_iterator&) const { }
  190. #endif
  191. PointerType m_position;
  192. PointerType m_endPosition;
  193. #if CHECK_HASHTABLE_ITERATORS
  194. public:
  195. // Any modifications of the m_next or m_previous of an iterator that is in a linked list of a HashTable::m_iterator,
  196. // should be guarded with m_table->m_mutex.
  197. mutable const HashTableType* m_table;
  198. mutable const_iterator* m_next;
  199. mutable const_iterator* m_previous;
  200. #endif
  201. };
  202. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  203. class HashTableIterator {
  204. private:
  205. typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
  206. typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
  207. typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
  208. typedef Value ValueType;
  209. typedef ValueType& ReferenceType;
  210. typedef ValueType* PointerType;
  211. friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
  212. HashTableIterator(HashTableType* table, PointerType pos, PointerType end) : m_iterator(table, pos, end) { }
  213. HashTableIterator(HashTableType* table, PointerType pos, PointerType end, HashItemKnownGoodTag tag) : m_iterator(table, pos, end, tag) { }
  214. public:
  215. HashTableIterator() { }
  216. // default copy, assignment and destructor are OK
  217. PointerType get() const { return const_cast<PointerType>(m_iterator.get()); }
  218. ReferenceType operator*() const { return *get(); }
  219. PointerType operator->() const { return get(); }
  220. iterator& operator++() { ++m_iterator; return *this; }
  221. // postfix ++ intentionally omitted
  222. // Comparison.
  223. bool operator==(const iterator& other) const { return m_iterator == other.m_iterator; }
  224. bool operator!=(const iterator& other) const { return m_iterator != other.m_iterator; }
  225. bool operator==(const const_iterator& other) const { return m_iterator == other; }
  226. bool operator!=(const const_iterator& other) const { return m_iterator != other; }
  227. operator const_iterator() const { return m_iterator; }
  228. private:
  229. const_iterator m_iterator;
  230. };
  231. using std::swap;
  232. // Work around MSVC's standard library, whose swap for pairs does not swap by component.
  233. template<typename T> inline void hashTableSwap(T& a, T& b)
  234. {
  235. swap(a, b);
  236. }
  237. template<typename T, typename U> inline void hashTableSwap(KeyValuePair<T, U>& a, KeyValuePair<T, U>& b)
  238. {
  239. swap(a.key, b.key);
  240. swap(a.value, b.value);
  241. }
  242. template<typename T, bool useSwap> struct Mover;
  243. template<typename T> struct Mover<T, true> { static void move(T& from, T& to) { hashTableSwap(from, to); } };
  244. template<typename T> struct Mover<T, false> { static void move(T& from, T& to) { to = from; } };
  245. template<typename HashFunctions> class IdentityHashTranslator {
  246. public:
  247. template<typename T> static unsigned hash(const T& key) { return HashFunctions::hash(key); }
  248. template<typename T, typename U> static bool equal(const T& a, const U& b) { return HashFunctions::equal(a, b); }
  249. template<typename T, typename U> static void translate(T& location, const U&, const T& value) { location = value; }
  250. };
  251. template<typename IteratorType> struct HashTableAddResult {
  252. HashTableAddResult(IteratorType iter, bool isNewEntry) : iterator(iter), isNewEntry(isNewEntry) { }
  253. IteratorType iterator;
  254. bool isNewEntry;
  255. };
  256. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  257. class HashTable {
  258. public:
  259. typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
  260. typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
  261. typedef Traits ValueTraits;
  262. typedef Key KeyType;
  263. typedef Value ValueType;
  264. typedef IdentityHashTranslator<HashFunctions> IdentityTranslatorType;
  265. typedef HashTableAddResult<iterator> AddResult;
  266. #if DUMP_HASHTABLE_STATS_PER_TABLE
  267. struct Stats {
  268. Stats()
  269. : numAccesses(0)
  270. , numRehashes(0)
  271. , numRemoves(0)
  272. , numReinserts(0)
  273. , maxCollisions(0)
  274. , numCollisions(0)
  275. , collisionGraph()
  276. {
  277. }
  278. int numAccesses;
  279. int numRehashes;
  280. int numRemoves;
  281. int numReinserts;
  282. int maxCollisions;
  283. int numCollisions;
  284. int collisionGraph[4096];
  285. void recordCollisionAtCount(int count)
  286. {
  287. if (count > maxCollisions)
  288. maxCollisions = count;
  289. numCollisions++;
  290. collisionGraph[count]++;
  291. }
  292. void dumpStats()
  293. {
  294. dataLogF("\nWTF::HashTable::Stats dump\n\n");
  295. dataLogF("%d accesses\n", numAccesses);
  296. dataLogF("%d total collisions, average %.2f probes per access\n", numCollisions, 1.0 * (numAccesses + numCollisions) / numAccesses);
  297. dataLogF("longest collision chain: %d\n", maxCollisions);
  298. for (int i = 1; i <= maxCollisions; i++) {
  299. dataLogF(" %d lookups with exactly %d collisions (%.2f%% , %.2f%% with this many or more)\n", collisionGraph[i], i, 100.0 * (collisionGraph[i] - collisionGraph[i+1]) / numAccesses, 100.0 * collisionGraph[i] / numAccesses);
  300. }
  301. dataLogF("%d rehashes\n", numRehashes);
  302. dataLogF("%d reinserts\n", numReinserts);
  303. }
  304. };
  305. #endif
  306. HashTable();
  307. ~HashTable()
  308. {
  309. invalidateIterators();
  310. if (m_table)
  311. deallocateTable(m_table, m_tableSize);
  312. #if CHECK_HASHTABLE_USE_AFTER_DESTRUCTION
  313. m_table = (ValueType*)(uintptr_t)0xbbadbeef;
  314. #endif
  315. }
  316. HashTable(const HashTable&);
  317. void swap(HashTable&);
  318. HashTable& operator=(const HashTable&);
  319. // When the hash table is empty, just return the same iterator for end as for begin.
  320. // This is more efficient because we don't have to skip all the empty and deleted
  321. // buckets, and iterating an empty table is a common case that's worth optimizing.
  322. iterator begin() { return isEmpty() ? end() : makeIterator(m_table); }
  323. iterator end() { return makeKnownGoodIterator(m_table + m_tableSize); }
  324. const_iterator begin() const { return isEmpty() ? end() : makeConstIterator(m_table); }
  325. const_iterator end() const { return makeKnownGoodConstIterator(m_table + m_tableSize); }
  326. int size() const { return m_keyCount; }
  327. int capacity() const { return m_tableSize; }
  328. bool isEmpty() const { return !m_keyCount; }
  329. AddResult add(const ValueType& value) { return add<IdentityTranslatorType>(Extractor::extract(value), value); }
  330. // A special version of add() that finds the object by hashing and comparing
  331. // with some other type, to avoid the cost of type conversion if the object is already
  332. // in the table.
  333. template<typename HashTranslator, typename T, typename Extra> AddResult add(const T& key, const Extra&);
  334. template<typename HashTranslator, typename T, typename Extra> AddResult addPassingHashCode(const T& key, const Extra&);
  335. iterator find(const KeyType& key) { return find<IdentityTranslatorType>(key); }
  336. const_iterator find(const KeyType& key) const { return find<IdentityTranslatorType>(key); }
  337. bool contains(const KeyType& key) const { return contains<IdentityTranslatorType>(key); }
  338. template<typename HashTranslator, typename T> iterator find(const T&);
  339. template<typename HashTranslator, typename T> const_iterator find(const T&) const;
  340. template<typename HashTranslator, typename T> bool contains(const T&) const;
  341. void remove(const KeyType&);
  342. void remove(iterator);
  343. void removeWithoutEntryConsistencyCheck(iterator);
  344. void removeWithoutEntryConsistencyCheck(const_iterator);
  345. void clear();
  346. static bool isEmptyBucket(const ValueType& value) { return isHashTraitsEmptyValue<KeyTraits>(Extractor::extract(value)); }
  347. static bool isDeletedBucket(const ValueType& value) { return KeyTraits::isDeletedValue(Extractor::extract(value)); }
  348. static bool isEmptyOrDeletedBucket(const ValueType& value) { return isEmptyBucket(value) || isDeletedBucket(value); }
  349. ValueType* lookup(const Key& key) { return lookup<IdentityTranslatorType>(key); }
  350. template<typename HashTranslator, typename T> ValueType* lookup(const T&);
  351. #if !ASSERT_DISABLED
  352. void checkTableConsistency() const;
  353. #else
  354. static void checkTableConsistency() { }
  355. #endif
  356. #if CHECK_HASHTABLE_CONSISTENCY
  357. void internalCheckTableConsistency() const { checkTableConsistency(); }
  358. void internalCheckTableConsistencyExceptSize() const { checkTableConsistencyExceptSize(); }
  359. #else
  360. static void internalCheckTableConsistencyExceptSize() { }
  361. static void internalCheckTableConsistency() { }
  362. #endif
  363. private:
  364. static ValueType* allocateTable(int size);
  365. static void deallocateTable(ValueType* table, int size);
  366. typedef std::pair<ValueType*, bool> LookupType;
  367. typedef std::pair<LookupType, unsigned> FullLookupType;
  368. LookupType lookupForWriting(const Key& key) { return lookupForWriting<IdentityTranslatorType>(key); };
  369. template<typename HashTranslator, typename T> FullLookupType fullLookupForWriting(const T&);
  370. template<typename HashTranslator, typename T> LookupType lookupForWriting(const T&);
  371. template<typename HashTranslator, typename T> void checkKey(const T&);
  372. void removeAndInvalidateWithoutEntryConsistencyCheck(ValueType*);
  373. void removeAndInvalidate(ValueType*);
  374. void remove(ValueType*);
  375. bool shouldExpand() const { return (m_keyCount + m_deletedCount) * m_maxLoad >= m_tableSize; }
  376. bool mustRehashInPlace() const { return m_keyCount * m_minLoad < m_tableSize * 2; }
  377. bool shouldShrink() const { return m_keyCount * m_minLoad < m_tableSize && m_tableSize > KeyTraits::minimumTableSize; }
  378. void expand();
  379. void shrink() { rehash(m_tableSize / 2); }
  380. void rehash(int newTableSize);
  381. void reinsert(ValueType&);
  382. static void initializeBucket(ValueType& bucket);
  383. static void deleteBucket(ValueType& bucket) { bucket.~ValueType(); Traits::constructDeletedValue(bucket); }
  384. FullLookupType makeLookupResult(ValueType* position, bool found, unsigned hash)
  385. { return FullLookupType(LookupType(position, found), hash); }
  386. iterator makeIterator(ValueType* pos) { return iterator(this, pos, m_table + m_tableSize); }
  387. const_iterator makeConstIterator(ValueType* pos) const { return const_iterator(this, pos, m_table + m_tableSize); }
  388. iterator makeKnownGoodIterator(ValueType* pos) { return iterator(this, pos, m_table + m_tableSize, HashItemKnownGood); }
  389. const_iterator makeKnownGoodConstIterator(ValueType* pos) const { return const_iterator(this, pos, m_table + m_tableSize, HashItemKnownGood); }
  390. #if !ASSERT_DISABLED
  391. void checkTableConsistencyExceptSize() const;
  392. #else
  393. static void checkTableConsistencyExceptSize() { }
  394. #endif
  395. #if CHECK_HASHTABLE_ITERATORS
  396. void invalidateIterators();
  397. #else
  398. static void invalidateIterators() { }
  399. #endif
  400. static const int m_maxLoad = 2;
  401. static const int m_minLoad = 6;
  402. ValueType* m_table;
  403. int m_tableSize;
  404. int m_tableSizeMask;
  405. int m_keyCount;
  406. int m_deletedCount;
  407. #if CHECK_HASHTABLE_ITERATORS
  408. public:
  409. // All access to m_iterators should be guarded with m_mutex.
  410. mutable const_iterator* m_iterators;
  411. // Use OwnPtr so HashTable can still be memmove'd or memcpy'ed.
  412. mutable OwnPtr<Mutex> m_mutex;
  413. #endif
  414. #if DUMP_HASHTABLE_STATS_PER_TABLE
  415. public:
  416. mutable OwnPtr<Stats> m_stats;
  417. #endif
  418. };
  419. // Set all the bits to one after the most significant bit: 00110101010 -> 00111111111.
  420. template<unsigned size> struct OneifyLowBits;
  421. template<>
  422. struct OneifyLowBits<0> {
  423. static const unsigned value = 0;
  424. };
  425. template<unsigned number>
  426. struct OneifyLowBits {
  427. static const unsigned value = number | OneifyLowBits<(number >> 1)>::value;
  428. };
  429. // Compute the first power of two integer that is an upper bound of the parameter 'number'.
  430. template<unsigned number>
  431. struct UpperPowerOfTwoBound {
  432. static const unsigned value = (OneifyLowBits<number - 1>::value + 1) * 2;
  433. };
  434. // Because power of two numbers are the limit of maxLoad, their capacity is twice the
  435. // UpperPowerOfTwoBound, or 4 times their values.
  436. template<unsigned size, bool isPowerOfTwo> struct HashTableCapacityForSizeSplitter;
  437. template<unsigned size>
  438. struct HashTableCapacityForSizeSplitter<size, true> {
  439. static const unsigned value = size * 4;
  440. };
  441. template<unsigned size>
  442. struct HashTableCapacityForSizeSplitter<size, false> {
  443. static const unsigned value = UpperPowerOfTwoBound<size>::value;
  444. };
  445. // HashTableCapacityForSize computes the upper power of two capacity to hold the size parameter.
  446. // This is done at compile time to initialize the HashTraits.
  447. template<unsigned size>
  448. struct HashTableCapacityForSize {
  449. static const unsigned value = HashTableCapacityForSizeSplitter<size, !(size & (size - 1))>::value;
  450. COMPILE_ASSERT(size > 0, HashTableNonZeroMinimumCapacity);
  451. COMPILE_ASSERT(!static_cast<int>(value >> 31), HashTableNoCapacityOverflow);
  452. COMPILE_ASSERT(value > (2 * size), HashTableCapacityHoldsContentSize);
  453. };
  454. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  455. inline HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::HashTable()
  456. : m_table(0)
  457. , m_tableSize(0)
  458. , m_tableSizeMask(0)
  459. , m_keyCount(0)
  460. , m_deletedCount(0)
  461. #if CHECK_HASHTABLE_ITERATORS
  462. , m_iterators(0)
  463. , m_mutex(adoptPtr(new Mutex))
  464. #endif
  465. #if DUMP_HASHTABLE_STATS_PER_TABLE
  466. , m_stats(adoptPtr(new Stats))
  467. #endif
  468. {
  469. }
  470. inline unsigned doubleHash(unsigned key)
  471. {
  472. key = ~key + (key >> 23);
  473. key ^= (key << 12);
  474. key ^= (key >> 7);
  475. key ^= (key << 2);
  476. key ^= (key >> 20);
  477. return key;
  478. }
  479. #if ASSERT_DISABLED
  480. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  481. template<typename HashTranslator, typename T>
  482. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkKey(const T&)
  483. {
  484. }
  485. #else
  486. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  487. template<typename HashTranslator, typename T>
  488. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkKey(const T& key)
  489. {
  490. if (!HashFunctions::safeToCompareToEmptyOrDeleted)
  491. return;
  492. ASSERT(!HashTranslator::equal(KeyTraits::emptyValue(), key));
  493. AlignedBuffer<sizeof(ValueType), WTF_ALIGN_OF(ValueType)> deletedValueBuffer;
  494. ValueType* deletedValuePtr = reinterpret_cast_ptr<ValueType*>(deletedValueBuffer.buffer);
  495. ValueType& deletedValue = *deletedValuePtr;
  496. Traits::constructDeletedValue(deletedValue);
  497. ASSERT(!HashTranslator::equal(Extractor::extract(deletedValue), key));
  498. }
  499. #endif
  500. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  501. template<typename HashTranslator, typename T>
  502. inline Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::lookup(const T& key)
  503. {
  504. checkKey<HashTranslator>(key);
  505. int k = 0;
  506. int sizeMask = m_tableSizeMask;
  507. ValueType* table = m_table;
  508. unsigned h = HashTranslator::hash(key);
  509. int i = h & sizeMask;
  510. if (!table)
  511. return 0;
  512. #if DUMP_HASHTABLE_STATS
  513. atomicIncrement(&HashTableStats::numAccesses);
  514. int probeCount = 0;
  515. #endif
  516. #if DUMP_HASHTABLE_STATS_PER_TABLE
  517. ++m_stats->numAccesses;
  518. int perTableProbeCount = 0;
  519. #endif
  520. while (1) {
  521. ValueType* entry = table + i;
  522. // we count on the compiler to optimize out this branch
  523. if (HashFunctions::safeToCompareToEmptyOrDeleted) {
  524. if (HashTranslator::equal(Extractor::extract(*entry), key))
  525. return entry;
  526. if (isEmptyBucket(*entry))
  527. return 0;
  528. } else {
  529. if (isEmptyBucket(*entry))
  530. return 0;
  531. if (!isDeletedBucket(*entry) && HashTranslator::equal(Extractor::extract(*entry), key))
  532. return entry;
  533. }
  534. #if DUMP_HASHTABLE_STATS
  535. ++probeCount;
  536. HashTableStats::recordCollisionAtCount(probeCount);
  537. #endif
  538. #if DUMP_HASHTABLE_STATS_PER_TABLE
  539. ++perTableProbeCount;
  540. m_stats->recordCollisionAtCount(perTableProbeCount);
  541. #endif
  542. if (k == 0)
  543. k = 1 | doubleHash(h);
  544. i = (i + k) & sizeMask;
  545. }
  546. }
  547. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  548. template<typename HashTranslator, typename T>
  549. inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::LookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::lookupForWriting(const T& key)
  550. {
  551. ASSERT(m_table);
  552. checkKey<HashTranslator>(key);
  553. int k = 0;
  554. ValueType* table = m_table;
  555. int sizeMask = m_tableSizeMask;
  556. unsigned h = HashTranslator::hash(key);
  557. int i = h & sizeMask;
  558. #if DUMP_HASHTABLE_STATS
  559. atomicIncrement(&HashTableStats::numAccesses);
  560. int probeCount = 0;
  561. #endif
  562. #if DUMP_HASHTABLE_STATS_PER_TABLE
  563. ++m_stats->numAccesses;
  564. int perTableProbeCount = 0;
  565. #endif
  566. ValueType* deletedEntry = 0;
  567. while (1) {
  568. ValueType* entry = table + i;
  569. // we count on the compiler to optimize out this branch
  570. if (HashFunctions::safeToCompareToEmptyOrDeleted) {
  571. if (isEmptyBucket(*entry))
  572. return LookupType(deletedEntry ? deletedEntry : entry, false);
  573. if (HashTranslator::equal(Extractor::extract(*entry), key))
  574. return LookupType(entry, true);
  575. if (isDeletedBucket(*entry))
  576. deletedEntry = entry;
  577. } else {
  578. if (isEmptyBucket(*entry))
  579. return LookupType(deletedEntry ? deletedEntry : entry, false);
  580. if (isDeletedBucket(*entry))
  581. deletedEntry = entry;
  582. else if (HashTranslator::equal(Extractor::extract(*entry), key))
  583. return LookupType(entry, true);
  584. }
  585. #if DUMP_HASHTABLE_STATS
  586. ++probeCount;
  587. HashTableStats::recordCollisionAtCount(probeCount);
  588. #endif
  589. #if DUMP_HASHTABLE_STATS_PER_TABLE
  590. ++perTableProbeCount;
  591. m_stats->recordCollisionAtCount(perTableProbeCount);
  592. #endif
  593. if (k == 0)
  594. k = 1 | doubleHash(h);
  595. i = (i + k) & sizeMask;
  596. }
  597. }
  598. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  599. template<typename HashTranslator, typename T>
  600. inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::FullLookupType HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::fullLookupForWriting(const T& key)
  601. {
  602. ASSERT(m_table);
  603. checkKey<HashTranslator>(key);
  604. int k = 0;
  605. ValueType* table = m_table;
  606. int sizeMask = m_tableSizeMask;
  607. unsigned h = HashTranslator::hash(key);
  608. int i = h & sizeMask;
  609. #if DUMP_HASHTABLE_STATS
  610. atomicIncrement(&HashTableStats::numAccesses);
  611. int probeCount = 0;
  612. #endif
  613. #if DUMP_HASHTABLE_STATS_PER_TABLE
  614. ++m_stats->numAccesses;
  615. int perTableProbeCount = 0;
  616. #endif
  617. ValueType* deletedEntry = 0;
  618. while (1) {
  619. ValueType* entry = table + i;
  620. // we count on the compiler to optimize out this branch
  621. if (HashFunctions::safeToCompareToEmptyOrDeleted) {
  622. if (isEmptyBucket(*entry))
  623. return makeLookupResult(deletedEntry ? deletedEntry : entry, false, h);
  624. if (HashTranslator::equal(Extractor::extract(*entry), key))
  625. return makeLookupResult(entry, true, h);
  626. if (isDeletedBucket(*entry))
  627. deletedEntry = entry;
  628. } else {
  629. if (isEmptyBucket(*entry))
  630. return makeLookupResult(deletedEntry ? deletedEntry : entry, false, h);
  631. if (isDeletedBucket(*entry))
  632. deletedEntry = entry;
  633. else if (HashTranslator::equal(Extractor::extract(*entry), key))
  634. return makeLookupResult(entry, true, h);
  635. }
  636. #if DUMP_HASHTABLE_STATS
  637. ++probeCount;
  638. HashTableStats::recordCollisionAtCount(probeCount);
  639. #endif
  640. #if DUMP_HASHTABLE_STATS_PER_TABLE
  641. ++perTableProbeCount;
  642. m_stats->recordCollisionAtCount(perTableProbeCount);
  643. #endif
  644. if (k == 0)
  645. k = 1 | doubleHash(h);
  646. i = (i + k) & sizeMask;
  647. }
  648. }
  649. template<bool emptyValueIsZero> struct HashTableBucketInitializer;
  650. template<> struct HashTableBucketInitializer<false> {
  651. template<typename Traits, typename Value> static void initialize(Value& bucket)
  652. {
  653. new (NotNull, &bucket) Value(Traits::emptyValue());
  654. }
  655. };
  656. template<> struct HashTableBucketInitializer<true> {
  657. template<typename Traits, typename Value> static void initialize(Value& bucket)
  658. {
  659. // This initializes the bucket without copying the empty value.
  660. // That makes it possible to use this with types that don't support copying.
  661. // The memset to 0 looks like a slow operation but is optimized by the compilers.
  662. memset(&bucket, 0, sizeof(bucket));
  663. }
  664. };
  665. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  666. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::initializeBucket(ValueType& bucket)
  667. {
  668. HashTableBucketInitializer<Traits::emptyValueIsZero>::template initialize<Traits>(bucket);
  669. }
  670. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  671. template<typename HashTranslator, typename T, typename Extra>
  672. inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::add(const T& key, const Extra& extra)
  673. {
  674. checkKey<HashTranslator>(key);
  675. invalidateIterators();
  676. if (!m_table)
  677. expand();
  678. internalCheckTableConsistency();
  679. ASSERT(m_table);
  680. int k = 0;
  681. ValueType* table = m_table;
  682. int sizeMask = m_tableSizeMask;
  683. unsigned h = HashTranslator::hash(key);
  684. int i = h & sizeMask;
  685. #if DUMP_HASHTABLE_STATS
  686. atomicIncrement(&HashTableStats::numAccesses);
  687. int probeCount = 0;
  688. #endif
  689. #if DUMP_HASHTABLE_STATS_PER_TABLE
  690. ++m_stats->numAccesses;
  691. int perTableProbeCount = 0;
  692. #endif
  693. ValueType* deletedEntry = 0;
  694. ValueType* entry;
  695. while (1) {
  696. entry = table + i;
  697. // we count on the compiler to optimize out this branch
  698. if (HashFunctions::safeToCompareToEmptyOrDeleted) {
  699. if (isEmptyBucket(*entry))
  700. break;
  701. if (HashTranslator::equal(Extractor::extract(*entry), key))
  702. return AddResult(makeKnownGoodIterator(entry), false);
  703. if (isDeletedBucket(*entry))
  704. deletedEntry = entry;
  705. } else {
  706. if (isEmptyBucket(*entry))
  707. break;
  708. if (isDeletedBucket(*entry))
  709. deletedEntry = entry;
  710. else if (HashTranslator::equal(Extractor::extract(*entry), key))
  711. return AddResult(makeKnownGoodIterator(entry), false);
  712. }
  713. #if DUMP_HASHTABLE_STATS
  714. ++probeCount;
  715. HashTableStats::recordCollisionAtCount(probeCount);
  716. #endif
  717. #if DUMP_HASHTABLE_STATS_PER_TABLE
  718. ++perTableProbeCount;
  719. m_stats->recordCollisionAtCount(perTableProbeCount);
  720. #endif
  721. if (k == 0)
  722. k = 1 | doubleHash(h);
  723. i = (i + k) & sizeMask;
  724. }
  725. if (deletedEntry) {
  726. initializeBucket(*deletedEntry);
  727. entry = deletedEntry;
  728. --m_deletedCount;
  729. }
  730. HashTranslator::translate(*entry, key, extra);
  731. ++m_keyCount;
  732. if (shouldExpand()) {
  733. // FIXME: This makes an extra copy on expand. Probably not that bad since
  734. // expand is rare, but would be better to have a version of expand that can
  735. // follow a pivot entry and return the new position.
  736. KeyType enteredKey = Extractor::extract(*entry);
  737. expand();
  738. AddResult result(find(enteredKey), true);
  739. ASSERT(result.iterator != end());
  740. return result;
  741. }
  742. internalCheckTableConsistency();
  743. return AddResult(makeKnownGoodIterator(entry), true);
  744. }
  745. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  746. template<typename HashTranslator, typename T, typename Extra>
  747. inline typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::addPassingHashCode(const T& key, const Extra& extra)
  748. {
  749. checkKey<HashTranslator>(key);
  750. invalidateIterators();
  751. if (!m_table)
  752. expand();
  753. internalCheckTableConsistency();
  754. FullLookupType lookupResult = fullLookupForWriting<HashTranslator>(key);
  755. ValueType* entry = lookupResult.first.first;
  756. bool found = lookupResult.first.second;
  757. unsigned h = lookupResult.second;
  758. if (found)
  759. return AddResult(makeKnownGoodIterator(entry), false);
  760. if (isDeletedBucket(*entry)) {
  761. initializeBucket(*entry);
  762. --m_deletedCount;
  763. }
  764. HashTranslator::translate(*entry, key, extra, h);
  765. ++m_keyCount;
  766. if (shouldExpand()) {
  767. // FIXME: This makes an extra copy on expand. Probably not that bad since
  768. // expand is rare, but would be better to have a version of expand that can
  769. // follow a pivot entry and return the new position.
  770. KeyType enteredKey = Extractor::extract(*entry);
  771. expand();
  772. AddResult result(find(enteredKey), true);
  773. ASSERT(result.iterator != end());
  774. return result;
  775. }
  776. internalCheckTableConsistency();
  777. return AddResult(makeKnownGoodIterator(entry), true);
  778. }
  779. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  780. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::reinsert(ValueType& entry)
  781. {
  782. ASSERT(m_table);
  783. ASSERT(!lookupForWriting(Extractor::extract(entry)).second);
  784. ASSERT(!isDeletedBucket(*(lookupForWriting(Extractor::extract(entry)).first)));
  785. #if DUMP_HASHTABLE_STATS
  786. atomicIncrement(&HashTableStats::numReinserts);
  787. #endif
  788. #if DUMP_HASHTABLE_STATS_PER_TABLE
  789. ++m_stats->numReinserts;
  790. #endif
  791. Mover<ValueType, Traits::needsDestruction>::move(entry, *lookupForWriting(Extractor::extract(entry)).first);
  792. }
  793. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  794. template <typename HashTranslator, typename T>
  795. typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::find(const T& key)
  796. {
  797. if (!m_table)
  798. return end();
  799. ValueType* entry = lookup<HashTranslator>(key);
  800. if (!entry)
  801. return end();
  802. return makeKnownGoodIterator(entry);
  803. }
  804. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  805. template <typename HashTranslator, typename T>
  806. typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::const_iterator HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::find(const T& key) const
  807. {
  808. if (!m_table)
  809. return end();
  810. ValueType* entry = const_cast<HashTable*>(this)->lookup<HashTranslator>(key);
  811. if (!entry)
  812. return end();
  813. return makeKnownGoodConstIterator(entry);
  814. }
  815. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  816. template <typename HashTranslator, typename T>
  817. bool HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::contains(const T& key) const
  818. {
  819. if (!m_table)
  820. return false;
  821. return const_cast<HashTable*>(this)->lookup<HashTranslator>(key);
  822. }
  823. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  824. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeAndInvalidateWithoutEntryConsistencyCheck(ValueType* pos)
  825. {
  826. invalidateIterators();
  827. remove(pos);
  828. }
  829. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  830. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeAndInvalidate(ValueType* pos)
  831. {
  832. invalidateIterators();
  833. internalCheckTableConsistency();
  834. remove(pos);
  835. }
  836. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  837. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(ValueType* pos)
  838. {
  839. #if DUMP_HASHTABLE_STATS
  840. atomicIncrement(&HashTableStats::numRemoves);
  841. #endif
  842. #if DUMP_HASHTABLE_STATS_PER_TABLE
  843. ++m_stats->numRemoves;
  844. #endif
  845. deleteBucket(*pos);
  846. ++m_deletedCount;
  847. --m_keyCount;
  848. if (shouldShrink())
  849. shrink();
  850. internalCheckTableConsistency();
  851. }
  852. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  853. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(iterator it)
  854. {
  855. if (it == end())
  856. return;
  857. removeAndInvalidate(const_cast<ValueType*>(it.m_iterator.m_position));
  858. }
  859. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  860. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeWithoutEntryConsistencyCheck(iterator it)
  861. {
  862. if (it == end())
  863. return;
  864. removeAndInvalidateWithoutEntryConsistencyCheck(const_cast<ValueType*>(it.m_iterator.m_position));
  865. }
  866. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  867. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::removeWithoutEntryConsistencyCheck(const_iterator it)
  868. {
  869. if (it == end())
  870. return;
  871. removeAndInvalidateWithoutEntryConsistencyCheck(const_cast<ValueType*>(it.m_position));
  872. }
  873. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  874. inline void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::remove(const KeyType& key)
  875. {
  876. remove(find(key));
  877. }
  878. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  879. Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::allocateTable(int size)
  880. {
  881. // would use a template member function with explicit specializations here, but
  882. // gcc doesn't appear to support that
  883. ValueType* result;
  884. #if ENABLE(DETACHED_JIT)
  885. if (Traits::valueIsShared) {
  886. if (Traits::emptyValueIsZero)
  887. return static_cast<ValueType*>(JITSharedDataMemory::shared_calloc(1, size * sizeof(ValueType)));
  888. result = static_cast<ValueType*>(JITSharedDataMemory::shared_malloc(size * sizeof(ValueType)));
  889. } else
  890. #endif
  891. {
  892. if (Traits::emptyValueIsZero)
  893. return static_cast<ValueType*>(fastZeroedMalloc(size * sizeof(ValueType)));
  894. result = static_cast<ValueType*>(fastMalloc(size * sizeof(ValueType)));
  895. }
  896. for (int i = 0; i < size; i++)
  897. initializeBucket(result[i]);
  898. return result;
  899. }
  900. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  901. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::deallocateTable(ValueType* table, int size)
  902. {
  903. if (Traits::needsDestruction) {
  904. for (int i = 0; i < size; ++i) {
  905. if (!isDeletedBucket(table[i]))
  906. table[i].~ValueType();
  907. }
  908. }
  909. #if ENABLE(DETACHED_JIT)
  910. if (Traits::valueIsShared) {
  911. JITSharedDataMemory::shared_free(table);
  912. } else
  913. #endif
  914. {
  915. fastFree(table);
  916. }
  917. }
  918. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  919. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::expand()
  920. {
  921. int newSize;
  922. if (m_tableSize == 0)
  923. newSize = KeyTraits::minimumTableSize;
  924. else if (mustRehashInPlace())
  925. newSize = m_tableSize;
  926. else
  927. newSize = m_tableSize * 2;
  928. rehash(newSize);
  929. }
  930. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  931. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::rehash(int newTableSize)
  932. {
  933. internalCheckTableConsistencyExceptSize();
  934. int oldTableSize = m_tableSize;
  935. ValueType* oldTable = m_table;
  936. #if DUMP_HASHTABLE_STATS
  937. if (oldTableSize != 0)
  938. atomicIncrement(&HashTableStats::numRehashes);
  939. #endif
  940. #if DUMP_HASHTABLE_STATS_PER_TABLE
  941. if (oldTableSize != 0)
  942. ++m_stats->numRehashes;
  943. #endif
  944. m_tableSize = newTableSize;
  945. m_tableSizeMask = newTableSize - 1;
  946. m_table = allocateTable(newTableSize);
  947. for (int i = 0; i != oldTableSize; ++i)
  948. if (!isEmptyOrDeletedBucket(oldTable[i]))
  949. reinsert(oldTable[i]);
  950. m_deletedCount = 0;
  951. deallocateTable(oldTable, oldTableSize);
  952. internalCheckTableConsistency();
  953. }
  954. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  955. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::clear()
  956. {
  957. invalidateIterators();
  958. if (!m_table)
  959. return;
  960. deallocateTable(m_table, m_tableSize);
  961. m_table = 0;
  962. m_tableSize = 0;
  963. m_tableSizeMask = 0;
  964. m_keyCount = 0;
  965. }
  966. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  967. HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::HashTable(const HashTable& other)
  968. : m_table(0)
  969. , m_tableSize(0)
  970. , m_tableSizeMask(0)
  971. , m_keyCount(0)
  972. , m_deletedCount(0)
  973. #if CHECK_HASHTABLE_ITERATORS
  974. , m_iterators(0)
  975. , m_mutex(adoptPtr(new Mutex))
  976. #endif
  977. #if DUMP_HASHTABLE_STATS_PER_TABLE
  978. , m_stats(adoptPtr(new Stats(*other.m_stats)))
  979. #endif
  980. {
  981. // Copy the hash table the dumb way, by adding each element to the new table.
  982. // It might be more efficient to copy the table slots, but it's not clear that efficiency is needed.
  983. const_iterator end = other.end();
  984. for (const_iterator it = other.begin(); it != end; ++it)
  985. add(*it);
  986. }
  987. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  988. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::swap(HashTable& other)
  989. {
  990. invalidateIterators();
  991. other.invalidateIterators();
  992. ValueType* tmp_table = m_table;
  993. m_table = other.m_table;
  994. other.m_table = tmp_table;
  995. int tmp_tableSize = m_tableSize;
  996. m_tableSize = other.m_tableSize;
  997. other.m_tableSize = tmp_tableSize;
  998. int tmp_tableSizeMask = m_tableSizeMask;
  999. m_tableSizeMask = other.m_tableSizeMask;
  1000. other.m_tableSizeMask = tmp_tableSizeMask;
  1001. int tmp_keyCount = m_keyCount;
  1002. m_keyCount = other.m_keyCount;
  1003. other.m_keyCount = tmp_keyCount;
  1004. int tmp_deletedCount = m_deletedCount;
  1005. m_deletedCount = other.m_deletedCount;
  1006. other.m_deletedCount = tmp_deletedCount;
  1007. #if DUMP_HASHTABLE_STATS_PER_TABLE
  1008. m_stats.swap(other.m_stats);
  1009. #endif
  1010. }
  1011. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1012. HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>& HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::operator=(const HashTable& other)
  1013. {
  1014. HashTable tmp(other);
  1015. swap(tmp);
  1016. return *this;
  1017. }
  1018. #if !ASSERT_DISABLED
  1019. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1020. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkTableConsistency() const
  1021. {
  1022. checkTableConsistencyExceptSize();
  1023. ASSERT(!m_table || !shouldExpand());
  1024. ASSERT(!shouldShrink());
  1025. }
  1026. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1027. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::checkTableConsistencyExceptSize() const
  1028. {
  1029. if (!m_table)
  1030. return;
  1031. int count = 0;
  1032. int deletedCount = 0;
  1033. for (int j = 0; j < m_tableSize; ++j) {
  1034. ValueType* entry = m_table + j;
  1035. if (isEmptyBucket(*entry))
  1036. continue;
  1037. if (isDeletedBucket(*entry)) {
  1038. ++deletedCount;
  1039. continue;
  1040. }
  1041. const_iterator it = find(Extractor::extract(*entry));
  1042. ASSERT(entry == it.m_position);
  1043. ++count;
  1044. ValueCheck<Key>::checkConsistency(it->key);
  1045. }
  1046. ASSERT(count == m_keyCount);
  1047. ASSERT(deletedCount == m_deletedCount);
  1048. ASSERT(m_tableSize >= KeyTraits::minimumTableSize);
  1049. ASSERT(m_tableSizeMask);
  1050. ASSERT(m_tableSize == m_tableSizeMask + 1);
  1051. }
  1052. #endif // ASSERT_DISABLED
  1053. #if CHECK_HASHTABLE_ITERATORS
  1054. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1055. void HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>::invalidateIterators()
  1056. {
  1057. MutexLocker lock(*m_mutex);
  1058. const_iterator* next;
  1059. for (const_iterator* p = m_iterators; p; p = next) {
  1060. next = p->m_next;
  1061. p->m_table = 0;
  1062. p->m_next = 0;
  1063. p->m_previous = 0;
  1064. }
  1065. m_iterators = 0;
  1066. }
  1067. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1068. void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* table,
  1069. HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* it)
  1070. {
  1071. it->m_table = table;
  1072. it->m_previous = 0;
  1073. // Insert iterator at head of doubly-linked list of iterators.
  1074. if (!table) {
  1075. it->m_next = 0;
  1076. } else {
  1077. MutexLocker lock(*table->m_mutex);
  1078. ASSERT(table->m_iterators != it);
  1079. it->m_next = table->m_iterators;
  1080. table->m_iterators = it;
  1081. if (it->m_next) {
  1082. ASSERT(!it->m_next->m_previous);
  1083. it->m_next->m_previous = it;
  1084. }
  1085. }
  1086. }
  1087. template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
  1088. void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>* it)
  1089. {
  1090. typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
  1091. typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
  1092. // Delete iterator from doubly-linked list of iterators.
  1093. if (!it->m_table) {
  1094. ASSERT(!it->m_next);
  1095. ASSERT(!it->m_previous);
  1096. } else {
  1097. MutexLocker lock(*it->m_table->m_mutex);
  1098. if (it->m_next) {
  1099. ASSERT(it->m_next->m_previous == it);
  1100. it->m_next->m_previous = it->m_previous;
  1101. }
  1102. if (it->m_previous) {
  1103. ASSERT(it->m_table->m_iterators != it);
  1104. ASSERT(it->m_previous->m_next == it);
  1105. it->m_previous->m_next = it->m_next;
  1106. } else {
  1107. ASSERT(it->m_table->m_iterators == it);
  1108. it->m_table->m_iterators = it->m_next;
  1109. }
  1110. }
  1111. it->m_table = 0;
  1112. it->m_next = 0;
  1113. it->m_previous = 0;
  1114. }
  1115. #endif // CHECK_HASHTABLE_ITERATORS
  1116. // iterator adapters
  1117. template<typename HashTableType, typename ValueType> struct HashTableConstIteratorAdapter {
  1118. HashTableConstIteratorAdapter() {}
  1119. HashTableConstIteratorAdapter(const typename HashTableType::const_iterator& impl) : m_impl(impl) {}
  1120. const ValueType* get() const { return (const ValueType*)m_impl.get(); }
  1121. const ValueType& operator*() const { return *get(); }
  1122. const ValueType* operator->() const { return get(); }
  1123. HashTableConstIteratorAdapter& operator++() { ++m_impl; return *this; }
  1124. // postfix ++ intentionally omitted
  1125. typename HashTableType::const_iterator m_impl;
  1126. };
  1127. template<typename HashTableType, typename ValueType> struct HashTableIteratorAdapter {
  1128. HashTableIteratorAdapter() {}
  1129. HashTableIteratorAdapter(const typename HashTableType::iterator& impl) : m_impl(impl) {}
  1130. ValueType* get() const { return (ValueType*)m_impl.get(); }
  1131. ValueType& operator*() const { return *get(); }
  1132. ValueType* operator->() const { return get(); }
  1133. HashTableIteratorAdapter& operator++() { ++m_impl; return *this; }
  1134. // postfix ++ intentionally omitted
  1135. operator HashTableConstIteratorAdapter<HashTableType, ValueType>() {
  1136. typename HashTableType::const_iterator i = m_impl;
  1137. return i;
  1138. }
  1139. typename HashTableType::iterator m_impl;
  1140. };
  1141. template<typename T, typename U>
  1142. inline bool operator==(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
  1143. {
  1144. return a.m_impl == b.m_impl;
  1145. }
  1146. template<typename T, typename U>
  1147. inline bool operator!=(const HashTableConstIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
  1148. {
  1149. return a.m_impl != b.m_impl;
  1150. }
  1151. template<typename T, typename U>
  1152. inline bool operator==(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
  1153. {
  1154. return a.m_impl == b.m_impl;
  1155. }
  1156. template<typename T, typename U>
  1157. inline bool operator!=(const HashTableIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
  1158. {
  1159. return a.m_impl != b.m_impl;
  1160. }
  1161. // All 4 combinations of ==, != and Const,non const.
  1162. template<typename T, typename U>
  1163. inline bool operator==(const HashTableConstIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
  1164. {
  1165. return a.m_impl == b.m_impl;
  1166. }
  1167. template<typename T, typename U>
  1168. inline bool operator!=(const HashTableConstIteratorAdapter<T, U>& a, const HashTableIteratorAdapter<T, U>& b)
  1169. {
  1170. return a.m_impl != b.m_impl;
  1171. }
  1172. template<typename T, typename U>
  1173. inline bool operator==(const HashTableIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
  1174. {
  1175. return a.m_impl == b.m_impl;
  1176. }
  1177. template<typename T, typename U>
  1178. inline bool operator!=(const HashTableIteratorAdapter<T, U>& a, const HashTableConstIteratorAdapter<T, U>& b)
  1179. {
  1180. return a.m_impl != b.m_impl;
  1181. }
  1182. } // namespace WTF
  1183. #include <wtf/HashIterators.h>
  1184. #endif // WTF_HashTable_h