sparsehash/internal/densehashtable.h

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