dense_hash_set.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. // This is just a very thin wrapper over densehashtable.h, just
  32. // like sgi stl's stl_hash_set is a very thin wrapper over
  33. // stl_hashtable. The major thing we define is operator[], because
  34. // we have a concept of a data_type which stl_hashtable doesn't
  35. // (it only has a key and a value).
  36. //
  37. // This is more different from dense_hash_map than you might think,
  38. // because all iterators for sets are const (you obviously can't
  39. // change the key, and for sets there is no value).
  40. //
  41. // NOTE: this is exactly like sparse_hash_set.h, with the word
  42. // "sparse" replaced by "dense", except for the addition of
  43. // set_empty_key().
  44. //
  45. // YOU MUST CALL SET_EMPTY_KEY() IMMEDIATELY AFTER CONSTRUCTION.
  46. //
  47. // Otherwise your program will die in mysterious ways. (Note if you
  48. // use the constructor that takes an InputIterator range, you pass in
  49. // the empty key in the constructor, rather than after. As a result,
  50. // this constructor differs from the standard STL version.)
  51. //
  52. // In other respects, we adhere mostly to the STL semantics for
  53. // hash-map. One important exception is that insert() may invalidate
  54. // iterators entirely -- STL semantics are that insert() may reorder
  55. // iterators, but they all still refer to something valid in the
  56. // hashtable. Not so for us. Likewise, insert() may invalidate
  57. // pointers into the hashtable. (Whether insert invalidates iterators
  58. // and pointers depends on whether it results in a hashtable resize).
  59. // On the plus side, delete() doesn't invalidate iterators or pointers
  60. // at all, or even change the ordering of elements.
  61. //
  62. // Here are a few "power user" tips:
  63. //
  64. // 1) set_deleted_key():
  65. // If you want to use erase() you must call set_deleted_key(),
  66. // in addition to set_empty_key(), after construction.
  67. // The deleted and empty keys must differ.
  68. //
  69. // 2) resize(0):
  70. // When an item is deleted, its memory isn't freed right
  71. // away. This allows you to iterate over a hashtable,
  72. // and call erase(), without invalidating the iterator.
  73. // To force the memory to be freed, call resize(0).
  74. // For tr1 compatibility, this can also be called as rehash(0).
  75. //
  76. // 3) min_load_factor(0.0)
  77. // Setting the minimum load factor to 0.0 guarantees that
  78. // the hash table will never shrink.
  79. //
  80. // Roughly speaking:
  81. // (1) dense_hash_set: fastest, uses the most memory unless entries are small
  82. // (2) sparse_hash_set: slowest, uses the least memory
  83. // (3) hash_set / unordered_set (STL): in the middle
  84. //
  85. // Typically I use sparse_hash_set when I care about space and/or when
  86. // I need to save the hashtable on disk. I use hash_set otherwise. I
  87. // don't personally use dense_hash_set ever; some people use it for
  88. // small sets with lots of lookups.
  89. //
  90. // - dense_hash_set has, typically, about 78% memory overhead (if your
  91. // data takes up X bytes, the hash_set uses .78X more bytes in overhead).
  92. // - sparse_hash_set has about 4 bits overhead per entry.
  93. // - sparse_hash_set can be 3-7 times slower than the others for lookup and,
  94. // especially, inserts. See time_hash_map.cc for details.
  95. //
  96. // See /usr/(local/)?doc/sparsehash-*/dense_hash_set.html
  97. // for information about how to use this class.
  98. #ifndef _DENSE_HASH_SET_H_
  99. #define _DENSE_HASH_SET_H_
  100. #include "internal/sparseconfig.h"
  101. #include <algorithm> // needed by stl_alloc
  102. #include <functional> // for equal_to<>, select1st<>, etc
  103. #include <memory> // for alloc
  104. #include <utility> // for pair<>
  105. #include "internal/densehashtable.h" // IWYU pragma: export
  106. #include "internal/libc_allocator_with_realloc.h"
  107. #include HASH_FUN_H // for hash<>
  108. _START_GOOGLE_NAMESPACE_
  109. template <class Value,
  110. class HashFcn = SPARSEHASH_HASH<Value>, // defined in sparseconfig.h
  111. class EqualKey = std::equal_to<Value>,
  112. class Alloc = libc_allocator_with_realloc<Value> >
  113. class dense_hash_set {
  114. private:
  115. // Apparently identity is not stl-standard, so we define our own
  116. struct Identity {
  117. typedef const Value& result_type;
  118. const Value& operator()(const Value& v) const { return v; }
  119. };
  120. struct SetKey {
  121. void operator()(Value* value, const Value& new_key) const {
  122. *value = new_key;
  123. }
  124. };
  125. // The actual data
  126. typedef dense_hashtable<Value, Value, HashFcn, Identity, SetKey,
  127. EqualKey, Alloc> ht;
  128. ht rep;
  129. public:
  130. typedef typename ht::key_type key_type;
  131. typedef typename ht::value_type value_type;
  132. typedef typename ht::hasher hasher;
  133. typedef typename ht::key_equal key_equal;
  134. typedef Alloc allocator_type;
  135. typedef typename ht::size_type size_type;
  136. typedef typename ht::difference_type difference_type;
  137. typedef typename ht::const_pointer pointer;
  138. typedef typename ht::const_pointer const_pointer;
  139. typedef typename ht::const_reference reference;
  140. typedef typename ht::const_reference const_reference;
  141. typedef typename ht::const_iterator iterator;
  142. typedef typename ht::const_iterator const_iterator;
  143. typedef typename ht::const_local_iterator local_iterator;
  144. typedef typename ht::const_local_iterator const_local_iterator;
  145. // Iterator functions -- recall all iterators are const
  146. iterator begin() const { return rep.begin(); }
  147. iterator end() const { return rep.end(); }
  148. // These come from tr1's unordered_set. For us, a bucket has 0 or 1 elements.
  149. local_iterator begin(size_type i) const { return rep.begin(i); }
  150. local_iterator end(size_type i) const { return rep.end(i); }
  151. // Accessor functions
  152. allocator_type get_allocator() const { return rep.get_allocator(); }
  153. hasher hash_funct() const { return rep.hash_funct(); }
  154. hasher hash_function() const { return hash_funct(); } // tr1 name
  155. key_equal key_eq() const { return rep.key_eq(); }
  156. // Constructors
  157. explicit dense_hash_set(size_type expected_max_items_in_table = 0,
  158. const hasher& hf = hasher(),
  159. const key_equal& eql = key_equal(),
  160. const allocator_type& alloc = allocator_type())
  161. : rep(expected_max_items_in_table, hf, eql, Identity(), SetKey(), alloc) {
  162. }
  163. template <class InputIterator>
  164. dense_hash_set(InputIterator f, InputIterator l,
  165. const key_type& empty_key_val,
  166. size_type expected_max_items_in_table = 0,
  167. const hasher& hf = hasher(),
  168. const key_equal& eql = key_equal(),
  169. const allocator_type& alloc = allocator_type())
  170. : rep(expected_max_items_in_table, hf, eql, Identity(), SetKey(), alloc) {
  171. set_empty_key(empty_key_val);
  172. rep.insert(f, l);
  173. }
  174. // We use the default copy constructor
  175. // We use the default operator=()
  176. // We use the default destructor
  177. void clear() { rep.clear(); }
  178. // This clears the hash set without resizing it down to the minimum
  179. // bucket count, but rather keeps the number of buckets constant
  180. void clear_no_resize() { rep.clear_no_resize(); }
  181. void swap(dense_hash_set& hs) { rep.swap(hs.rep); }
  182. // Functions concerning size
  183. size_type size() const { return rep.size(); }
  184. size_type max_size() const { return rep.max_size(); }
  185. bool empty() const { return rep.empty(); }
  186. size_type bucket_count() const { return rep.bucket_count(); }
  187. size_type max_bucket_count() const { return rep.max_bucket_count(); }
  188. // These are tr1 methods. bucket() is the bucket the key is or would be in.
  189. size_type bucket_size(size_type i) const { return rep.bucket_size(i); }
  190. size_type bucket(const key_type& key) const { return rep.bucket(key); }
  191. float load_factor() const {
  192. return size() * 1.0f / bucket_count();
  193. }
  194. float max_load_factor() const {
  195. float shrink, grow;
  196. rep.get_resizing_parameters(&shrink, &grow);
  197. return grow;
  198. }
  199. void max_load_factor(float new_grow) {
  200. float shrink, grow;
  201. rep.get_resizing_parameters(&shrink, &grow);
  202. rep.set_resizing_parameters(shrink, new_grow);
  203. }
  204. // These aren't tr1 methods but perhaps ought to be.
  205. float min_load_factor() const {
  206. float shrink, grow;
  207. rep.get_resizing_parameters(&shrink, &grow);
  208. return shrink;
  209. }
  210. void min_load_factor(float new_shrink) {
  211. float shrink, grow;
  212. rep.get_resizing_parameters(&shrink, &grow);
  213. rep.set_resizing_parameters(new_shrink, grow);
  214. }
  215. // Deprecated; use min_load_factor() or max_load_factor() instead.
  216. void set_resizing_parameters(float shrink, float grow) {
  217. rep.set_resizing_parameters(shrink, grow);
  218. }
  219. void resize(size_type hint) { rep.resize(hint); }
  220. void rehash(size_type hint) { resize(hint); } // the tr1 name
  221. // Lookup routines
  222. iterator find(const key_type& key) const { return rep.find(key); }
  223. size_type count(const key_type& key) const { return rep.count(key); }
  224. std::pair<iterator, iterator> equal_range(const key_type& key) const {
  225. return rep.equal_range(key);
  226. }
  227. // Insertion routines
  228. std::pair<iterator, bool> insert(const value_type& obj) {
  229. std::pair<typename ht::iterator, bool> p = rep.insert(obj);
  230. return std::pair<iterator, bool>(p.first, p.second); // const to non-const
  231. }
  232. template <class InputIterator> void insert(InputIterator f, InputIterator l) {
  233. rep.insert(f, l);
  234. }
  235. void insert(const_iterator f, const_iterator l) {
  236. rep.insert(f, l);
  237. }
  238. // Required for std::insert_iterator; the passed-in iterator is ignored.
  239. iterator insert(iterator, const value_type& obj) {
  240. return insert(obj).first;
  241. }
  242. // Deletion and empty routines
  243. // THESE ARE NON-STANDARD! I make you specify an "impossible" key
  244. // value to identify deleted and empty buckets. You can change the
  245. // deleted key as time goes on, or get rid of it entirely to be insert-only.
  246. void set_empty_key(const key_type& key) { rep.set_empty_key(key); }
  247. key_type empty_key() const { return rep.empty_key(); }
  248. void set_deleted_key(const key_type& key) { rep.set_deleted_key(key); }
  249. void clear_deleted_key() { rep.clear_deleted_key(); }
  250. key_type deleted_key() const { return rep.deleted_key(); }
  251. // These are standard
  252. size_type erase(const key_type& key) { return rep.erase(key); }
  253. void erase(iterator it) { rep.erase(it); }
  254. void erase(iterator f, iterator l) { rep.erase(f, l); }
  255. // Comparison
  256. bool operator==(const dense_hash_set& hs) const { return rep == hs.rep; }
  257. bool operator!=(const dense_hash_set& hs) const { return rep != hs.rep; }
  258. // I/O -- this is an add-on for writing metainformation to disk
  259. //
  260. // For maximum flexibility, this does not assume a particular
  261. // file type (though it will probably be a FILE *). We just pass
  262. // the fp through to rep.
  263. // If your keys and values are simple enough, you can pass this
  264. // serializer to serialize()/unserialize(). "Simple enough" means
  265. // value_type is a POD type that contains no pointers. Note,
  266. // however, we don't try to normalize endianness.
  267. typedef typename ht::NopointerSerializer NopointerSerializer;
  268. // serializer: a class providing operator()(OUTPUT*, const value_type&)
  269. // (writing value_type to OUTPUT). You can specify a
  270. // NopointerSerializer object if appropriate (see above).
  271. // fp: either a FILE*, OR an ostream*/subclass_of_ostream*, OR a
  272. // pointer to a class providing size_t Write(const void*, size_t),
  273. // which writes a buffer into a stream (which fp presumably
  274. // owns) and returns the number of bytes successfully written.
  275. // Note basic_ostream<not_char> is not currently supported.
  276. template <typename ValueSerializer, typename OUTPUT>
  277. bool serialize(ValueSerializer serializer, OUTPUT* fp) {
  278. return rep.serialize(serializer, fp);
  279. }
  280. // serializer: a functor providing operator()(INPUT*, value_type*)
  281. // (reading from INPUT and into value_type). You can specify a
  282. // NopointerSerializer object if appropriate (see above).
  283. // fp: either a FILE*, OR an istream*/subclass_of_istream*, OR a
  284. // pointer to a class providing size_t Read(void*, size_t),
  285. // which reads into a buffer from a stream (which fp presumably
  286. // owns) and returns the number of bytes successfully read.
  287. // Note basic_istream<not_char> is not currently supported.
  288. template <typename ValueSerializer, typename INPUT>
  289. bool unserialize(ValueSerializer serializer, INPUT* fp) {
  290. return rep.unserialize(serializer, fp);
  291. }
  292. };
  293. template <class Val, class HashFcn, class EqualKey, class Alloc>
  294. inline void swap(dense_hash_set<Val, HashFcn, EqualKey, Alloc>& hs1,
  295. dense_hash_set<Val, HashFcn, EqualKey, Alloc>& hs2) {
  296. hs1.swap(hs2);
  297. }
  298. _END_GOOGLE_NAMESPACE_
  299. #endif /* _DENSE_HASH_SET_H_ */