sparse_hash_map.h 15 KB

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