PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/HpsFramework/google/sparsehash/sparsehashtable.h

#
C++ Header | 1187 lines | 734 code | 127 blank | 326 comment | 151 complexity | 0c9b3b3c619a814f69e2aa9c0f0063fb MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. // Author: Craig Silverstein
  31. //
  32. // A sparse hashtable is a particular implementation of
  33. // a hashtable: one that is meant to minimize memory use.
  34. // It does this by using a *sparse table* (cf sparsetable.h),
  35. // which uses between 1 and 2 bits to store empty buckets
  36. // (we may need another bit for hashtables that support deletion).
  37. //
  38. // When empty buckets are so cheap, an appealing hashtable
  39. // implementation is internal probing, in which the hashtable
  40. // is a single table, and collisions are resolved by trying
  41. // to insert again in another bucket. The most cache-efficient
  42. // internal probing schemes are linear probing (which suffers,
  43. // alas, from clumping) and quadratic probing, which is what
  44. // we implement by default.
  45. //
  46. // Deleted buckets are a bit of a pain. We have to somehow mark
  47. // deleted buckets (the probing must distinguish them from empty
  48. // buckets). The most principled way is to have another bitmap,
  49. // but that's annoying and takes up space. Instead we let the
  50. // user specify an "impossible" key. We set deleted buckets
  51. // to have the impossible key.
  52. //
  53. // Note it is possible to change the value of the delete key
  54. // on the fly; you can even remove it, though after that point
  55. // the hashtable is insert_only until you set it again.
  56. //
  57. // You probably shouldn't use this code directly. Use
  58. // <google/sparse_hash_table> or <google/sparse_hash_set> instead.
  59. //
  60. // You can modify the following, below:
  61. // HT_OCCUPANCY_PCT -- how full before we double size
  62. // HT_EMPTY_PCT -- how empty before we halve size
  63. // HT_MIN_BUCKETS -- smallest bucket size
  64. // HT_DEFAULT_STARTING_BUCKETS -- default bucket size at construct-time
  65. //
  66. // You can also change enlarge_factor (which defaults to
  67. // HT_OCCUPANCY_PCT), and shrink_factor (which defaults to
  68. // HT_EMPTY_PCT) with set_resizing_parameters().
  69. //
  70. // How to decide what values to use?
  71. // shrink_factor's default of .4 * OCCUPANCY_PCT, is probably good.
  72. // HT_MIN_BUCKETS is probably unnecessary since you can specify
  73. // (indirectly) the starting number of buckets at construct-time.
  74. // For enlarge_factor, you can use this chart to try to trade-off
  75. // expected lookup time to the space taken up. By default, this
  76. // code uses quadratic probing, though you can change it to linear
  77. // via _JUMP below if you really want to.
  78. //
  79. // From http://www.augustana.ca/~mohrj/courses/1999.fall/csc210/lecture_notes/hashing.html
  80. // NUMBER OF PROBES / LOOKUP Successful Unsuccessful
  81. // Quadratic collision resolution 1 - ln(1-L) - L/2 1/(1-L) - L - ln(1-L)
  82. // Linear collision resolution [1+1/(1-L)]/2 [1+1/(1-L)2]/2
  83. //
  84. // -- enlarge_factor -- 0.10 0.50 0.60 0.75 0.80 0.90 0.99
  85. // QUADRATIC COLLISION RES.
  86. // probes/successful lookup 1.05 1.44 1.62 2.01 2.21 2.85 5.11
  87. // probes/unsuccessful lookup 1.11 2.19 2.82 4.64 5.81 11.4 103.6
  88. // LINEAR COLLISION RES.
  89. // probes/successful lookup 1.06 1.5 1.75 2.5 3.0 5.5 50.5
  90. // probes/unsuccessful lookup 1.12 2.5 3.6 8.5 13.0 50.0 5000.0
  91. //
  92. // The value type is required to be copy constructible and default
  93. // constructible, but it need not be (and commonly isn't) assignable.
  94. #ifndef _SPARSEHASHTABLE_H_
  95. #define _SPARSEHASHTABLE_H_
  96. #ifndef SPARSEHASH_STAT_UPDATE
  97. #define SPARSEHASH_STAT_UPDATE(x) ((void) 0)
  98. #endif
  99. // The probing method
  100. // Linear probing
  101. // #define JUMP_(key, num_probes) ( 1 )
  102. // Quadratic probing
  103. #define JUMP_(key, num_probes) ( num_probes )
  104. #include <google/sparsehash/sparseconfig.h>
  105. #include <assert.h>
  106. #include <algorithm> // For swap(), eg
  107. #include <stdexcept> // For length_error
  108. #include <iterator> // for facts about iterator tags
  109. #include <limits> // for numeric_limits<>
  110. #include <utility> // for pair<>
  111. #include <google/sparsehash/hashtable-common.h>
  112. #include <google/sparsetable> // Since that's basically what we are
  113. _START_GOOGLE_NAMESPACE_
  114. using STL_NAMESPACE::pair;
  115. // The smaller this is, the faster lookup is (because the group bitmap is
  116. // smaller) and the faster insert is, because there's less to move.
  117. // On the other hand, there are more groups. Since group::size_type is
  118. // a short, this number should be of the form 32*x + 16 to avoid waste.
  119. static const u_int16_t DEFAULT_GROUP_SIZE = 48; // fits in 1.5 words
  120. // Hashtable class, used to implement the hashed associative containers
  121. // hash_set and hash_map.
  122. //
  123. // Value: what is stored in the table (each bucket is a Value).
  124. // Key: something in a 1-to-1 correspondence to a Value, that can be used
  125. // to search for a Value in the table (find() takes a Key).
  126. // HashFcn: Takes a Key and returns an integer, the more unique the better.
  127. // ExtractKey: given a Value, returns the unique Key associated with it.
  128. // SetKey: given a Value* and a Key, modifies the value such that
  129. // ExtractKey(value) == key. We guarantee this is only called
  130. // with key == deleted_key.
  131. // EqualKey: Given two Keys, says whether they are the same (that is,
  132. // if they are both associated with the same Value).
  133. // Alloc: STL allocator to use to allocate memory.
  134. template <class Value, class Key, class HashFcn,
  135. class ExtractKey, class SetKey, class EqualKey, class Alloc>
  136. class sparse_hashtable;
  137. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  138. struct sparse_hashtable_iterator;
  139. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  140. struct sparse_hashtable_const_iterator;
  141. // As far as iterating, we're basically just a sparsetable
  142. // that skips over deleted elements.
  143. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  144. struct sparse_hashtable_iterator {
  145. private:
  146. typedef typename A::template rebind<V>::other value_alloc_type;
  147. public:
  148. typedef sparse_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
  149. typedef sparse_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
  150. typedef typename sparsetable<V,DEFAULT_GROUP_SIZE,A>::nonempty_iterator
  151. st_iterator;
  152. typedef STL_NAMESPACE::forward_iterator_tag iterator_category;
  153. typedef V value_type;
  154. typedef typename value_alloc_type::difference_type difference_type;
  155. typedef typename value_alloc_type::size_type size_type;
  156. typedef typename value_alloc_type::reference reference;
  157. typedef typename value_alloc_type::pointer pointer;
  158. // "Real" constructor and default constructor
  159. sparse_hashtable_iterator(const sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
  160. st_iterator it, st_iterator it_end)
  161. : ht(h), pos(it), end(it_end) { advance_past_deleted(); }
  162. sparse_hashtable_iterator() { } // not ever used internally
  163. // The default destructor is fine; we don't define one
  164. // The default operator= is fine; we don't define one
  165. // Happy dereferencer
  166. reference operator*() const { return *pos; }
  167. pointer operator->() const { return &(operator*()); }
  168. // Arithmetic. The only hard part is making sure that
  169. // we're not on a marked-deleted array element
  170. void advance_past_deleted() {
  171. while ( pos != end && ht->test_deleted(*this) )
  172. ++pos;
  173. }
  174. iterator& operator++() {
  175. assert(pos != end); ++pos; advance_past_deleted(); return *this;
  176. }
  177. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  178. // Comparison.
  179. bool operator==(const iterator& it) const { return pos == it.pos; }
  180. bool operator!=(const iterator& it) const { return pos != it.pos; }
  181. // The actual data
  182. const sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
  183. st_iterator pos, end;
  184. };
  185. // Now do it all again, but with const-ness!
  186. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  187. struct sparse_hashtable_const_iterator {
  188. private:
  189. typedef typename A::template rebind<V>::other value_alloc_type;
  190. public:
  191. typedef sparse_hashtable_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
  192. typedef sparse_hashtable_const_iterator<V,K,HF,ExK,SetK,EqK,A> const_iterator;
  193. typedef typename sparsetable<V,DEFAULT_GROUP_SIZE,A>::const_nonempty_iterator
  194. st_iterator;
  195. typedef STL_NAMESPACE::forward_iterator_tag iterator_category;
  196. typedef V value_type;
  197. typedef typename value_alloc_type::difference_type difference_type;
  198. typedef typename value_alloc_type::size_type size_type;
  199. typedef typename value_alloc_type::const_reference reference;
  200. typedef typename value_alloc_type::const_pointer pointer;
  201. // "Real" constructor and default constructor
  202. sparse_hashtable_const_iterator(const sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
  203. st_iterator it, st_iterator it_end)
  204. : ht(h), pos(it), end(it_end) { advance_past_deleted(); }
  205. // This lets us convert regular iterators to const iterators
  206. sparse_hashtable_const_iterator() { } // never used internally
  207. sparse_hashtable_const_iterator(const iterator &it)
  208. : ht(it.ht), pos(it.pos), end(it.end) { }
  209. // The default destructor is fine; we don't define one
  210. // The default operator= is fine; we don't define one
  211. // Happy dereferencer
  212. reference operator*() const { return *pos; }
  213. pointer operator->() const { return &(operator*()); }
  214. // Arithmetic. The only hard part is making sure that
  215. // we're not on a marked-deleted array element
  216. void advance_past_deleted() {
  217. while ( pos != end && ht->test_deleted(*this) )
  218. ++pos;
  219. }
  220. const_iterator& operator++() {
  221. assert(pos != end); ++pos; advance_past_deleted(); return *this;
  222. }
  223. const_iterator operator++(int) { const_iterator tmp(*this); ++*this; return tmp; }
  224. // Comparison.
  225. bool operator==(const const_iterator& it) const { return pos == it.pos; }
  226. bool operator!=(const const_iterator& it) const { return pos != it.pos; }
  227. // The actual data
  228. const sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
  229. st_iterator pos, end;
  230. };
  231. // And once again, but this time freeing up memory as we iterate
  232. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  233. struct sparse_hashtable_destructive_iterator {
  234. private:
  235. typedef typename A::template rebind<V>::other value_alloc_type;
  236. public:
  237. typedef sparse_hashtable_destructive_iterator<V,K,HF,ExK,SetK,EqK,A> iterator;
  238. typedef typename sparsetable<V,DEFAULT_GROUP_SIZE,A>::destructive_iterator
  239. st_iterator;
  240. typedef STL_NAMESPACE::forward_iterator_tag iterator_category;
  241. typedef V value_type;
  242. typedef typename value_alloc_type::difference_type difference_type;
  243. typedef typename value_alloc_type::size_type size_type;
  244. typedef typename value_alloc_type::reference reference;
  245. typedef typename value_alloc_type::pointer pointer;
  246. // "Real" constructor and default constructor
  247. sparse_hashtable_destructive_iterator(const
  248. sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *h,
  249. st_iterator it, st_iterator it_end)
  250. : ht(h), pos(it), end(it_end) { advance_past_deleted(); }
  251. sparse_hashtable_destructive_iterator() { } // never used internally
  252. // The default destructor is fine; we don't define one
  253. // The default operator= is fine; we don't define one
  254. // Happy dereferencer
  255. reference operator*() const { return *pos; }
  256. pointer operator->() const { return &(operator*()); }
  257. // Arithmetic. The only hard part is making sure that
  258. // we're not on a marked-deleted array element
  259. void advance_past_deleted() {
  260. while ( pos != end && ht->test_deleted(*this) )
  261. ++pos;
  262. }
  263. iterator& operator++() {
  264. assert(pos != end); ++pos; advance_past_deleted(); return *this;
  265. }
  266. iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }
  267. // Comparison.
  268. bool operator==(const iterator& it) const { return pos == it.pos; }
  269. bool operator!=(const iterator& it) const { return pos != it.pos; }
  270. // The actual data
  271. const sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> *ht;
  272. st_iterator pos, end;
  273. };
  274. template <class Value, class Key, class HashFcn,
  275. class ExtractKey, class SetKey, class EqualKey, class Alloc>
  276. class sparse_hashtable {
  277. private:
  278. typedef typename Alloc::template rebind<Value>::other value_alloc_type;
  279. public:
  280. typedef Key key_type;
  281. typedef Value value_type;
  282. typedef HashFcn hasher;
  283. typedef EqualKey key_equal;
  284. typedef Alloc allocator_type;
  285. typedef typename value_alloc_type::size_type size_type;
  286. typedef typename value_alloc_type::difference_type difference_type;
  287. typedef typename value_alloc_type::reference reference;
  288. typedef typename value_alloc_type::const_reference const_reference;
  289. typedef typename value_alloc_type::pointer pointer;
  290. typedef typename value_alloc_type::const_pointer const_pointer;
  291. typedef sparse_hashtable_iterator<Value, Key, HashFcn, ExtractKey,
  292. SetKey, EqualKey, Alloc>
  293. iterator;
  294. typedef sparse_hashtable_const_iterator<Value, Key, HashFcn, ExtractKey,
  295. SetKey, EqualKey, Alloc>
  296. const_iterator;
  297. typedef sparse_hashtable_destructive_iterator<Value, Key, HashFcn, ExtractKey,
  298. SetKey, EqualKey, Alloc>
  299. destructive_iterator;
  300. // These come from tr1. For us they're the same as regular iterators.
  301. typedef iterator local_iterator;
  302. typedef const_iterator const_local_iterator;
  303. // How full we let the table get before we resize, by default.
  304. // Knuth says .8 is good -- higher causes us to probe too much,
  305. // though it saves memory.
  306. static const int HT_OCCUPANCY_PCT; // = 80 (out of 100);
  307. // How empty we let the table get before we resize lower, by default.
  308. // (0.0 means never resize lower.)
  309. // It should be less than OCCUPANCY_PCT / 2 or we thrash resizing
  310. static const int HT_EMPTY_PCT; // = 0.4 * HT_OCCUPANCY_PCT;
  311. // Minimum size we're willing to let hashtables be.
  312. // Must be a power of two, and at least 4.
  313. // Note, however, that for a given hashtable, the initial size is a
  314. // function of the first constructor arg, and may be >HT_MIN_BUCKETS.
  315. static const size_type HT_MIN_BUCKETS = 4;
  316. // By default, if you don't specify a hashtable size at
  317. // construction-time, we use this size. Must be a power of two, and
  318. // at least HT_MIN_BUCKETS.
  319. static const size_type HT_DEFAULT_STARTING_BUCKETS = 32;
  320. // ITERATOR FUNCTIONS
  321. iterator begin() { return iterator(this, table.nonempty_begin(),
  322. table.nonempty_end()); }
  323. iterator end() { return iterator(this, table.nonempty_end(),
  324. table.nonempty_end()); }
  325. const_iterator begin() const { return const_iterator(this,
  326. table.nonempty_begin(),
  327. table.nonempty_end()); }
  328. const_iterator end() const { return const_iterator(this,
  329. table.nonempty_end(),
  330. table.nonempty_end()); }
  331. // These come from tr1 unordered_map. They iterate over 'bucket' n.
  332. // For sparsehashtable, we could consider each 'group' to be a bucket,
  333. // I guess, but I don't really see the point. We'll just consider
  334. // bucket n to be the n-th element of the sparsetable, if it's occupied,
  335. // or some empty element, otherwise.
  336. local_iterator begin(size_type i) {
  337. if (table.test(i))
  338. return local_iterator(this, table.get_iter(i), table.nonempty_end());
  339. else
  340. return local_iterator(this, table.nonempty_end(), table.nonempty_end());
  341. }
  342. local_iterator end(size_type i) {
  343. local_iterator it = begin(i);
  344. if (table.test(i) && !test_deleted(i))
  345. ++it;
  346. return it;
  347. }
  348. const_local_iterator begin(size_type i) const {
  349. if (table.test(i))
  350. return const_local_iterator(this, table.get_iter(i),
  351. table.nonempty_end());
  352. else
  353. return const_local_iterator(this, table.nonempty_end(),
  354. table.nonempty_end());
  355. }
  356. const_local_iterator end(size_type i) const {
  357. const_local_iterator it = begin(i);
  358. if (table.test(i) && !test_deleted(i))
  359. ++it;
  360. return it;
  361. }
  362. // This is used when resizing
  363. destructive_iterator destructive_begin() {
  364. return destructive_iterator(this, table.destructive_begin(),
  365. table.destructive_end());
  366. }
  367. destructive_iterator destructive_end() {
  368. return destructive_iterator(this, table.destructive_end(),
  369. table.destructive_end());
  370. }
  371. // ACCESSOR FUNCTIONS for the things we templatize on, basically
  372. hasher hash_funct() const { return settings; }
  373. key_equal key_eq() const { return key_info; }
  374. allocator_type get_allocator() const { return table.get_allocator(); }
  375. // Accessor function for statistics gathering.
  376. int num_table_copies() const { return settings.num_ht_copies(); }
  377. private:
  378. // We need to copy values when we set the special marker for deleted
  379. // elements, but, annoyingly, we can't just use the copy assignment
  380. // operator because value_type might not be assignable (it's often
  381. // pair<const X, Y>). We use explicit destructor invocation and
  382. // placement new to get around this. Arg.
  383. void set_value(pointer dst, const_reference src) {
  384. dst->~value_type(); // delete the old value, if any
  385. new(dst) value_type(src);
  386. }
  387. // This is used as a tag for the copy constructor, saying to destroy its
  388. // arg We have two ways of destructively copying: with potentially growing
  389. // the hashtable as we copy, and without. To make sure the outside world
  390. // can't do a destructive copy, we make the typename private.
  391. enum MoveDontCopyT {MoveDontCopy, MoveDontGrow};
  392. // DELETE HELPER FUNCTIONS
  393. // This lets the user describe a key that will indicate deleted
  394. // table entries. This key should be an "impossible" entry --
  395. // if you try to insert it for real, you won't be able to retrieve it!
  396. // (NB: while you pass in an entire value, only the key part is looked
  397. // at. This is just because I don't know how to assign just a key.)
  398. private:
  399. void squash_deleted() { // gets rid of any deleted entries we have
  400. if ( num_deleted ) { // get rid of deleted before writing
  401. sparse_hashtable tmp(MoveDontGrow, *this);
  402. swap(tmp); // now we are tmp
  403. }
  404. assert(num_deleted == 0);
  405. }
  406. bool test_deleted_key(const key_type& key) const {
  407. // The num_deleted test is crucial for read(): after read(), the ht values
  408. // are garbage, and we don't want to think some of them are deleted.
  409. // Invariant: !use_deleted implies num_deleted is 0.
  410. assert(settings.use_deleted() || num_deleted == 0);
  411. return num_deleted > 0 && equals(key_info.delkey, key);
  412. }
  413. public:
  414. void set_deleted_key(const key_type &key) {
  415. // It's only safe to change what "deleted" means if we purge deleted guys
  416. squash_deleted();
  417. settings.set_use_deleted(true);
  418. key_info.delkey = key;
  419. }
  420. void clear_deleted_key() {
  421. squash_deleted();
  422. settings.set_use_deleted(false);
  423. }
  424. key_type deleted_key() const {
  425. assert(settings.use_deleted()
  426. && "Must set deleted key before calling deleted_key");
  427. return key_info.delkey;
  428. }
  429. // These are public so the iterators can use them
  430. // True if the item at position bucknum is "deleted" marker
  431. bool test_deleted(size_type bucknum) const {
  432. if (num_deleted == 0 || !table.test(bucknum)) return false;
  433. return test_deleted_key(get_key(table.unsafe_get(bucknum)));
  434. }
  435. bool test_deleted(const iterator &it) const {
  436. if (!settings.use_deleted()) return false;
  437. return test_deleted_key(get_key(*it));
  438. }
  439. bool test_deleted(const const_iterator &it) const {
  440. if (!settings.use_deleted()) return false;
  441. return test_deleted_key(get_key(*it));
  442. }
  443. bool test_deleted(const destructive_iterator &it) const {
  444. if (!settings.use_deleted()) return false;
  445. return test_deleted_key(get_key(*it));
  446. }
  447. private:
  448. // Set it so test_deleted is true. true if object didn't used to be deleted.
  449. // TODO(csilvers): make these private (also in densehashtable.h)
  450. bool set_deleted(iterator &it) {
  451. assert(settings.use_deleted());
  452. bool retval = !test_deleted(it);
  453. // &* converts from iterator to value-type.
  454. set_key(&(*it), key_info.delkey);
  455. return retval;
  456. }
  457. // Set it so test_deleted is false. true if object used to be deleted.
  458. bool clear_deleted(iterator &it) {
  459. assert(settings.use_deleted());
  460. // Happens automatically when we assign something else in its place.
  461. return test_deleted(it);
  462. }
  463. // We also allow to set/clear the deleted bit on a const iterator.
  464. // We allow a const_iterator for the same reason you can delete a
  465. // const pointer: it's convenient, and semantically you can't use
  466. // 'it' after it's been deleted anyway, so its const-ness doesn't
  467. // really matter.
  468. bool set_deleted(const_iterator &it) {
  469. assert(settings.use_deleted()); // bad if set_deleted_key() wasn't called
  470. bool retval = !test_deleted(it);
  471. set_key(const_cast<pointer>(&(*it)), key_info.delkey);
  472. return retval;
  473. }
  474. // Set it so test_deleted is false. true if object used to be deleted.
  475. bool clear_deleted(const_iterator &it) {
  476. assert(settings.use_deleted()); // bad if set_deleted_key() wasn't called
  477. return test_deleted(it);
  478. }
  479. // FUNCTIONS CONCERNING SIZE
  480. public:
  481. size_type size() const { return table.num_nonempty() - num_deleted; }
  482. size_type max_size() const { return table.max_size(); }
  483. bool empty() const { return size() == 0; }
  484. size_type bucket_count() const { return table.size(); }
  485. size_type max_bucket_count() const { return max_size(); }
  486. // These are tr1 methods. Their idea of 'bucket' doesn't map well to
  487. // what we do. We just say every bucket has 0 or 1 items in it.
  488. size_type bucket_size(size_type i) const {
  489. return begin(i) == end(i) ? 0 : 1;
  490. }
  491. private:
  492. // Because of the above, size_type(-1) is never legal; use it for errors
  493. static const size_type ILLEGAL_BUCKET = size_type(-1);
  494. // Used after a string of deletes. Returns true if we actually shrunk.
  495. // TODO(csilvers): take a delta so we can take into account inserts
  496. // done after shrinking. Maybe make part of the Settings class?
  497. bool maybe_shrink() {
  498. assert(table.num_nonempty() >= num_deleted);
  499. assert((bucket_count() & (bucket_count()-1)) == 0); // is a power of two
  500. assert(bucket_count() >= HT_MIN_BUCKETS);
  501. bool retval = false;
  502. // If you construct a hashtable with < HT_DEFAULT_STARTING_BUCKETS,
  503. // we'll never shrink until you get relatively big, and we'll never
  504. // shrink below HT_DEFAULT_STARTING_BUCKETS. Otherwise, something
  505. // like "dense_hash_set<int> x; x.insert(4); x.erase(4);" will
  506. // shrink us down to HT_MIN_BUCKETS buckets, which is too small.
  507. const size_type num_remain = table.num_nonempty() - num_deleted;
  508. const size_type shrink_threshold = settings.shrink_threshold();
  509. if (shrink_threshold > 0 && num_remain < shrink_threshold &&
  510. bucket_count() > HT_DEFAULT_STARTING_BUCKETS) {
  511. const float shrink_factor = settings.shrink_factor();
  512. size_type sz = bucket_count() / 2; // find how much we should shrink
  513. while (sz > HT_DEFAULT_STARTING_BUCKETS &&
  514. num_remain < static_cast<size_type>(sz * shrink_factor)) {
  515. sz /= 2; // stay a power of 2
  516. }
  517. sparse_hashtable tmp(MoveDontCopy, *this, sz);
  518. swap(tmp); // now we are tmp
  519. retval = true;
  520. }
  521. settings.set_consider_shrink(false); // because we just considered it
  522. return retval;
  523. }
  524. // We'll let you resize a hashtable -- though this makes us copy all!
  525. // When you resize, you say, "make it big enough for this many more elements"
  526. // Returns true if we actually resized, false if size was already ok.
  527. bool resize_delta(size_type delta) {
  528. bool did_resize = false;
  529. if ( settings.consider_shrink() ) { // see if lots of deletes happened
  530. if ( maybe_shrink() )
  531. did_resize = true;
  532. }
  533. if (table.num_nonempty() >=
  534. (STL_NAMESPACE::numeric_limits<size_type>::max)() - delta)
  535. throw std::length_error("resize overflow");
  536. if ( bucket_count() >= HT_MIN_BUCKETS &&
  537. (table.num_nonempty() + delta) <= settings.enlarge_threshold() )
  538. return did_resize; // we're ok as we are
  539. // Sometimes, we need to resize just to get rid of all the
  540. // "deleted" buckets that are clogging up the hashtable. So when
  541. // deciding whether to resize, count the deleted buckets (which
  542. // are currently taking up room). But later, when we decide what
  543. // size to resize to, *don't* count deleted buckets, since they
  544. // get discarded during the resize.
  545. const size_type needed_size =
  546. settings.min_buckets(table.num_nonempty() + delta, 0);
  547. if ( needed_size <= bucket_count() ) // we have enough buckets
  548. return did_resize;
  549. size_type resize_to =
  550. settings.min_buckets(table.num_nonempty() - num_deleted + delta,
  551. bucket_count());
  552. if (resize_to < needed_size && // may double resize_to
  553. resize_to < (STL_NAMESPACE::numeric_limits<size_type>::max)() / 2) {
  554. // This situation means that we have enough deleted elements,
  555. // that once we purge them, we won't actually have needed to
  556. // grow. But we may want to grow anyway: if we just purge one
  557. // element, say, we'll have to grow anyway next time we
  558. // insert. Might as well grow now, since we're already going
  559. // through the trouble of copying (in order to purge the
  560. // deleted elements).
  561. const size_type target =
  562. static_cast<size_type>(settings.shrink_size(resize_to*2));
  563. if (table.num_nonempty() - num_deleted + delta >= target) {
  564. // Good, we won't be below the shrink threshhold even if we double.
  565. resize_to *= 2;
  566. }
  567. }
  568. sparse_hashtable tmp(MoveDontCopy, *this, resize_to);
  569. swap(tmp); // now we are tmp
  570. return true;
  571. }
  572. // Used to actually do the rehashing when we grow/shrink a hashtable
  573. void copy_from(const sparse_hashtable &ht, size_type min_buckets_wanted) {
  574. clear(); // clear table, set num_deleted to 0
  575. // If we need to change the size of our table, do it now
  576. const size_type resize_to =
  577. settings.min_buckets(ht.size(), min_buckets_wanted);
  578. if ( resize_to > bucket_count() ) { // we don't have enough buckets
  579. table.resize(resize_to); // sets the number of buckets
  580. settings.reset_thresholds(bucket_count());
  581. }
  582. // We use a normal iterator to get non-deleted bcks from ht
  583. // We could use insert() here, but since we know there are
  584. // no duplicates and no deleted items, we can be more efficient
  585. assert((bucket_count() & (bucket_count()-1)) == 0); // a power of two
  586. for ( const_iterator it = ht.begin(); it != ht.end(); ++it ) {
  587. size_type num_probes = 0; // how many times we've probed
  588. size_type bucknum;
  589. const size_type bucket_count_minus_one = bucket_count() - 1;
  590. for (bucknum = hash(get_key(*it)) & bucket_count_minus_one;
  591. table.test(bucknum); // not empty
  592. bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one) {
  593. ++num_probes;
  594. assert(num_probes < bucket_count()
  595. && "Hashtable is full: an error in key_equal<> or hash<>");
  596. }
  597. table.set(bucknum, *it); // copies the value to here
  598. }
  599. settings.inc_num_ht_copies();
  600. }
  601. // Implementation is like copy_from, but it destroys the table of the
  602. // "from" guy by freeing sparsetable memory as we iterate. This is
  603. // useful in resizing, since we're throwing away the "from" guy anyway.
  604. void move_from(MoveDontCopyT mover, sparse_hashtable &ht,
  605. size_type min_buckets_wanted) {
  606. clear(); // clear table, set num_deleted to 0
  607. // If we need to change the size of our table, do it now
  608. size_type resize_to;
  609. if ( mover == MoveDontGrow )
  610. resize_to = ht.bucket_count(); // keep same size as old ht
  611. else // MoveDontCopy
  612. resize_to = settings.min_buckets(ht.size(), min_buckets_wanted);
  613. if ( resize_to > bucket_count() ) { // we don't have enough buckets
  614. table.resize(resize_to); // sets the number of buckets
  615. settings.reset_thresholds(bucket_count());
  616. }
  617. // We use a normal iterator to get non-deleted bcks from ht
  618. // We could use insert() here, but since we know there are
  619. // no duplicates and no deleted items, we can be more efficient
  620. assert( (bucket_count() & (bucket_count()-1)) == 0); // a power of two
  621. // THIS IS THE MAJOR LINE THAT DIFFERS FROM COPY_FROM():
  622. for ( destructive_iterator it = ht.destructive_begin();
  623. it != ht.destructive_end(); ++it ) {
  624. size_type num_probes = 0; // how many times we've probed
  625. size_type bucknum;
  626. for ( bucknum = hash(get_key(*it)) & (bucket_count()-1); // h % buck_cnt
  627. table.test(bucknum); // not empty
  628. bucknum = (bucknum + JUMP_(key, num_probes)) & (bucket_count()-1) ) {
  629. ++num_probes;
  630. assert(num_probes < bucket_count()
  631. && "Hashtable is full: an error in key_equal<> or hash<>");
  632. }
  633. table.set(bucknum, *it); // copies the value to here
  634. }
  635. settings.inc_num_ht_copies();
  636. }
  637. // Required by the spec for hashed associative container
  638. public:
  639. // Though the docs say this should be num_buckets, I think it's much
  640. // more useful as num_elements. As a special feature, calling with
  641. // req_elements==0 will cause us to shrink if we can, saving space.
  642. void resize(size_type req_elements) { // resize to this or larger
  643. if ( settings.consider_shrink() || req_elements == 0 )
  644. maybe_shrink();
  645. if ( req_elements > table.num_nonempty() ) // we only grow
  646. resize_delta(req_elements - table.num_nonempty());
  647. }
  648. // Get and change the value of shrink_factor and enlarge_factor. The
  649. // description at the beginning of this file explains how to choose
  650. // the values. Setting the shrink parameter to 0.0 ensures that the
  651. // table never shrinks.
  652. void get_resizing_parameters(float* shrink, float* grow) const {
  653. *shrink = settings.shrink_factor();
  654. *grow = settings.enlarge_factor();
  655. }
  656. void set_resizing_parameters(float shrink, float grow) {
  657. settings.set_resizing_parameters(shrink, grow);
  658. settings.reset_thresholds(bucket_count());
  659. }
  660. // CONSTRUCTORS -- as required by the specs, we take a size,
  661. // but also let you specify a hashfunction, key comparator,
  662. // and key extractor. We also define a copy constructor and =.
  663. // DESTRUCTOR -- the default is fine, surprisingly.
  664. explicit sparse_hashtable(size_type expected_max_items_in_table = 0,
  665. const HashFcn& hf = HashFcn(),
  666. const EqualKey& eql = EqualKey(),
  667. const ExtractKey& ext = ExtractKey(),
  668. const SetKey& set = SetKey(),
  669. const Alloc& alloc = Alloc())
  670. : settings(hf),
  671. key_info(ext, set, eql),
  672. num_deleted(0),
  673. table((expected_max_items_in_table == 0
  674. ? HT_DEFAULT_STARTING_BUCKETS
  675. : settings.min_buckets(expected_max_items_in_table, 0)),
  676. alloc) {
  677. settings.reset_thresholds(bucket_count());
  678. }
  679. // As a convenience for resize(), we allow an optional second argument
  680. // which lets you make this new hashtable a different size than ht.
  681. // We also provide a mechanism of saying you want to "move" the ht argument
  682. // into us instead of copying.
  683. sparse_hashtable(const sparse_hashtable& ht,
  684. size_type min_buckets_wanted = HT_DEFAULT_STARTING_BUCKETS)
  685. : settings(ht.settings),
  686. key_info(ht.key_info),
  687. num_deleted(0),
  688. table(0, ht.get_allocator()) {
  689. settings.reset_thresholds(bucket_count());
  690. copy_from(ht, min_buckets_wanted); // copy_from() ignores deleted entries
  691. }
  692. sparse_hashtable(MoveDontCopyT mover, sparse_hashtable& ht,
  693. size_type min_buckets_wanted = HT_DEFAULT_STARTING_BUCKETS)
  694. : settings(ht.settings),
  695. key_info(ht.key_info),
  696. num_deleted(0),
  697. table(0, ht.get_allocator()) {
  698. settings.reset_thresholds(bucket_count());
  699. move_from(mover, ht, min_buckets_wanted); // ignores deleted entries
  700. }
  701. sparse_hashtable& operator= (const sparse_hashtable& ht) {
  702. if (&ht == this) return *this; // don't copy onto ourselves
  703. settings = ht.settings;
  704. key_info = ht.key_info;
  705. num_deleted = ht.num_deleted;
  706. // copy_from() calls clear and sets num_deleted to 0 too
  707. copy_from(ht, HT_MIN_BUCKETS);
  708. // we purposefully don't copy the allocator, which may not be copyable
  709. return *this;
  710. }
  711. // Many STL algorithms use swap instead of copy constructors
  712. void swap(sparse_hashtable& ht) {
  713. STL_NAMESPACE::swap(settings, ht.settings);
  714. STL_NAMESPACE::swap(key_info, ht.key_info);
  715. STL_NAMESPACE::swap(num_deleted, ht.num_deleted);
  716. table.swap(ht.table);
  717. }
  718. // It's always nice to be able to clear a table without deallocating it
  719. void clear() {
  720. if (!empty() || (num_deleted != 0)) {
  721. table.clear();
  722. }
  723. settings.reset_thresholds(bucket_count());
  724. num_deleted = 0;
  725. }
  726. // LOOKUP ROUTINES
  727. private:
  728. // Returns a pair of positions: 1st where the object is, 2nd where
  729. // it would go if you wanted to insert it. 1st is ILLEGAL_BUCKET
  730. // if object is not found; 2nd is ILLEGAL_BUCKET if it is.
  731. // Note: because of deletions where-to-insert is not trivial: it's the
  732. // first deleted bucket we see, as long as we don't find the key later
  733. pair<size_type, size_type> find_position(const key_type &key) const {
  734. size_type num_probes = 0; // how many times we've probed
  735. const size_type bucket_count_minus_one = bucket_count() - 1;
  736. size_type bucknum = hash(key) & bucket_count_minus_one;
  737. size_type insert_pos = ILLEGAL_BUCKET; // where we would insert
  738. SPARSEHASH_STAT_UPDATE(total_lookups += 1);
  739. while ( 1 ) { // probe until something happens
  740. if ( !table.test(bucknum) ) { // bucket is empty
  741. SPARSEHASH_STAT_UPDATE(total_probes += num_probes);
  742. if ( insert_pos == ILLEGAL_BUCKET ) // found no prior place to insert
  743. return pair<size_type,size_type>(ILLEGAL_BUCKET, bucknum);
  744. else
  745. return pair<size_type,size_type>(ILLEGAL_BUCKET, insert_pos);
  746. } else if ( test_deleted(bucknum) ) {// keep searching, but mark to insert
  747. if ( insert_pos == ILLEGAL_BUCKET )
  748. insert_pos = bucknum;
  749. } else if ( equals(key, get_key(table.unsafe_get(bucknum))) ) {
  750. SPARSEHASH_STAT_UPDATE(total_probes += num_probes);
  751. return pair<size_type,size_type>(bucknum, ILLEGAL_BUCKET);
  752. }
  753. ++num_probes; // we're doing another probe
  754. bucknum = (bucknum + JUMP_(key, num_probes)) & bucket_count_minus_one;
  755. assert(num_probes < bucket_count()
  756. && "Hashtable is full: an error in key_equal<> or hash<>");
  757. }
  758. }
  759. public:
  760. iterator find(const key_type& key) {
  761. if ( size() == 0 ) return end();
  762. pair<size_type, size_type> pos = find_position(key);
  763. if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
  764. return end();
  765. else
  766. return iterator(this, table.get_iter(pos.first), table.nonempty_end());
  767. }
  768. const_iterator find(const key_type& key) const {
  769. if ( size() == 0 ) return end();
  770. pair<size_type, size_type> pos = find_position(key);
  771. if ( pos.first == ILLEGAL_BUCKET ) // alas, not there
  772. return end();
  773. else
  774. return const_iterator(this,
  775. table.get_iter(pos.first), table.nonempty_end());
  776. }
  777. // This is a tr1 method: the bucket a given key is in, or what bucket
  778. // it would be put in, if it were to be inserted. Shrug.
  779. size_type bucket(const key_type& key) const {
  780. pair<size_type, size_type> pos = find_position(key);
  781. return pos.first == ILLEGAL_BUCKET ? pos.second : pos.first;
  782. }
  783. // Counts how many elements have key key. For maps, it's either 0 or 1.
  784. size_type count(const key_type &key) const {
  785. pair<size_type, size_type> pos = find_position(key);
  786. return pos.first == ILLEGAL_BUCKET ? 0 : 1;
  787. }
  788. // Likewise, equal_range doesn't really make sense for us. Oh well.
  789. pair<iterator,iterator> equal_range(const key_type& key) {
  790. iterator pos = find(key); // either an iterator or end
  791. if (pos == end()) {
  792. return pair<iterator,iterator>(pos, pos);
  793. } else {
  794. const iterator startpos = pos++;
  795. return pair<iterator,iterator>(startpos, pos);
  796. }
  797. }
  798. pair<const_iterator,const_iterator> equal_range(const key_type& key) const {
  799. const_iterator pos = find(key); // either an iterator or end
  800. if (pos == end()) {
  801. return pair<const_iterator,const_iterator>(pos, pos);
  802. } else {
  803. const const_iterator startpos = pos++;
  804. return pair<const_iterator,const_iterator>(startpos, pos);
  805. }
  806. }
  807. // INSERTION ROUTINES
  808. private:
  809. // Private method used by insert_noresize and find_or_insert.
  810. iterator insert_at(const_reference obj, size_type pos) {
  811. if (size() >= max_size())
  812. throw std::length_error("insert overflow");
  813. if ( test_deleted(pos) ) { // just replace if it's been deleted
  814. // The set() below will undelete this object. We just worry about stats
  815. assert(num_deleted > 0);
  816. --num_deleted; // used to be, now it isn't
  817. }
  818. table.set(pos, obj);
  819. return iterator(this, table.get_iter(pos), table.nonempty_end());
  820. }
  821. // If you know *this is big enough to hold obj, use this routine
  822. pair<iterator, bool> insert_noresize(const_reference obj) {
  823. // First, double-check we're not inserting delkey
  824. assert((!settings.use_deleted() || !equals(get_key(obj), key_info.delkey))
  825. && "Inserting the deleted key");
  826. const pair<size_type,size_type> pos = find_position(get_key(obj));
  827. if ( pos.first != ILLEGAL_BUCKET) { // object was already there
  828. return pair<iterator,bool>(iterator(this, table.get_iter(pos.first),
  829. table.nonempty_end()),
  830. false); // false: we didn't insert
  831. } else { // pos.second says where to put it
  832. return pair<iterator,bool>(insert_at(obj, pos.second), true);
  833. }
  834. }
  835. // Specializations of insert(it, it) depending on the power of the iterator:
  836. // (1) Iterator supports operator-, resize before inserting
  837. template <class ForwardIterator>
  838. void insert(ForwardIterator f, ForwardIterator l, STL_NAMESPACE::forward_iterator_tag) {
  839. size_t dist = STL_NAMESPACE::distance(f, l);
  840. if (dist >= (std::numeric_limits<size_type>::max)())
  841. throw std::length_error("insert-range overflow");
  842. resize_delta(static_cast<size_type>(dist));
  843. for ( ; dist > 0; --dist, ++f) {
  844. insert_noresize(*f);
  845. }
  846. }
  847. // (2) Arbitrary iterator, can't tell how much to resize
  848. template <class InputIterator>
  849. void insert(InputIterator f, InputIterator l, STL_NAMESPACE::input_iterator_tag) {
  850. for ( ; f != l; ++f)
  851. insert(*f);
  852. }
  853. public:
  854. // This is the normal insert routine, used by the outside world
  855. pair<iterator, bool> insert(const_reference obj) {
  856. resize_delta(1); // adding an object, grow if need be
  857. return insert_noresize(obj);
  858. }
  859. // When inserting a lot at a time, we specialize on the type of iterator
  860. template <class InputIterator>
  861. void insert(InputIterator f, InputIterator l) {
  862. // specializes on iterator type
  863. insert(f, l, typename STL_NAMESPACE::iterator_traits<InputIterator>::iterator_category());
  864. }
  865. // DefaultValue is a functor that takes a key and returns a value_type
  866. // representing the default value to be inserted if none is found.
  867. template <class DefaultValue>
  868. value_type& find_or_insert(const key_type& key) {
  869. // First, double-check we're not inserting delkey
  870. assert((!settings.use_deleted() || !equals(key, key_info.delkey))
  871. && "Inserting the deleted key");
  872. const pair<size_type,size_type> pos = find_position(key);
  873. DefaultValue default_value;
  874. if ( pos.first != ILLEGAL_BUCKET) { // object was already there
  875. return *table.get_iter(pos.first);
  876. } else if (resize_delta(1)) { // needed to rehash to make room
  877. // Since we resized, we can't use pos, so recalculate where to insert.
  878. return *insert_noresize(default_value(key)).first;
  879. } else { // no need to rehash, insert right here
  880. return *insert_at(default_value(key), pos.second);
  881. }
  882. }
  883. // DELETION ROUTINES
  884. size_type erase(const key_type& key) {
  885. // First, double-check we're not erasing delkey.
  886. assert((!settings.use_deleted() || !equals(key, key_info.delkey))
  887. && "Erasing the deleted key");
  888. assert(!settings.use_deleted() || !equals(key, key_info.delkey));
  889. const_iterator pos = find(key); // shrug: shouldn't need to be const
  890. if ( pos != end() ) {
  891. assert(!test_deleted(pos)); // or find() shouldn't have returned it
  892. set_deleted(pos);
  893. ++num_deleted;
  894. // will think about shrink after next insert
  895. settings.set_consider_shrink(true);
  896. return 1; // because we deleted one thing
  897. } else {
  898. return 0; // because we deleted nothing
  899. }
  900. }
  901. // We return the iterator past the deleted item.
  902. void erase(iterator pos) {
  903. if ( pos == end() ) return; // sanity check
  904. if ( set_deleted(pos) ) { // true if object has been newly deleted
  905. ++num_deleted;
  906. // will think about shrink after next insert
  907. settings.set_consider_shrink(true);
  908. }
  909. }
  910. void erase(iterator f, iterator l) {
  911. for ( ; f != l; ++f) {
  912. if ( set_deleted(f) ) // should always be true
  913. ++num_deleted;
  914. }
  915. // will think about shrink after next insert
  916. settings.set_consider_shrink(true);
  917. }
  918. // We allow you to erase a const_iterator just like we allow you to
  919. // erase an iterator. This is in parallel to 'delete': you can delete
  920. // a const pointer just like a non-const pointer. The logic is that
  921. // you can't use the object after it's erased anyway, so it doesn't matter
  922. // if it's const or not.
  923. void erase(const_iterator pos) {
  924. if ( pos == end() ) return; // sanity check
  925. if ( set_deleted(pos) ) { // true if object has been newly deleted
  926. ++num_deleted;
  927. // will think about shrink after next insert
  928. settings.set_consider_shrink(true);
  929. }
  930. }
  931. void erase(const_iterator f, const_iterator l) {
  932. for ( ; f != l; ++f) {
  933. if ( set_deleted(f) ) // should always be true
  934. ++num_deleted;
  935. }
  936. // will think about shrink after next insert
  937. settings.set_consider_shrink(true);
  938. }
  939. // COMPARISON
  940. bool operator==(const sparse_hashtable& ht) const {
  941. if (size() != ht.size()) {
  942. return false;
  943. } else if (this == &ht) {
  944. return true;
  945. } else {
  946. // Iterate through the elements in "this" and see if the
  947. // corresponding element is in ht
  948. for ( const_iterator it = begin(); it != end(); ++it ) {
  949. const_iterator it2 = ht.find(get_key(*it));
  950. if ((it2 == ht.end()) || (*it != *it2)) {
  951. return false;
  952. }
  953. }
  954. return true;
  955. }
  956. }
  957. bool operator!=(const sparse_hashtable& ht) const {
  958. return !(*this == ht);
  959. }
  960. // I/O
  961. // We support reading and writing hashtables to disk. NOTE that
  962. // this only stores the hashtable metadata, not the stuff you've
  963. // actually put in the hashtable! Alas, since I don't know how to
  964. // write a hasher or key_equal, you have to make sure everything
  965. // but the table is the same. We compact before writing.
  966. bool write_metadata(FILE *fp) {
  967. squash_deleted(); // so we don't have to worry about delkey
  968. return table.write_metadata(fp);
  969. }
  970. bool read_metadata(FILE *fp) {
  971. num_deleted = 0; // since we got rid before writing
  972. bool result = table.read_metadata(fp);
  973. settings.reset_thresholds(bucket_count());
  974. return result;
  975. }
  976. // Only meaningful if value_type is a POD.
  977. bool write_nopointer_data(FILE *fp) {
  978. return table.write_nopointer_data(fp);
  979. }
  980. // Only meaningful if value_type is a POD.
  981. bool read_nopointer_data(FILE *fp) {
  982. return table.read_nopointer_data(fp);
  983. }
  984. private:
  985. // Table is the main storage class.
  986. typedef sparsetable<value_type, DEFAULT_GROUP_SIZE, value_alloc_type> Table;
  987. // Package templated functors with the other types to eliminate memory
  988. // needed for storing these zero-size operators. Since ExtractKey and
  989. // hasher's operator() might have the same function signature, they
  990. // must be packaged in different classes.
  991. struct Settings :
  992. sh_hashtable_settings<key_type, hasher, size_type, HT_MIN_BUCKETS> {
  993. explicit Settings(const hasher& hf)
  994. : sh_hashtable_settings<key_type, hasher, size_type, HT_MIN_BUCKETS>(
  995. hf, HT_OCCUPANCY_PCT / 100.0f, HT_EMPTY_PCT / 100.0f) {}
  996. };
  997. // KeyInfo stores delete key and packages zero-size functors:
  998. // ExtractKey and SetKey.
  999. class KeyInfo : public ExtractKey, public SetKey, public key_equal {
  1000. public:
  1001. KeyInfo(const ExtractKey& ek, const SetKey& sk, const key_equal& eq)
  1002. : ExtractKey(ek),
  1003. SetKey(sk),
  1004. key_equal(eq) {
  1005. }
  1006. const key_type get_key(const_reference v) const {
  1007. return ExtractKey::operator()(v);
  1008. }
  1009. void set_key(pointer v, const key_type& k) const {
  1010. SetKey::operator()(v, k);
  1011. }
  1012. bool equals(const key_type& a, const key_type& b) const {
  1013. return key_equal::operator()(a, b);
  1014. }
  1015. // Which key marks deleted entries.
  1016. // TODO(csilvers): make a pointer, and get rid of use_deleted (benchmark!)
  1017. typename remove_const<key_type>::type delkey;
  1018. };
  1019. // Utility functions to access the templated operators
  1020. size_type hash(const key_type& v) const {
  1021. return settings.hash(v);
  1022. }
  1023. bool equals(const key_type& a, const key_type& b) const {
  1024. return key_info.equals(a, b);
  1025. }
  1026. const key_type get_key(const_reference v) const {
  1027. return key_info.get_key(v);
  1028. }
  1029. void set_key(pointer v, const key_type& k) const {
  1030. key_info.set_key(v, k);
  1031. }
  1032. private:
  1033. // Actual data
  1034. Settings settings;
  1035. KeyInfo key_info;
  1036. size_type num_deleted; // how many occupied buckets are marked deleted
  1037. Table table; // holds num_buckets and num_elements too
  1038. };
  1039. // We need a global swap as well
  1040. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1041. inline void swap(sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> &x,
  1042. sparse_hashtable<V,K,HF,ExK,SetK,EqK,A> &y) {
  1043. x.swap(y);
  1044. }
  1045. #undef JUMP_
  1046. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1047. const typename sparse_hashtable<V,K,HF,ExK,SetK,EqK,A>::size_type
  1048. sparse_hashtable<V,K,HF,ExK,SetK,EqK,A>::ILLEGAL_BUCKET;
  1049. // How full we let the table get before we resize. Knuth says .8 is
  1050. // good -- higher causes us to probe too much, though saves memory
  1051. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1052. const int sparse_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_OCCUPANCY_PCT = 80;
  1053. // How empty we let the table get before we resize lower.
  1054. // It should be less than OCCUPANCY_PCT / 2 or we thrash resizing
  1055. template <class V, class K, class HF, class ExK, class SetK, class EqK, class A>
  1056. const int sparse_hashtable<V,K,HF,ExK,SetK,EqK,A>::HT_EMPTY_PCT
  1057. = static_cast<int>(0.4 *
  1058. sparse_hashtable<V,K,HF,

Large files files are truncated, but you can click here to view the full file