暫無描述
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.

sparsehashtable.h 51KB

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