Debian Codegraph @

3rdparty/robin-map/README.md

raw symbols SCIP
1 [![CI](https://github.com/Tessil/robin-map/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/Tessil/robin-map/actions/workflows/ci.yml)
2
3 ## A C++ implementation of a fast hash map and hash set using robin hood hashing
4
5 The robin-map library is a C++ implementation of a fast hash map and hash set using open-addressing and linear robin hood hashing with backward shift deletion to resolve collisions.
6
7 Four classes are provided: `tsl::robin_map`, `tsl::robin_set`, `tsl::robin_pg_map` and `tsl::robin_pg_set`. The first two are faster and use a power of two growth policy, the last two use a prime growth policy instead and are able to cope better with a poor hash function. Use the prime version if there is a chance of repeating patterns in the lower bits of your hash (e.g. you are storing pointers with an identity hash function). See [GrowthPolicy](#growth-policy) for details.
8
9 A **benchmark** of `tsl::robin_map` against other hash maps may be found [here](https://tessil.github.io/2016/08/29/benchmark-hopscotch-map.html). This page also gives some advices on which hash table structure you should try for your use case (useful if you are a bit lost with the multiple hash tables implementations in the `tsl` namespace).
10
11 ### Key features
12
13 - Header-only library, just add the [include](include/) directory to your include path and you are ready to go. If you use CMake, you can also use the `tsl::robin_map` exported target from the [CMakeLists.txt](CMakeLists.txt).
14 - Fast hash table, check the [benchmark](https://tessil.github.io/2016/08/29/benchmark-hopscotch-map.html) for some numbers.
15 - Support for move-only and non-default constructible key/value.
16 - Support for heterogeneous lookups allowing the usage of `find` with a type different than `Key` (e.g. if you have a map that uses `std::unique_ptr<foo>` as key, you can use a `foo*` or a `std::uintptr_t` as key parameter to `find` without constructing a `std::unique_ptr<foo>`, see [example](#heterogeneous-lookups)).
17 - No need to reserve any sentinel value from the keys.
18 - Possibility to store the hash value alongside the stored key-value for faster rehash and lookup if the hash or the key equal functions are expensive to compute. Note that hash may be stored even if not asked explicitly when the library can detect that it will have no impact on the size of the structure in memory due to alignment. See the [StoreHash](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html#details) template parameter for details.
19 - If the hash is known before a lookup, it is possible to pass it as parameter to speed-up the lookup (see `precalculated_hash` parameter in [API](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html#a35021b11aabb61820236692a54b3a0f8)).
20 - Support for efficient serialization and deserialization (see [example](#serialization) and the `serialize/deserialize` methods in the [API](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html) for details).
21 - The library can be used with exceptions disabled (through `-fno-exceptions` option on Clang and GCC, without an `/EH` option on MSVC or simply by defining `TSL_NO_EXCEPTIONS`). `std::terminate` is used in replacement of the `throw` instruction when exceptions are disabled.
22 - API closely similar to `std::unordered_map` and `std::unordered_set`.
23
24 ### Differences compared to `std::unordered_map`
25
26 `tsl::robin_map` tries to have an interface similar to `std::unordered_map`, but some differences exist.
27 - The **strong exception guarantee only holds** if the following statement is true `std::is_nothrow_swappable<value_type>::value && std::is_nothrow_move_constructible<value_type>::value` (where `value_type` is `Key` for `tsl::robin_set` and `std::pair<Key, T>` for `tsl::robin_map`). Otherwise if an exception is thrown during the swap or the move, the structure may end up in a undefined state. Note that per the standard, a `value_type` with a noexcept copy constructor and no move constructor also satisfies this condition and will thus guarantee the strong exception guarantee for the structure (see [API](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html#details) for details).
28 - The type `Key`, and also `T` in case of map, must be swappable. They must also be copy and/or move constructible.
29 - Iterator invalidation doesn't behave in the same way, any operation modifying the hash table invalidate them (see [API](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html#details) for details).
30 - References and pointers to keys or values in the map are invalidated in the same way as iterators to these keys-values.
31 - For iterators of `tsl::robin_map`, `operator*()` and `operator->()` return a reference and a pointer to `const std::pair<Key, T>` instead of `std::pair<const Key, T>` making the value `T` not modifiable. To modify the value you have to call the `value()` method of the iterator to get a mutable reference. Example:
32 ```c++
33 tsl::robin_map<int, int> map = {{1, 1}, {2, 1}, {3, 1}};
34 for(auto it = map.begin(); it != map.end(); ++it) {
35 //it->second = 2; // Illegal
36 it.value() = 2; // Ok
37 }
38 ```
39 - No support for some buckets related methods (like `bucket_size`, `bucket`, ...).
40
41 These differences also apply between `std::unordered_set` and `tsl::robin_set`.
42
43 Thread-safety guarantees are the same as `std::unordered_map/set` (i.e. possible to have multiple readers with no writer).
44
45 ### Growth policy
46
47 The library supports multiple growth policies through the `GrowthPolicy` template parameter. Three policies are provided by the library but you can easily implement your own if needed.
48
49 * **[tsl::rh::power_of_two_growth_policy.](https://tessil.github.io/robin-map/classtsl_1_1rh_1_1power__of__two__growth__policy.html)** Default policy used by `tsl::robin_map/set`. This policy keeps the size of the bucket array of the hash table to a power of two. This constraint allows the policy to avoid the usage of the slow modulo operation to map a hash to a bucket, instead of <code>hash % 2<sup>n</sup></code>, it uses <code>hash & (2<sup>n</sup> - 1)</code> (see [fast modulo](https://en.wikipedia.org/wiki/Modulo_operation#Performance_issues)). Fast but this may cause a lot of collisions with a poor hash function as the modulo with a power of two only masks the most significant bits in the end.
50 * **[tsl::rh::prime_growth_policy.](https://tessil.github.io/robin-map/classtsl_1_1rh_1_1prime__growth__policy.html)** Default policy used by `tsl::robin_pg_map/set`. The policy keeps the size of the bucket array of the hash table to a prime number. When mapping a hash to a bucket, using a prime number as modulo will result in a better distribution of the hash across the buckets even with a poor hash function. To allow the compiler to optimize the modulo operation, the policy use a lookup table with constant primes modulos (see [API](https://tessil.github.io/robin-map/classtsl_1_1rh_1_1prime__growth__policy.html#details) for details). Slower than `tsl::rh::power_of_two_growth_policy` but more secure.
51 * **[tsl::rh::mod_growth_policy.](https://tessil.github.io/robin-map/classtsl_1_1rh_1_1mod__growth__policy.html)** The policy grows the map by a customizable growth factor passed in parameter. It then just use the modulo operator to map a hash to a bucket. Slower but more flexible.
52
53
54 To implement your own policy, you have to implement the following interface.
55
56 ```c++
57 struct custom_policy {
58 // Called on hash table construction and rehash, min_bucket_count_in_out is the minimum buckets
59 // that the hash table needs. The policy can change it to a higher number of buckets if needed
60 // and the hash table will use this value as bucket count. If 0 bucket is asked, then the value
61 // must stay at 0.
62 explicit custom_policy(std::size_t& min_bucket_count_in_out);
63
64 // Return the bucket [0, bucket_count()) to which the hash belongs.
65 // If bucket_count() is 0, it must always return 0.
66 std::size_t bucket_for_hash(std::size_t hash) const noexcept;
67
68 // Return the number of buckets that should be used on next growth
69 std::size_t next_bucket_count() const;
70
71 // Maximum number of buckets supported by the policy
72 std::size_t max_bucket_count() const;
73
74 // Reset the growth policy as if the policy was created with a bucket count of 0.
75 // After a clear, the policy must always return 0 when bucket_for_hash() is called.
76 void clear() noexcept;
77 }
78 ```
79
80 ### Installation
81
82 To use robin-map, just add the [include](include/) directory to your include path. It is a **header-only** library.
83
84 If you use CMake, you can also use the `tsl::robin_map` exported target from the [CMakeLists.txt](CMakeLists.txt) with `target_link_libraries`.
85 ```cmake
86 # Example where the robin-map project is stored in a third-party directory
87 add_subdirectory(third-party/robin-map)
88 target_link_libraries(your_target PRIVATE tsl::robin_map)
89 ```
90
91 If the project has been installed through `make install`, you can also use `find_package(tsl-robin-map REQUIRED)` instead of `add_subdirectory`.
92
93 The library is available in [vcpkg](https://github.com/Microsoft/vcpkg/tree/master/ports/robin-map) and [conan](https://conan.io/center/tsl-robin-map). It's also present in [Debian](https://packages.debian.org/buster/robin-map-dev), [Ubuntu](https://packages.ubuntu.com/disco/robin-map-dev) and [Fedora](https://apps.fedoraproject.org/packages/robin-map-devel) package repositories.
94
95 The code should work with any C++11 standard-compliant compiler and has been tested with GCC 4.8.4, Clang 3.5.0 and Visual Studio 2015.
96
97 To run the tests you will need the Boost Test library and CMake.
98
99 ```bash
100 git clone https://github.com/Tessil/robin-map.git
101 cd robin-map/tests
102 mkdir build
103 cd build
104 cmake ..
105 cmake --build .
106 ./tsl_robin_map_tests
107 ```
108
109 ### Usage
110
111 The API can be found [here](https://tessil.github.io/robin-map/).
112
113 All methods are not documented yet, but they replicate the behavior of the ones in `std::unordered_map` and `std::unordered_set`, except if specified otherwise.
114
115
116 ### Example
117
118 ```c++
119 #include <cstdint>
120 #include <iostream>
121 #include <string>
122 #include <tsl/robin_map.h>
123 #include <tsl/robin_set.h>
124
125 int main() {
126 tsl::robin_map<std::string, int> map = {{"a", 1}, {"b", 2}};
127 map["c"] = 3;
128 map["d"] = 4;
129
130 map.insert({"e", 5});
131 map.erase("b");
132
133 for(auto it = map.begin(); it != map.end(); ++it) {
134 //it->second += 2; // Not valid.
135 it.value() += 2;
136 }
137
138 // {d, 6} {a, 3} {e, 7} {c, 5}
139 for(const auto& key_value : map) {
140 std::cout << "{" << key_value.first << ", " << key_value.second << "}" << std::endl;
141 }
142
143
144 if(map.find("a") != map.end()) {
145 std::cout << "Found \"a\"." << std::endl;
146 }
147
148 const std::size_t precalculated_hash = std::hash<std::string>()("a");
149 // If we already know the hash beforehand, we can pass it in parameter to speed-up lookups.
150 if(map.find("a", precalculated_hash) != map.end()) {
151 std::cout << "Found \"a\" with hash " << precalculated_hash << "." << std::endl;
152 }
153
154
155 /*
156 * Calculating the hash and comparing two std::string may be slow.
157 * We can store the hash of each std::string in the hash map to make
158 * the inserts and lookups faster by setting StoreHash to true.
159 */
160 tsl::robin_map<std::string, int, std::hash<std::string>,
161 std::equal_to<std::string>,
162 std::allocator<std::pair<std::string, int>>,
163 true> map2;
164
165 map2["a"] = 1;
166 map2["b"] = 2;
167
168 // {a, 1} {b, 2}
169 for(const auto& key_value : map2) {
170 std::cout << "{" << key_value.first << ", " << key_value.second << "}" << std::endl;
171 }
172
173
174
175
176 tsl::robin_set<int> set;
177 set.insert({1, 9, 0});
178 set.insert({2, -1, 9});
179
180 // {0} {1} {2} {9} {-1}
181 for(const auto& key : set) {
182 std::cout << "{" << key << "}" << std::endl;
183 }
184 }
185 ```
186
187 #### Heterogeneous lookups
188
189 Heterogeneous overloads allow the usage of other types than `Key` for lookup and erase operations as long as the used types are hashable and comparable to `Key`.
190
191 To activate the heterogeneous overloads in `tsl::robin_map/set`, the qualified-id `KeyEqual::is_transparent` must be valid. It works the same way as for [`std::map::find`](http://en.cppreference.com/w/cpp/container/map/find). You can either use [`std::equal_to<>`](http://en.cppreference.com/w/cpp/utility/functional/equal_to_void) or define your own function object.
192
193 Both `KeyEqual` and `Hash` will need to be able to deal with the different types.
194
195 ```c++
196 #include <functional>
197 #include <iostream>
198 #include <string>
199 #include <tsl/robin_map.h>
200
201
202 struct employee {
203 employee(int id, std::string name) : m_id(id), m_name(std::move(name)) {
204 }
205
206 // Either we include the comparators in the class and we use `std::equal_to<>`...
207 friend bool operator==(const employee& empl, int empl_id) {
208 return empl.m_id == empl_id;
209 }
210
211 friend bool operator==(int empl_id, const employee& empl) {
212 return empl_id == empl.m_id;
213 }
214
215 friend bool operator==(const employee& empl1, const employee& empl2) {
216 return empl1.m_id == empl2.m_id;
217 }
218
219
220 int m_id;
221 std::string m_name;
222 };
223
224 // ... or we implement a separate class to compare employees.
225 struct equal_employee {
226 using is_transparent = void;
227
228 bool operator()(const employee& empl, int empl_id) const {
229 return empl.m_id == empl_id;
230 }
231
232 bool operator()(int empl_id, const employee& empl) const {
233 return empl_id == empl.m_id;
234 }
235
236 bool operator()(const employee& empl1, const employee& empl2) const {
237 return empl1.m_id == empl2.m_id;
238 }
239 };
240
241 struct hash_employee {
242 std::size_t operator()(const employee& empl) const {
243 return std::hash<int>()(empl.m_id);
244 }
245
246 std::size_t operator()(int id) const {
247 return std::hash<int>()(id);
248 }
249 };
250
251
252 int main() {
253 // Use std::equal_to<> which will automatically deduce and forward the parameters
254 tsl::robin_map<employee, int, hash_employee, std::equal_to<>> map;
255 map.insert({employee(1, "John Doe"), 2001});
256 map.insert({employee(2, "Jane Doe"), 2002});
257 map.insert({employee(3, "John Smith"), 2003});
258
259 // John Smith 2003
260 auto it = map.find(3);
261 if(it != map.end()) {
262 std::cout << it->first.m_name << " " << it->second << std::endl;
263 }
264
265 map.erase(1);
266
267
268
269 // Use a custom KeyEqual which has an is_transparent member type
270 tsl::robin_map<employee, int, hash_employee, equal_employee> map2;
271 map2.insert({employee(4, "Johnny Doe"), 2004});
272
273 // 2004
274 std::cout << map2.at(4) << std::endl;
275 }
276 ```
277
278 #### Serialization
279
280 The library provides an efficient way to serialize and deserialize a map or a set so that it can be saved to a file or send through the network.
281 To do so, it requires the user to provide a function object for both serialization and deserialization.
282
283 ```c++
284 struct serializer {
285 // Must support the following types for U: std::int16_t, std::uint32_t,
286 // std::uint64_t, float and std::pair<Key, T> if a map is used or Key for
287 // a set.
288 template<typename U>
289 void operator()(const U& value);
290 };
291 ```
292
293 ```c++
294 struct deserializer {
295 // Must support the following types for U: std::int16_t, std::uint32_t,
296 // std::uint64_t, float and std::pair<Key, T> if a map is used or Key for
297 // a set.
298 template<typename U>
299 U operator()();
300 };
301 ```
302
303 Note that the implementation leaves binary compatibility (endianness, float binary representation, size of int, ...) of the types it serializes/deserializes in the hands of the provided function objects if compatibility is required.
304
305 More details regarding the `serialize` and `deserialize` methods can be found in the [API](https://tessil.github.io/robin-map/classtsl_1_1robin__map.html).
306
307 ```c++
308 #include <cassert>
309 #include <cstdint>
310 #include <fstream>
311 #include <type_traits>
312 #include <tsl/robin_map.h>
313
314
315 class serializer {
316 public:
317 serializer(const char* file_name) {
318 m_ostream.exceptions(m_ostream.badbit | m_ostream.failbit);
319 m_ostream.open(file_name, std::ios::binary);
320 }
321
322 template<class T,
323 typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
324 void operator()(const T& value) {
325 m_ostream.write(reinterpret_cast<const char*>(&value), sizeof(T));
326 }
327
328 void operator()(const std::pair<std::int64_t, std::int64_t>& value) {
329 (*this)(value.first);
330 (*this)(value.second);
331 }
332
333 private:
334 std::ofstream m_ostream;
335 };
336
337 class deserializer {
338 public:
339 deserializer(const char* file_name) {
340 m_istream.exceptions(m_istream.badbit | m_istream.failbit | m_istream.eofbit);
341 m_istream.open(file_name, std::ios::binary);
342 }
343
344 template<class T>
345 T operator()() {
346 T value;
347 deserialize(value);
348
349 return value;
350 }
351
352 private:
353 template<class T,
354 typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
355 void deserialize(T& value) {
356 m_istream.read(reinterpret_cast<char*>(&value), sizeof(T));
357 }
358
359 void deserialize(std::pair<std::int64_t, std::int64_t>& value) {
360 deserialize(value.first);
361 deserialize(value.second);
362 }
363
364 private:
365 std::ifstream m_istream;
366 };
367
368
369 int main() {
370 const tsl::robin_map<std::int64_t, std::int64_t> map = {{1, -1}, {2, -2}, {3, -3}, {4, -4}};
371
372
373 const char* file_name = "robin_map.data";
374 {
375 serializer serial(file_name);
376 map.serialize(serial);
377 }
378
379 {
380 deserializer dserial(file_name);
381 auto map_deserialized = tsl::robin_map<std::int64_t, std::int64_t>::deserialize(dserial);
382
383 assert(map == map_deserialized);
384 }
385
386 {
387 deserializer dserial(file_name);
388
389 /**
390 * If the serialized and deserialized map are hash compatibles (see conditions in API),
391 * setting the argument to true speed-up the deserialization process as we don't have
392 * to recalculate the hash of each key. We also know how much space each bucket needs.
393 */
394 const bool hash_compatible = true;
395 auto map_deserialized =
396 tsl::robin_map<std::int64_t, std::int64_t>::deserialize(dserial, hash_compatible);
397
398 assert(map == map_deserialized);
399 }
400 }
401 ```
402
403 ##### Serialization with Boost Serialization and compression with zlib
404
405 It is possible to use a serialization library to avoid the boilerplate.
406
407 The following example uses Boost Serialization with the Boost zlib compression stream to reduce the size of the resulting serialized file. The example requires C++20 due to the usage of the template parameter list syntax in lambdas, but it can be adapted to less recent versions.
408
409 ```c++
410 #include <boost/archive/binary_iarchive.hpp>
411 #include <boost/archive/binary_oarchive.hpp>
412 #include <boost/iostreams/filter/zlib.hpp>
413 #include <boost/iostreams/filtering_stream.hpp>
414 #include <boost/serialization/split_free.hpp>
415 #include <boost/serialization/utility.hpp>
416 #include <cassert>
417 #include <cstdint>
418 #include <fstream>
419 #include <tsl/robin_map.h>
420
421
422 namespace boost { namespace serialization {
423 template<class Archive, class Key, class T>
424 void serialize(Archive & ar, tsl::robin_map<Key, T>& map, const unsigned int version) {
425 split_free(ar, map, version);
426 }
427
428 template<class Archive, class Key, class T>
429 void save(Archive & ar, const tsl::robin_map<Key, T>& map, const unsigned int /*version*/) {
430 auto serializer = [&ar](const auto& v) { ar & v; };
431 map.serialize(serializer);
432 }
433
434 template<class Archive, class Key, class T>
435 void load(Archive & ar, tsl::robin_map<Key, T>& map, const unsigned int /*version*/) {
436 auto deserializer = [&ar]<typename U>() { U u; ar & u; return u; };
437 map = tsl::robin_map<Key, T>::deserialize(deserializer);
438 }
439 }}
440
441
442 int main() {
443 tsl::robin_map<std::int64_t, std::int64_t> map = {{1, -1}, {2, -2}, {3, -3}, {4, -4}};
444
445
446 const char* file_name = "robin_map.data";
447 {
448 std::ofstream ofs;
449 ofs.exceptions(ofs.badbit | ofs.failbit);
450 ofs.open(file_name, std::ios::binary);
451
452 boost::iostreams::filtering_ostream fo;
453 fo.push(boost::iostreams::zlib_compressor());
454 fo.push(ofs);
455
456 boost::archive::binary_oarchive oa(fo);
457
458 oa << map;
459 }
460
461 {
462 std::ifstream ifs;
463 ifs.exceptions(ifs.badbit | ifs.failbit | ifs.eofbit);
464 ifs.open(file_name, std::ios::binary);
465
466 boost::iostreams::filtering_istream fi;
467 fi.push(boost::iostreams::zlib_decompressor());
468 fi.push(ifs);
469
470 boost::archive::binary_iarchive ia(fi);
471
472 tsl::robin_map<std::int64_t, std::int64_t> map_deserialized;
473 ia >> map_deserialized;
474
475 assert(map == map_deserialized);
476 }
477 }
478 ```
479
480 #### Performance pitfalls
481
482 Two potential performance pitfalls involving `tsl::robin_map` and
483 `tsl::robin_set` are noteworthy:
484
485 1. *Bad hashes*. Hash functions that produce many collisions can lead to the
486 following surprising behavior: when the number of collisions exceeds a
487 certain threshold, the hash table will automatically expand to fix the
488 problem. However, in degenerate cases, this expansion might have _no effect_
489 on the collision count, causing a failure mode where a linear sequence of
490 insertion leads to exponential storage growth.
491
492 This case has mainly been observed when using the default power-of-two
493 growth strategy with the default STL `std::hash<T>` for arithmetic types
494 `T`, which is often an identity! See issue
495 [#39](https://github.com/Tessil/robin-map/issues/39) for an example. The
496 solution is simple: use a better hash function and/or `tsl::robin_pg_set` /
497 `tsl::robin_pg_map`.
498
499 2. *Element erasure and low load factors*. `tsl::robin_map` and
500 `tsl::robin_set` mirror the STL map/set API, which exposes an `iterator
501 erase(iterator)` method that removes an element at a certain position,
502 returning a valid iterator that points to the next element.
503
504 Constructing this new iterator object requires walking to the next nonempty
505 bucket in the table, which can be a expensive operation when the hash table
506 has a low *load factor* (i.e., when `capacity()` is much larger then
507 `size()`).
508
509 The `erase()` method furthermore never shrinks & re-hashes the table as
510 this is not permitted by the specification of this function. A linear
511 sequence of random removals without intermediate insertions can then lead to
512 a degenerate case with quadratic runtime cost.
513
514 In such cases, an iterator return value is often not even needed, so the
515 cost is entirely unnecessary. Both `tsl::robin_set` and `tsl::robin_map`
516 therefore provide an alternative erasure method `void erase_fast(iterator)`
517 that does not return an iterator to avoid having to find the next element.
518
519 ### License
520
521 The code is licensed under the MIT license, see the [LICENSE file](LICENSE) for details.