No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

densehashtable.h 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. // Copyright (c) 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // ---
  30. //
  31. // A dense hashtable is a particular implementation of
  32. // a hashtable: one that is meant to minimize memory allocation.
  33. // It does this by using an array to store all the data. We
  34. // steal a value from the key space to indicate "empty" array
  35. // elements (ie indices where no item lives) and another to indicate
  36. // "deleted" elements.
  37. //
  38. // (Note it is possible to change the value of the delete key
  39. // on the fly; you can even remove it, though after that point
  40. // the hashtable is insert_only until you set it again. The empty
  41. // value however can't be changed.)
  42. //
  43. // To minimize allocation and pointer overhead, we use internal
  44. // probing, in which the hashtable is a single table, and collisions
  45. // are resolved by trying to insert again in another bucket. The
  46. // most cache-efficient internal probing schemes are linear probing
  47. // (which suffers, alas, from clumping) and quadratic probing, which
  48. // is what we implement by default.
  49. //
  50. // Type requirements: value_type is required to be Copy Constructible
  51. // and Default Constructible. It is not required to be (and commonly
  52. // isn't) Assignable.
  53. //
  54. // You probably shouldn't use this code directly. Use dense_hash_map<>
  55. // or dense_hash_set<> instead.
  56. // You can change the following below:
  57. // HT_OCCUPANCY_PCT -- how full before we double size
  58. // HT_EMPTY_PCT -- how empty before we halve size
  59. // HT_MIN_BUCKETS -- default smallest bucket size
  60. //
  61. // You can also change enlarge_factor (which defaults to
  62. // HT_OCCUPANCY_PCT), and shrink_factor (which defaults to
  63. // HT_EMPTY_PCT) with set_resizing_parameters().
  64. //
  65. // How to decide what values to use?
  66. // shrink_factor's default of .4 * OCCUPANCY_PCT, is probably good.
  67. // HT_MIN_BUCKETS is probably unnecessary since you can specify
  68. // (indirectly) the starting number of buckets at construct-time.
  69. // For enlarge_factor, you can use this chart to try to trade-off
  70. // expected lookup time to the space taken up. By default, this
  71. // code uses quadratic probing, though you can change it to linear
  72. // via JUMP_ below if you really want to.
  73. //
  74. // From http://www.augustana.ca/~mohrj/courses/1999.fall/csc210/lecture_notes/hashing.html
  75. // NUMBER OF PROBES / LOOKUP Successful Unsuccessful
  76. // Quadratic collision resolution 1 - ln(1-L) - L/2 1/(1-L) - L - ln(1-L)
  77. // Linear collision resolution [1+1/(1-L)]/2 [1+1/(1-L)2]/2
  78. //
  79. // -- enlarge_factor -- 0.10 0.50 0.60 0.75 0.80 0.90 0.99
  80. // QUADRATIC COLLISION RES.
  81. // probes/successful lookup 1.05 1.44 1.62 2.01 2.21 2.85 5.11
  82. // probes/unsuccessful lookup 1.11 2.19 2.82 4.64 5.81 11.4 103.6
  83. // LINEAR COLLISION RES.
  84. // probes/successful lookup 1.06 1.5 1.75 2.5 3.0 5.5 50.5
  85. // probes/unsuccessful lookup 1.12 2.5 3.6 8.5 13.0 50.0 5000.0
  86. #ifndef _DENSEHASHTABLE_H_
  87. #define _DENSEHASHTABLE_H_
  88. #include "sparseconfig.h"
  89. #include <assert.h>
  90. #include <stdio.h> // for FILE, fwrite, fread
  91. #include <algorithm> // For swap(), eg
  92. #include <iterator> // For iterator tags
  93. #include <limits> // for numeric_limits
  94. #include <memory> // For uninitialized_fill
  95. #include <utility> // for pair
  96. #include "hashtable-common.h"
  97. #include "libc_allocator_with_realloc.h"
  98. #include "../type_traits.h"
  99. #include <stdexcept> // For length_error
  100. _START_GOOGLE_NAMESPACE_
  101. namespace base { // just to make google->opensource transition easier
  102. using GOOGLE_NAMESPACE::true_type;
  103. using GOOGLE_NAMESPACE::false_type;
  104. using GOOGLE_NAMESPACE::integral_constant;
  105. using GOOGLE_NAMESPACE::is_same;
  106. using GOOGLE_NAMESPACE::remove_const;
  107. }
  108. // The probing method
  109. // Linear probing
  110. // #define JUMP_(key, num_probes) ( 1 )
  111. // Quadratic probing
  112. #define JUMP_(key, num_probes) ( num_probes )
  113. // Hashtable class, used to implement the hashed associative containers
  114. // hash_set and hash_map.
  115. // Value: what is stored in the table (each bucket is a Value).
  116. // Key: something in a 1-to-1 correspondence to a Value, that can be used
  117. // to search for a Value in the table (find() takes a Key).
  118. // HashFcn: Takes a Key and returns an integer, the more unique the better.
  119. // ExtractKey: given a Value, returns the unique Key associated with it.
  120. // Must inherit from unary_function, or at least have a
  121. // result_type enum indicating the return type of operator().
  122. // SetKey: given a Value* and a Key, modifies the value such that
  123. // ExtractKey(value) == key. We guarantee this is only called
  124. // with key == deleted_key or key == empty_key.
  125. // EqualKey: Given two Keys, says whether they are the same (that is,
  126. // if they are both associated with the same Value).
  127. // Alloc: STL allocator to use to allocate memory.
  128. template <class Value, class Key, class HashFcn,
  129. class ExtractKey, class SetKey, class EqualKey, class Alloc>
  130. class dense_hashtable;
  131. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  132. struct dense_hashtable_iterator;
  133. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  134. struct dense_hashtable_const_iterator;
  135. // We're just an array, but we need to skip over empty and deleted elements
  136. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  137. struct dense_hashtable_iterator {
  138. private:
  139. typedef typename A::template rebind<V>::other value_alloc_type;
  140. public:
  141. typedef dense_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
  142. typedef dense_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
  143. typedef std::forward_iterator_tag iterator_category; // very little defined!
  144. typedef V value_type;
  145. typedef typename value_alloc_type::difference_type difference_type;
  146. typedef typename value_alloc_type::size_type size_type;
  147. typedef typename value_alloc_type::reference reference;
  148. typedef typename value_alloc_type::pointer pointer;
  149. // "Real" constructor and default constructor
  150. dense_hashtable_iterator(const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
  151. pointer it, pointer it_end, bool advance)
  152. : ht(h), pos(it), end(it_end) {
  153. if (advance) advance_past_empty_and_deleted();
  154. }
  155. dense_hashtable_iterator() { }
  156. // The default destructor is fine; we don't define one
  157. // The default operator= is fine; we don't define one
  158. // Happy dereferencer
  159. reference operator*() const { return *pos; }
  160. pointer operator->() const { return &(operator*()); }
  161. // Arithmetic. The only hard part is making sure that
  162. // we're not on an empty or marked-deleted array element
  163. void advance_past_empty_and_deleted() {
  164. while ( pos != end && (ht->test_empty(*this) || ht->test_deleted(*this)) )
  165. ++pos;
  166. }
  167. iterator& operator++() {
  168. assert(pos != end); ++pos; advance_past_empty_and_deleted(); return *this;
  169. }
  170. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  171. // Comparison.
  172. bool operator==(const iterator& it) const { return pos == it.pos; }
  173. bool operator!=(const iterator& it) const { return pos != it.pos; }
  174. // The actual data
  175. const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
  176. pointer pos, end;
  177. };
  178. // Now do it all again, but with const-ness!
  179. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  180. struct dense_hashtable_const_iterator {
  181. private:
  182. typedef typename A::template rebind<V>::other value_alloc_type;
  183. public:
  184. typedef dense_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
  185. typedef dense_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
  186. typedef std::forward_iterator_tag iterator_category; // very little defined!
  187. typedef V value_type;
  188. typedef typename value_alloc_type::difference_type difference_type;
  189. typedef typename value_alloc_type::size_type size_type;
  190. typedef typename value_alloc_type::const_reference reference;
  191. typedef typename value_alloc_type::const_pointer pointer;
  192. // "Real" constructor and default constructor
  193. dense_hashtable_const_iterator(
  194. const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
  195. pointer it, pointer it_end, bool advance)
  196. : ht(h), pos(it), end(it_end) {
  197. if (advance) advance_past_empty_and_deleted();
  198. }
  199. dense_hashtable_const_iterator()
  200. : ht(NULL), pos(pointer()), end(pointer()) { }
  201. // This lets us convert regular iterators to const iterators
  202. dense_hashtable_const_iterator(const iterator &it)
  203. : ht(it.ht), pos(it.pos), end(it.end) { }
  204. // The default destructor is fine; we don't define one
  205. // The default operator= is fine; we don't define one
  206. // Happy dereferencer
  207. reference operator*() const { return *pos; }
  208. pointer operator->() const { return &(operator*()); }
  209. // Arithmetic. The only hard part is making sure that
  210. // we're not on an empty or marked-deleted array element
  211. void advance_past_empty_and_deleted() {
  212. while ( pos != end && (ht->test_empty(*this) || ht->test_deleted(*this)) )
  213. ++pos;
  214. }
  215. const_iterator& operator++() {
  216. assert(pos != end); ++pos; advance_past_empty_and_deleted(); return *this;
  217. }
  218. const_iterator operator++(int) { const_iterator tmp(*this); ++*this; return tmp; }
  219. // Comparison.
  220. bool operator==(const const_iterator& it) const { return pos == it.pos; }
  221. bool operator!=(const const_iterator& it) const { return pos != it.pos; }
  222. // The actual data
  223. const dense_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
  224. pointer pos, end;
  225. };
  226. template <class Value, class Key, class HashFcn,
  227. class ExtractKey, class SetKey, class EqualKey, class Alloc>
  228. class dense_hashtable {
  229. private:
  230. typedef typename Alloc::template rebind<Value>::other value_alloc_type;
  231. public:
  232. typedef Key key_type;
  233. typedef Value value_type;
  234. typedef HashFcn hasher;
  235. typedef EqualKey key_equal;
  236. typedef Alloc allocator_type;
  237. typedef typename value_alloc_type::size_type size_type;
  238. typedef typename value_alloc_type::difference_type difference_type;
  239. typedef typename value_alloc_type::reference reference;
  240. typedef typename value_alloc_type::const_reference const_reference;
  241. typedef typename value_alloc_type::pointer pointer;
  242. typedef typename value_alloc_type::const_pointer const_pointer;
  243. typedef dense_hashtable_iterator<Value, Key, HashFcn,
  244. ExtractKey, SetKey, EqualKey, Alloc>
  245. iterator;
  246. typedef dense_hashtable_const_iterator<Value, Key, HashFcn,
  247. ExtractKey, SetKey, EqualKey, Alloc>
  248. const_iterator;
  249. // These come from tr1. For us they're the same as regular iterators.
  250. typedef iterator local_iterator;
  251. typedef const_iterator const_local_iterator;
  252. // How full we let the table get before we resize, by default.
  253. // Knuth says .8 is good -- higher causes us to probe too much,
  254. // though it saves memory.
  255. static const int HT_OCCUPANCY_PCT; // defined at the bottom of this file
  256. // How empty we let the table get before we resize lower, by default.
  257. // (0.0 means never resize lower.)
  258. // It should be less than OCCUPANCY_PCT / 2 or we thrash resizing
  259. static const int HT_EMPTY_PCT; // defined at the bottom of this file
  260. // Minimum size we're willing to let hashtables be.
  261. // Must be a power of two, and at least 4.
  262. // Note, however, that for a given hashtable, the initial size is a
  263. // function of the first constructor arg, and may be >HT_MIN_BUCKETS.
  264. static const size_type HT_MIN_BUCKETS = 4;
  265. // By default, if you don't specify a hashtable size at
  266. // construction-time, we use this size. Must be a power of two, and
  267. // at least HT_MIN_BUCKETS.
  268. static const size_type HT_DEFAULT_STARTING_BUCKETS = 32;
  269. // ITERATOR FUNCTIONS
  270. iterator begin() { return iterator(this, table,
  271. table + num_buckets, true); }
  272. iterator end() { return iterator(this, table + num_buckets,
  273. table + num_buckets, true); }
  274. const_iterator begin() const { return const_iterator(this, table,
  275. table+num_buckets,true);}
  276. const_iterator end() const { return const_iterator(this, table + num_buckets,
  277. table+num_buckets,true);}
  278. // These come from tr1 unordered_map. They iterate over 'bucket' n.
  279. // We'll just consider bucket n to be the n-th element of the table.
  280. local_iterator begin(size_type i) {
  281. return local_iterator(this, table + i, table + i+1, false);
  282. }
  283. local_iterator end(size_type i) {
  284. local_iterator it = begin(i);
  285. if (!test_empty(i) && !test_deleted(i))
  286. ++it;
  287. return it;
  288. }
  289. const_local_iterator begin(size_type i) const {
  290. return const_local_iterator(this, table + i, table + i+1, false);
  291. }
  292. const_local_iterator end(size_type i) const {
  293. const_local_iterator it = begin(i);
  294. if (!test_empty(i) && !test_deleted(i))
  295. ++it;
  296. return it;
  297. }
  298. // ACCESSOR FUNCTIONS for the things we templatize on, basically
  299. hasher hash_funct() const { return settings; }
  300. key_equal key_eq() const { return key_info; }
  301. allocator_type get_allocator() const {
  302. return allocator_type(val_info);
  303. }
  304. // Accessor function for statistics gathering.
  305. int num_table_copies() const { return settings.num_ht_copies(); }
  306. private:
  307. // Annoyingly, we can't copy values around, because they might have
  308. // const components (they're probably pair<const X, Y>). We use
  309. // explicit destructor invocation and placement new to get around
  310. // this. Arg.
  311. void set_value(pointer dst, const_reference src) {
  312. dst->~value_type(); // delete the old value, if any
  313. new(dst) value_type(src);
  314. }
  315. void destroy_buckets(size_type first, size_type last) {
  316. for ( ; first != last; ++first)
  317. table[first].~value_type();
  318. }
  319. // DELETE HELPER FUNCTIONS
  320. // This lets the user describe a key that will indicate deleted
  321. // table entries. This key should be an "impossible" entry --
  322. // if you try to insert it for real, you won't be able to retrieve it!
  323. // (NB: while you pass in an entire value, only the key part is looked
  324. // at. This is just because I don't know how to assign just a key.)
  325. private:
  326. void squash_deleted() { // gets rid of any deleted entries we have
  327. if ( num_deleted ) { // get rid of deleted before writing
  328. dense_hashtable tmp(*this); // copying will get rid of deleted
  329. swap(tmp); // now we are tmp
  330. }
  331. assert(num_deleted == 0);
  332. }
  333. // Test if the given key is the deleted indicator. Requires
  334. // num_deleted > 0, for correctness of read(), and because that
  335. // guarantees that key_info.delkey is valid.
  336. bool test_deleted_key(const key_type& key) const {
  337. assert(num_deleted > 0);
  338. return equals(key_info.delkey, key);
  339. }
  340. public:
  341. void set_deleted_key(const key_type &key) {
  342. // the empty indicator (if specified) and the deleted indicator
  343. // must be different
  344. assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
  345. && "Passed the empty-key to set_deleted_key");
  346. // It's only safe to change what "deleted" means if we purge deleted guys
  347. squash_deleted();
  348. settings.set_use_deleted(true);
  349. key_info.delkey = key;
  350. }
  351. void clear_deleted_key() {
  352. squash_deleted();
  353. settings.set_use_deleted(false);
  354. }
  355. key_type deleted_key() const {
  356. assert(settings.use_deleted()
  357. && "Must set deleted key before calling deleted_key");
  358. return key_info.delkey;
  359. }
  360. // These are public so the iterators can use them
  361. // True if the item at position bucknum is "deleted" marker
  362. bool test_deleted(size_type bucknum) const {
  363. // Invariant: !use_deleted() implies num_deleted is 0.
  364. assert(settings.use_deleted() || num_deleted == 0);
  365. return num_deleted > 0 && test_deleted_key(get_key(table[bucknum]));
  366. }
  367. bool test_deleted(const iterator &it) const {
  368. // Invariant: !use_deleted() implies num_deleted is 0.
  369. assert(settings.use_deleted() || num_deleted == 0);
  370. return num_deleted > 0 && test_deleted_key(get_key(*it));
  371. }
  372. bool test_deleted(const const_iterator &it) const {
  373. // Invariant: !use_deleted() implies num_deleted is 0.
  374. assert(settings.use_deleted() || num_deleted == 0);
  375. return num_deleted > 0 && test_deleted_key(get_key(*it));
  376. }
  377. private:
  378. void check_use_deleted(const char* caller) {
  379. (void)caller; // could log it if the assert failed
  380. assert(settings.use_deleted());
  381. }
  382. // Set it so test_deleted is true. true if object didn't used to be deleted.
  383. bool set_deleted(iterator &it) {
  384. check_use_deleted("set_deleted()");
  385. bool retval = !test_deleted(it);
  386. // &* converts from iterator to value-type.
  387. set_key(&(*it), key_info.delkey);
  388. return retval;
  389. }
  390. // Set it so test_deleted is false. true if object used to be deleted.
  391. bool clear_deleted(iterator &it) {
  392. check_use_deleted("clear_deleted()");
  393. // Happens automatically when we assign something else in its place.
  394. return test_deleted(it);
  395. }
  396. // We also allow to set/clear the deleted bit on a const iterator.
  397. // We allow a const_iterator for the same reason you can delete a
  398. // const pointer: it's convenient, and semantically you can't use
  399. // 'it' after it's been deleted anyway, so its const-ness doesn't
  400. // really matter.
  401. bool set_deleted(const_iterator &it) {
  402. check_use_deleted("set_deleted()");
  403. bool retval = !test_deleted(it);
  404. set_key(const_cast<pointer>(&(*it)), key_info.delkey);
  405. return retval;
  406. }
  407. // Set it so test_deleted is false. true if object used to be deleted.
  408. bool clear_deleted(const_iterator &it) {
  409. check_use_deleted("clear_deleted()");
  410. return test_deleted(it);
  411. }
  412. // EMPTY HELPER FUNCTIONS
  413. // This lets the user describe a key that will indicate empty (unused)
  414. // table entries. This key should be an "impossible" entry --
  415. // if you try to insert it for real, you won't be able to retrieve it!
  416. // (NB: while you pass in an entire value, only the key part is looked
  417. // at. This is just because I don't know how to assign just a key.)
  418. public:
  419. // These are public so the iterators can use them
  420. // True if the item at position bucknum is "empty" marker
  421. bool test_empty(size_type bucknum) const {
  422. assert(settings.use_empty()); // we always need to know what's empty!
  423. return equals(get_key(val_info.emptyval), get_key(table[bucknum]));
  424. }
  425. bool test_empty(const iterator &it) const {
  426. assert(settings.use_empty()); // we always need to know what's empty!
  427. return equals(get_key(val_info.emptyval), get_key(*it));
  428. }
  429. bool test_empty(const const_iterator &it) const {
  430. assert(settings.use_empty()); // we always need to know what's empty!
  431. return equals(get_key(val_info.emptyval), get_key(*it));
  432. }
  433. private:
  434. void fill_range_with_empty(pointer table_start, pointer table_end) {
  435. std::uninitialized_fill(table_start, table_end, val_info.emptyval);
  436. }
  437. public:
  438. // TODO(csilvers): change all callers of this to pass in a key instead,
  439. // and take a const key_type instead of const value_type.
  440. void set_empty_key(const_reference val) {
  441. // Once you set the empty key, you can't change it
  442. assert(!settings.use_empty() && "Calling set_empty_key multiple times");
  443. // The deleted indicator (if specified) and the empty indicator
  444. // must be different.
  445. assert((!settings.use_deleted() || !equals(get_key(val), key_info.delkey))
  446. && "Setting the empty key the same as the deleted key");
  447. settings.set_use_empty(true);
  448. set_value(&val_info.emptyval, val);
  449. assert(!table); // must set before first use
  450. // num_buckets was set in constructor even though table was NULL
  451. table = val_info.allocate(num_buckets);
  452. assert(table);
  453. fill_range_with_empty(table, table + num_buckets);
  454. }
  455. // TODO(user): return a key_type rather than a value_type
  456. value_type empty_key() const {
  457. assert(settings.use_empty());
  458. return val_info.emptyval;
  459. }
  460. // FUNCTIONS CONCERNING SIZE
  461. public:
  462. size_type size() const { return num_elements - num_deleted; }
  463. size_type max_size() const { return val_info.max_size(); }
  464. bool empty() const { return size() == 0; }
  465. size_type bucket_count() const { return num_buckets; }
  466. size_type max_bucket_count() const { return max_size(); }
  467. size_type nonempty_bucket_count() const { return num_elements; }
  468. // These are tr1 methods. Their idea of 'bucket' doesn't map well to
  469. // what we do. We just say every bucket has 0 or 1 items in it.
  470. size_type bucket_size(size_type i) const {
  471. return begin(i) == end(i) ? 0 : 1;
  472. }
  473. private:
  474. // Because of the above, size_type(-1) is never legal; use it for errors
  475. static const size_type ILLEGAL_BUCKET = size_type(-1);
  476. // Used after a string of deletes. Returns true if we actually shrunk.
  477. // TODO(csilvers): take a delta so we can take into account inserts
  478. // done after shrinking. Maybe make part of the Settings class?
  479. bool maybe_shrink() {
  480. assert(num_elements >= num_deleted);
  481. assert((bucket_count() & (bucket_count()-1)) == 0); // is a power of two
  482. assert(bucket_count() >= HT_MIN_BUCKETS);
  483. bool retval = false;
  484. // If you construct a hashtable with < HT_DEFAULT_STARTING_BUCKETS,
  485. // we'll never shrink until you get relatively big, and we'll never
  486. // shrink below HT_DEFAULT_STARTING_BUCKETS. Otherwise, something
  487. // like "dense_hash_set<int> x; x.insert(4); x.erase(4);" will
  488. // shrink us down to HT_MIN_BUCKETS buckets, which is too small.
  489. const size_type num_remain = num_elements - num_deleted;
  490. const size_type shrink_threshold = settings.shrink_threshold();
  491. if (shrink_threshold > 0 && num_remain < shrink_threshold &&
  492. bucket_count() > HT_DEFAULT_STARTING_BUCKETS) {
  493. const float shrink_factor = settings.shrink_factor();
  494. size_type sz = bucket_count() / 2; // find how much we should shrink
  495. while (sz > HT_DEFAULT_STARTING_BUCKETS &&
  496. num_remain < sz * shrink_factor) {
  497. sz /= 2; // stay a power of 2
  498. }
  499. dense_hashtable tmp(*this, sz); // Do the actual resizing
  500. swap(tmp); // now we are tmp
  501. retval = true;
  502. }
  503. settings.set_consider_shrink(false); // because we just considered it
  504. return retval;
  505. }
  506. // We'll let you resize a hashtable -- though this makes us copy all!
  507. // When you resize, you say, "make it big enough for this many more elements"
  508. // Returns true if we actually resized, false if size was already ok.
  509. bool resize_delta(size_type delta) {
  510. bool did_resize = false;
  511. if ( settings.consider_shrink() ) { // see if lots of deletes happened
  512. if ( maybe_shrink() )
  513. did_resize = true;
  514. }
  515. if (num_elements >=
  516. (std::numeric_limits<size_type>::max)() - delta) {
  517. assert(false && "resize overflow");
  518. exit(-1);
  519. }
  520. if ( bucket_count() >= HT_MIN_BUCKETS &&
  521. (num_elements + delta) <= settings.enlarge_threshold() )
  522. return did_resize; // we're ok as we are
  523. // Sometimes, we need to resize just to get rid of all the
  524. // "deleted" buckets that are clogging up the hashtable. So when
  525. // deciding whether to resize, count the deleted buckets (which
  526. // are currently taking up room). But later, when we decide what
  527. // size to resize to, *don't* count deleted buckets, since they
  528. // get discarded during the resize.
  529. size_type needed_size = settings.min_buckets(num_elements + delta, 0);
  530. if ( needed_size <= bucket_count() ) // we have enough buckets
  531. return did_resize;
  532. size_type resize_to =
  533. settings.min_buckets(num_elements - num_deleted + delta, bucket_count());
  534. // When num_deleted is large, we may still grow but we do not want to
  535. // over expand. So we reduce needed_size by a portion of num_deleted
  536. // (the exact portion does not matter). This is especially helpful
  537. // when min_load_factor is zero (no shrink at all) to avoid doubling
  538. // the bucket count to infinity. See also test ResizeWithoutShrink.
  539. needed_size = settings.min_buckets(num_elements - num_deleted / 4 + delta, 0);
  540. if (resize_to < needed_size && // may double resize_to
  541. resize_to < (std::numeric_limits<size_type>::max)() / 2) {
  542. // This situation means that we have enough deleted elements,
  543. // that once we purge them, we won't actually have needed to
  544. // grow. But we may want to grow anyway: if we just purge one
  545. // element, say, we'll have to grow anyway next time we
  546. // insert. Might as well grow now, since we're already going
  547. // through the trouble of copying (in order to purge the
  548. // deleted elements).
  549. const size_type target =
  550. static_cast<size_type>(settings.shrink_size(resize_to*2));
  551. if (num_elements - num_deleted + delta >= target) {
  552. // Good, we won't be below the shrink threshhold even if we double.
  553. resize_to *= 2;
  554. }
  555. }
  556. dense_hashtable tmp(*this, resize_to);
  557. swap(tmp); // now we are tmp
  558. return true;
  559. }
  560. // We require table be not-NULL and empty before calling this.
  561. void resize_table(size_type /*old_size*/, size_type new_size,
  562. base::true_type) {
  563. table = val_info.realloc_or_die(table, new_size);
  564. }
  565. void resize_table(size_type old_size, size_type new_size, base::false_type) {
  566. val_info.deallocate(table, old_size);
  567. table = val_info.allocate(new_size);
  568. }
  569. // Used to actually do the rehashing when we grow/shrink a hashtable
  570. void copy_from(const dense_hashtable &ht, size_type min_buckets_wanted) {
  571. clear_to_size(settings.min_buckets(ht.size(), min_buckets_wanted));
  572. // We use a normal iterator to get non-deleted bcks from ht
  573. // We could use insert() here, but since we know there are
  574. // no duplicates and no deleted items, we can be more efficient
  575. assert((bucket_count() & (bucket_count()-1)) == 0); // a power of two
  576. for ( const_iterator it = ht.begin(); it != ht.end(); ++it ) {
  577. size_type num_probes = 0; // how many times we've probed
  578. size_type bucknum;
  579. const size_type bucket_count_minus_one = bucket_count() - 1;
  580. for (bucknum = hash(get_key(*it)) & bucket_count_minus_one;
  581. !test_empty(bucknum); // not empty
  582. bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one) {
  583. ++num_probes;
  584. assert(num_probes < bucket_count()
  585. && "Hashtable is full: an error in key_equal<> or hash<>");
  586. }
  587. set_value(&table[bucknum], *it); // copies the value to here
  588. num_elements++;
  589. }
  590. settings.inc_num_ht_copies();
  591. }
  592. // Required by the spec for hashed associative container
  593. public:
  594. // Though the docs say this should be num_buckets, I think it's much
  595. // more useful as num_elements. As a special feature, calling with
  596. // req_elements==0 will cause us to shrink if we can, saving space.
  597. void resize(size_type req_elements) { // resize to this or larger
  598. if ( settings.consider_shrink() || req_elements == 0 )
  599. maybe_shrink();
  600. if ( req_elements > num_elements )
  601. resize_delta(req_elements - num_elements);
  602. }
  603. // Get and change the value of shrink_factor and enlarge_factor. The
  604. // description at the beginning of this file explains how to choose
  605. // the values. Setting the shrink parameter to 0.0 ensures that the
  606. // table never shrinks.
  607. void get_resizing_parameters(float* shrink, float* grow) const {
  608. *shrink = settings.shrink_factor();
  609. *grow = settings.enlarge_factor();
  610. }
  611. void set_resizing_parameters(float shrink, float grow) {
  612. settings.set_resizing_parameters(shrink, grow);
  613. settings.reset_thresholds(bucket_count());
  614. }
  615. // CONSTRUCTORS -- as required by the specs, we take a size,
  616. // but also let you specify a hashfunction, key comparator,
  617. // and key extractor. We also define a copy constructor and =.
  618. // DESTRUCTOR -- needs to free the table
  619. explicit dense_hashtable(size_type expected_max_items_in_table = 0,
  620. const HashFcn& hf = HashFcn(),
  621. const EqualKey& eql = EqualKey(),
  622. const ExtractKey& ext = ExtractKey(),
  623. const SetKey& set = SetKey(),
  624. const Alloc& alloc = Alloc())
  625. : settings(hf),
  626. key_info(ext, set, eql),
  627. num_deleted(0),
  628. num_elements(0),
  629. num_buckets(expected_max_items_in_table == 0
  630. ? HT_DEFAULT_STARTING_BUCKETS
  631. : settings.min_buckets(expected_max_items_in_table, 0)),
  632. val_info(alloc_impl<value_alloc_type>(alloc)),
  633. table(NULL) {
  634. // table is NULL until emptyval is set. However, we set num_buckets
  635. // here so we know how much space to allocate once emptyval is set
  636. settings.reset_thresholds(bucket_count());
  637. }
  638. // As a convenience for resize(), we allow an optional second argument
  639. // which lets you make this new hashtable a different size than ht
  640. dense_hashtable(const dense_hashtable& ht,
  641. size_type min_buckets_wanted = HT_DEFAULT_STARTING_BUCKETS)
  642. : settings(ht.settings),
  643. key_info(ht.key_info),
  644. num_deleted(0),
  645. num_elements(0),
  646. num_buckets(0),
  647. val_info(ht.val_info),
  648. table(NULL) {
  649. if (!ht.settings.use_empty()) {
  650. // If use_empty isn't set, copy_from will crash, so we do our own copying.
  651. assert(ht.empty());
  652. num_buckets = settings.min_buckets(ht.size(), min_buckets_wanted);
  653. settings.reset_thresholds(bucket_count());
  654. return;
  655. }
  656. settings.reset_thresholds(bucket_count());
  657. copy_from(ht, min_buckets_wanted); // copy_from() ignores deleted entries
  658. }
  659. dense_hashtable& operator= (const dense_hashtable& ht) {
  660. if (&ht == this) return *this; // don't copy onto ourselves
  661. if (!ht.settings.use_empty()) {
  662. assert(ht.empty());
  663. dense_hashtable empty_table(ht); // empty table with ht's thresholds
  664. this->swap(empty_table);
  665. return *this;
  666. }
  667. settings = ht.settings;
  668. key_info = ht.key_info;
  669. set_value(&val_info.emptyval, ht.val_info.emptyval);
  670. // copy_from() calls clear and sets num_deleted to 0 too
  671. copy_from(ht, HT_MIN_BUCKETS);
  672. // we purposefully don't copy the allocator, which may not be copyable
  673. return *this;
  674. }
  675. ~dense_hashtable() {
  676. if (table) {
  677. destroy_buckets(0, num_buckets);
  678. val_info.deallocate(table, num_buckets);
  679. }
  680. }
  681. // Many STL algorithms use swap instead of copy constructors
  682. void swap(dense_hashtable& ht) {
  683. std::swap(settings, ht.settings);
  684. std::swap(key_info, ht.key_info);
  685. std::swap(num_deleted, ht.num_deleted);
  686. std::swap(num_elements, ht.num_elements);
  687. std::swap(num_buckets, ht.num_buckets);
  688. { value_type tmp; // for annoying reasons, swap() doesn't work
  689. set_value(&tmp, val_info.emptyval);
  690. set_value(&val_info.emptyval, ht.val_info.emptyval);
  691. set_value(&ht.val_info.emptyval, tmp);
  692. }
  693. std::swap(table, ht.table);
  694. settings.reset_thresholds(bucket_count()); // also resets consider_shrink
  695. ht.settings.reset_thresholds(ht.bucket_count());
  696. // we purposefully don't swap the allocator, which may not be swap-able
  697. }
  698. private:
  699. void clear_to_size(size_type new_num_buckets) {
  700. if (!table) {
  701. table = val_info.allocate(new_num_buckets);
  702. } else {
  703. destroy_buckets(0, num_buckets);
  704. if (new_num_buckets != num_buckets) { // resize, if necessary
  705. typedef base::integral_constant<bool,
  706. base::is_same<value_alloc_type,
  707. libc_allocator_with_realloc<value_type> >::value>
  708. realloc_ok;
  709. resize_table(num_buckets, new_num_buckets, realloc_ok());
  710. }
  711. }
  712. assert(table);
  713. fill_range_with_empty(table, table + new_num_buckets);
  714. num_elements = 0;
  715. num_deleted = 0;
  716. num_buckets = new_num_buckets; // our new size
  717. settings.reset_thresholds(bucket_count());
  718. }
  719. public:
  720. // It's always nice to be able to clear a table without deallocating it
  721. void clear() {
  722. // If the table is already empty, and the number of buckets is
  723. // already as we desire, there's nothing to do.
  724. const size_type new_num_buckets = settings.min_buckets(0, 0);
  725. if (num_elements == 0 && new_num_buckets == num_buckets) {
  726. return;
  727. }
  728. clear_to_size(new_num_buckets);
  729. }
  730. // Clear the table without resizing it.
  731. // Mimicks the stl_hashtable's behaviour when clear()-ing in that it
  732. // does not modify the bucket count
  733. void clear_no_resize() {
  734. if (num_elements > 0) {
  735. assert(table);
  736. destroy_buckets(0, num_buckets);
  737. fill_range_with_empty(table, table + num_buckets);
  738. }
  739. // don't consider to shrink before another erase()
  740. settings.reset_thresholds(bucket_count());
  741. num_elements = 0;
  742. num_deleted = 0;
  743. }
  744. // LOOKUP ROUTINES
  745. private:
  746. // Returns a pair of positions: 1st where the object is, 2nd where
  747. // it would go if you wanted to insert it. 1st is ILLEGAL_BUCKET
  748. // if object is not found; 2nd is ILLEGAL_BUCKET if it is.
  749. // Note: because of deletions where-to-insert is not trivial: it's the
  750. // first deleted bucket we see, as long as we don't find the key later
  751. std::pair<size_type, size_type> find_position(const key_type &key) const {
  752. size_type num_probes = 0; // how many times we've probed
  753. const size_type bucket_count_minus_one = bucket_count() - 1;
  754. size_type bucknum = hash(key) & bucket_count_minus_one;
  755. size_type insert_pos = ILLEGAL_BUCKET; // where we would insert
  756. while ( 1 ) { // probe until something happens
  757. if ( test_empty(bucknum) ) { // bucket is empty
  758. if ( insert_pos == ILLEGAL_BUCKET ) // found no prior place to insert
  759. return std::pair<size_type,size_type>(ILLEGAL_BUCKET, bucknum);
  760. else
  761. return std::pair<size_type,size_type>(ILLEGAL_BUCKET, insert_pos);
  762. } else if ( test_deleted(bucknum) ) {// keep searching, but mark to insert
  763. if ( insert_pos == ILLEGAL_BUCKET )
  764. insert_pos = bucknum;
  765. } else if ( equals(key, get_key(table[bucknum])) ) {
  766. return std::pair<size_type,size_type>(bucknum, ILLEGAL_BUCKET);
  767. }
  768. ++num_probes; // we're doing another probe
  769. bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one;
  770. assert(num_probes < bucket_count()
  771. && "Hashtable is full: an error in key_equal<> or hash<>");
  772. }
  773. }
  774. public:
  775. iterator find(const key_type& key) {
  776. if ( size() == 0 ) return end();
  777. std::pair<size_type, size_type> pos = find_position(key);
  778. if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
  779. return end();
  780. else
  781. return iterator(this, table + pos.first, table + num_buckets, false);
  782. }
  783. const_iterator find(const key_type& key) const {
  784. if ( size() == 0 ) return end();
  785. std::pair<size_type, size_type> pos = find_position(key);
  786. if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
  787. return end();
  788. else
  789. return const_iterator(this, table + pos.first, table+num_buckets, false);
  790. }
  791. // This is a tr1 method: the bucket a given key is in, or what bucket
  792. // it would be put in, if it were to be inserted. Shrug.
  793. size_type bucket(const key_type& key) const {
  794. std::pair<size_type, size_type> pos = find_position(key);
  795. return pos.first == ILLEGAL_BUCKET ? pos.second : pos.first;
  796. }
  797. // Counts how many elements have key key. For maps, it's either 0 or 1.
  798. size_type count(const key_type &key) const {
  799. std::pair<size_type, size_type> pos = find_position(key);
  800. return pos.first == ILLEGAL_BUCKET ? 0 : 1;
  801. }
  802. // Likewise, equal_range doesn't really make sense for us. Oh well.
  803. std::pair<iterator,iterator> equal_range(const key_type& key) {
  804. iterator pos = find(key); // either an iterator or end
  805. if (pos == end()) {
  806. return std::pair<iterator,iterator>(pos, pos);
  807. } else {
  808. const iterator startpos = pos++;
  809. return std::pair<iterator,iterator>(startpos, pos);
  810. }
  811. }
  812. std::pair<const_iterator,const_iterator> equal_range(const key_type& key)
  813. const {
  814. const_iterator pos = find(key); // either an iterator or end
  815. if (pos == end()) {
  816. return std::pair<const_iterator,const_iterator>(pos, pos);
  817. } else {
  818. const const_iterator startpos = pos++;
  819. return std::pair<const_iterator,const_iterator>(startpos, pos);
  820. }
  821. }
  822. // INSERTION ROUTINES
  823. private:
  824. // Private method used by insert_noresize and find_or_insert.
  825. iterator insert_at(const_reference obj, size_type pos) {
  826. if (size() >= max_size()) {
  827. assert(false && "insert overflow");
  828. exit(-1);
  829. }
  830. if ( test_deleted(pos) ) { // just replace if it's been del.
  831. // shrug: shouldn't need to be const.
  832. const_iterator delpos(this, table + pos, table + num_buckets, false);
  833. clear_deleted(delpos);
  834. assert( num_deleted > 0);
  835. --num_deleted; // used to be, now it isn't
  836. } else {
  837. ++num_elements; // replacing an empty bucket
  838. }
  839. set_value(&table[pos], obj);
  840. return iterator(this, table + pos, table + num_buckets, false);
  841. }
  842. // If you know *this is big enough to hold obj, use this routine
  843. std::pair<iterator, bool> insert_noresize(const_reference obj) {
  844. // First, double-check we're not inserting delkey or emptyval
  845. assert((!settings.use_empty() || !equals(get_key(obj),
  846. get_key(val_info.emptyval)))
  847. && "Inserting the empty key");
  848. assert((!settings.use_deleted() || !equals(get_key(obj), key_info.delkey))
  849. && "Inserting the deleted key");
  850. const std::pair<size_type,size_type> pos = find_position(get_key(obj));
  851. if ( pos.first != ILLEGAL_BUCKET) { // object was already there
  852. return std::pair<iterator,bool>(iterator(this, table + pos.first,
  853. table + num_buckets, false),
  854. false); // false: we didn't insert
  855. } else { // pos.second says where to put it
  856. return std::pair<iterator,bool>(insert_at(obj, pos.second), true);
  857. }
  858. }
  859. // Specializations of insert(it, it) depending on the power of the iterator:
  860. // (1) Iterator supports operator-, resize before inserting
  861. template <class ForwardIterator>
  862. void insert(ForwardIterator f, ForwardIterator l, std::forward_iterator_tag) {
  863. size_t dist = std::distance(f, l);
  864. if (dist >= (std::numeric_limits<size_type>::max)()) {
  865. assert(false && "insert-range overflow");
  866. exit(-1);
  867. }
  868. resize_delta(static_cast<size_type>(dist));
  869. for ( ; dist > 0; --dist, ++f) {
  870. insert_noresize(*f);
  871. }
  872. }
  873. // (2) Arbitrary iterator, can't tell how much to resize
  874. template <class InputIterator>
  875. void insert(InputIterator f, InputIterator l, std::input_iterator_tag) {
  876. for ( ; f != l; ++f)
  877. insert(*f);
  878. }
  879. public:
  880. // This is the normal insert routine, used by the outside world
  881. std::pair<iterator, bool> insert(const_reference obj) {
  882. resize_delta(1); // adding an object, grow if need be
  883. return insert_noresize(obj);
  884. }
  885. // When inserting a lot at a time, we specialize on the type of iterator
  886. template <class InputIterator>
  887. void insert(InputIterator f, InputIterator l) {
  888. // specializes on iterator type
  889. insert(f, l,
  890. typename std::iterator_traits<InputIterator>::iterator_category());
  891. }
  892. // DefaultValue is a functor that takes a key and returns a value_type
  893. // representing the default value to be inserted if none is found.
  894. template <class DefaultValue>
  895. value_type& find_or_insert(const key_type& key) {
  896. // First, double-check we're not inserting emptykey or delkey
  897. assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
  898. && "Inserting the empty key");
  899. assert((!settings.use_deleted() || !equals(key, key_info.delkey))
  900. && "Inserting the deleted key");
  901. const std::pair<size_type,size_type> pos = find_position(key);
  902. DefaultValue default_value;
  903. if ( pos.first != ILLEGAL_BUCKET) { // object was already there
  904. return table[pos.first];
  905. } else if (resize_delta(1)) { // needed to rehash to make room
  906. // Since we resized, we can't use pos, so recalculate where to insert.
  907. return *insert_noresize(default_value(key)).first;
  908. } else { // no need to rehash, insert right here
  909. return *insert_at(default_value(key), pos.second);
  910. }
  911. }
  912. // DELETION ROUTINES
  913. size_type erase(const key_type& key) {
  914. // First, double-check we're not trying to erase delkey or emptyval.
  915. assert((!settings.use_empty() || !equals(key, get_key(val_info.emptyval)))
  916. && "Erasing the empty key");
  917. assert((!settings.use_deleted() || !equals(key, key_info.delkey))
  918. && "Erasing the deleted key");
  919. const_iterator pos = find(key); // shrug: shouldn't need to be const
  920. if ( pos != end() ) {
  921. assert(!test_deleted(pos)); // or find() shouldn't have returned it
  922. set_deleted(pos);
  923. ++num_deleted;
  924. settings.set_consider_shrink(true); // will think about shrink after next insert
  925. return 1; // because we deleted one thing
  926. } else {
  927. return 0; // because we deleted nothing
  928. }
  929. }
  930. // We return the iterator past the deleted item.
  931. void erase(iterator pos) {
  932. if ( pos == end() ) return; // sanity check
  933. if ( set_deleted(pos) ) { // true if object has been newly deleted
  934. ++num_deleted;
  935. settings.set_consider_shrink(true); // will think about shrink after next insert
  936. }
  937. }
  938. void erase(iterator f, iterator l) {
  939. for ( ; f != l; ++f) {
  940. if ( set_deleted(f) ) // should always be true
  941. ++num_deleted;
  942. }
  943. settings.set_consider_shrink(true); // will think about shrink after next insert
  944. }
  945. // We allow you to erase a const_iterator just like we allow you to
  946. // erase an iterator. This is in parallel to 'delete': you can delete
  947. // a const pointer just like a non-const pointer. The logic is that
  948. // you can't use the object after it's erased anyway, so it doesn't matter
  949. // if it's const or not.
  950. void erase(const_iterator pos) {
  951. if ( pos == end() ) return; // sanity check
  952. if ( set_deleted(pos) ) { // true if object has been newly deleted
  953. ++num_deleted;
  954. settings.set_consider_shrink(true); // will think about shrink after next insert
  955. }
  956. }
  957. void erase(const_iterator f, const_iterator l) {
  958. for ( ; f != l; ++f) {
  959. if ( set_deleted(f) ) // should always be true
  960. ++num_deleted;
  961. }
  962. settings.set_consider_shrink(true); // will think about shrink after next insert
  963. }
  964. // COMPARISON
  965. bool operator==(const dense_hashtable& ht) const {
  966. if (size() != ht.size()) {
  967. return false;
  968. } else if (this == &ht) {
  969. return true;
  970. } else {
  971. // Iterate through the elements in "this" and see if the
  972. // corresponding element is in ht
  973. for ( const_iterator it = begin(); it != end(); ++it ) {
  974. const_iterator it2 = ht.find(get_key(*it));
  975. if ((it2 == ht.end()) || (*it != *it2)) {
  976. return false;
  977. }
  978. }
  979. return true;
  980. }
  981. }
  982. bool operator!=(const dense_hashtable& ht) const {
  983. return !(*this == ht);
  984. }
  985. // I/O
  986. // We support reading and writing hashtables to disk. Alas, since
  987. // I don't know how to write a hasher or key_equal, you have to make
  988. // sure everything but the table is the same. We compact before writing.
  989. private:
  990. // Every time the disk format changes, this should probably change too
  991. typedef unsigned long MagicNumberType;
  992. static const MagicNumberType MAGIC_NUMBER = 0x13578642;
  993. public:
  994. // I/O -- this is an add-on for writing hash table to disk
  995. //
  996. // INPUT and OUTPUT must be either a FILE, *or* a C++ stream
  997. // (istream, ostream, etc) *or* a class providing
  998. // Read(void*, size_t) and Write(const void*, size_t)
  999. // (respectively), which writes a buffer into a stream
  1000. // (which the INPUT/OUTPUT instance presumably owns).
  1001. typedef sparsehash_internal::pod_serializer<value_type> NopointerSerializer;
  1002. // ValueSerializer: a functor. operator()(OUTPUT*, const value_type&)
  1003. template <typename ValueSerializer, typename OUTPUT>
  1004. bool serialize(ValueSerializer serializer, OUTPUT *fp) {
  1005. squash_deleted(); // so we don't have to worry about delkey
  1006. if ( !sparsehash_internal::write_bigendian_number(fp, MAGIC_NUMBER, 4) )
  1007. return false;
  1008. if ( !sparsehash_internal::write_bigendian_number(fp, num_buckets, 8) )
  1009. return false;
  1010. if ( !sparsehash_internal::write_bigendian_number(fp, num_elements, 8) )
  1011. return false;
  1012. // Now write a bitmap of non-empty buckets.
  1013. for ( size_type i = 0; i < num_buckets; i += 8 ) {
  1014. unsigned char bits = 0;
  1015. for ( int bit = 0; bit < 8; ++bit ) {
  1016. if ( i + bit < num_buckets && !test_empty(i + bit) )
  1017. bits |= (1 << bit);
  1018. }
  1019. if ( !sparsehash_internal::write_data(fp, &bits, sizeof(bits)) )
  1020. return false;
  1021. for ( int bit = 0; bit < 8; ++bit ) {
  1022. if ( bits & (1 << bit) ) {
  1023. if ( !serializer(fp, table[i + bit]) ) return false;
  1024. }
  1025. }
  1026. }
  1027. return true;
  1028. }
  1029. // INPUT: anything we've written an overload of read_data() for.
  1030. // ValueSerializer: a functor. operator()(INPUT*, value_type*)
  1031. template <typename ValueSerializer, typename INPUT>
  1032. bool unserialize(ValueSerializer serializer, INPUT *fp) {
  1033. assert(settings.use_empty() && "empty_key not set for read");
  1034. clear(); // just to be consistent
  1035. MagicNumberType magic_read;
  1036. if ( !sparsehash_internal::read_bigendian_number(fp, &magic_read, 4) )
  1037. return false;
  1038. if ( magic_read != MAGIC_NUMBER ) {
  1039. return false;
  1040. }
  1041. size_type new_num_buckets;
  1042. if ( !sparsehash_internal::read_bigendian_number(fp, &new_num_buckets, 8) )
  1043. return false;
  1044. clear_to_size(new_num_buckets);
  1045. if ( !sparsehash_internal::read_bigendian_number(fp, &num_elements, 8) )
  1046. return false;
  1047. // Read the bitmap of non-empty buckets.
  1048. for (size_type i = 0; i < num_buckets; i += 8) {
  1049. unsigned char bits;
  1050. if ( !sparsehash_internal::read_data(fp, &bits, sizeof(bits)) )
  1051. return false;
  1052. for ( int bit = 0; bit < 8; ++bit ) {
  1053. if ( i + bit < num_buckets && (bits & (1 << bit)) ) { // not empty
  1054. if ( !serializer(fp, &table[i + bit]) ) return false;
  1055. }
  1056. }
  1057. }
  1058. return true;
  1059. }
  1060. private:
  1061. template <class A>
  1062. class alloc_impl : public A {
  1063. public:
  1064. typedef typename A::pointer pointer;
  1065. typedef typename A::size_type size_type;
  1066. // Convert a normal allocator to one that has realloc_or_die()
  1067. alloc_impl(const A& a) : A(a) { }
  1068. // realloc_or_die should only be used when using the default
  1069. // allocator (libc_allocator_with_realloc).
  1070. pointer realloc_or_die(pointer /*ptr*/, size_type /*n*/) {
  1071. fprintf(stderr, "realloc_or_die is only supported for "
  1072. "libc_allocator_with_realloc\n");
  1073. exit(1);
  1074. return NULL;
  1075. }
  1076. };
  1077. // A template specialization of alloc_impl for
  1078. // libc_allocator_with_realloc that can handle realloc_or_die.
  1079. template <class A>
  1080. class alloc_impl<libc_allocator_with_realloc<A> >
  1081. : public libc_allocator_with_realloc<A> {
  1082. public:
  1083. typedef typename libc_allocator_with_realloc<A>::pointer pointer;
  1084. typedef typename libc_allocator_with_realloc<A>::size_type size_type;
  1085. alloc_impl(const libc_allocator_with_realloc<A>& a)
  1086. : libc_allocator_with_realloc<A>(a) { }
  1087. pointer realloc_or_die(pointer ptr, size_type n) {
  1088. pointer retval = this->reallocate(ptr, n);
  1089. if (retval == NULL) {
  1090. fprintf(stderr,
  1091. "sparsehash: FATAL ERROR: failed to reallocate "
  1092. "%lu elements for ptr %p",
  1093. static_cast<unsigned long>(n), static_cast<void*>(ptr));
  1094. exit(1);
  1095. }
  1096. return retval;
  1097. }
  1098. };
  1099. // Package allocator with emptyval to eliminate memory needed for
  1100. // the zero-size allocator.
  1101. // If new fields are added to this class, we should add them to
  1102. // operator= and swap.
  1103. class ValInfo : public alloc_impl<value_alloc_type> {
  1104. public:
  1105. typedef typename alloc_impl<value_alloc_type>::value_type value_type;
  1106. ValInfo(const alloc_impl<value_alloc_type>& a)
  1107. : alloc_impl<value_alloc_type>(a), emptyval() { }
  1108. ValInfo(const ValInfo& v)
  1109. : alloc_impl<value_alloc_type>(v), emptyval(v.emptyval) { }
  1110. value_type emptyval; // which key marks unused entries
  1111. };
  1112. // Package functors with another class to eliminate memory needed for
  1113. // zero-size functors. Since ExtractKey and hasher's operator() might
  1114. // have the same function signature, they must be packaged in
  1115. // different classes.
  1116. struct Settings :
  1117. sparsehash_internal::sh_hashtable_settings<key_type, hasher,
  1118. size_type, HT_MIN_BUCKETS> {
  1119. explicit Settings(const hasher& hf)
  1120. : sparsehash_internal::sh_hashtable_settings<key_type, hasher,
  1121. size_type, HT_MIN_BUCKETS>(
  1122. hf, HT_OCCUPANCY_PCT / 100.0f, HT_EMPTY_PCT / 100.0f) {}
  1123. };
  1124. // Packages ExtractKey and SetKey functors.
  1125. class KeyInfo : public ExtractKey, public SetKey, public EqualKey {
  1126. public:
  1127. KeyInfo(const ExtractKey& ek, const SetKey& sk, const EqualKey& eq)
  1128. : ExtractKey(ek),
  1129. SetKey(sk),
  1130. EqualKey(eq) {
  1131. }
  1132. // We want to return the exact same type as ExtractKey: Key or const Key&
  1133. typename ExtractKey::result_type get_key(const_reference v) const {
  1134. return ExtractKey::operator()(v);
  1135. }
  1136. void set_key(pointer v, const key_type& k) const {
  1137. SetKey::operator()(v, k);
  1138. }
  1139. bool equals(const key_type& a, const key_type& b) const {
  1140. return EqualKey::operator()(a, b);
  1141. }
  1142. // Which key marks deleted entries.
  1143. // TODO(csilvers): make a pointer, and get rid of use_deleted (benchmark!)
  1144. typename base::remove_const<key_type>::type delkey;
  1145. };
  1146. // Utility functions to access the templated operators
  1147. size_type hash(const key_type& v) const {
  1148. return settings.hash(v);
  1149. }
  1150. bool equals(const key_type& a, const key_type& b) const {
  1151. return key_info.equals(a, b);
  1152. }
  1153. typename ExtractKey::result_type get_key(const_reference v) const {
  1154. return key_info.get_key(v);
  1155. }
  1156. void set_key(pointer v, const key_type& k) const {
  1157. key_info.set_key(v, k);
  1158. }
  1159. private:
  1160. // Actual data
  1161. Settings settings;
  1162. KeyInfo key_info;
  1163. size_type num_deleted; // how many occupied buckets are marked deleted
  1164. size_type num_elements;
  1165. size_type num_buckets;
  1166. ValInfo val_info; // holds emptyval, and also the allocator
  1167. pointer table;
  1168. };
  1169. // We need a global swap as well
  1170. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1171. inline void swap(dense_hashtable<V,K,HF,ExK,SetK,EqK,A> &x,
  1172. dense_hashtable<V,K,HF,ExK,SetK,EqK,A> &y) {
  1173. x.swap(y);
  1174. }
  1175. #undef JUMP_
  1176. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1177. const typename dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::size_type
  1178. dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::ILLEGAL_BUCKET;
  1179. // How full we let the table get before we resize. Knuth says .8 is
  1180. // good -- higher causes us to probe too much, though saves memory.
  1181. // However, we go with .5, getting better performance at the cost of
  1182. // more space (a trade-off densehashtable explicitly chooses to make).
  1183. // Feel free to play around with different values, though, via
  1184. // max_load_factor() and/or set_resizing_parameters().
  1185. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1186. const int dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_OCCUPANCY_PCT = 50;
  1187. // How empty we let the table get before we resize lower.
  1188. // It should be less than OCCUPANCY_PCT / 2 or we thrash resizing.
  1189. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1190. const int dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_EMPTY_PCT
  1191. = static_cast<int>(0.4 *
  1192. dense_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_OCCUPANCY_PCT);
  1193. _END_GOOGLE_NAMESPACE_
  1194. #endif /* _DENSEHASHTABLE_H_ */