summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/multiprecision/example/hashing_examples.cpp
blob: a0c3fb508a2071fcd107cd152c31806ef7f792bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
///////////////////////////////////////////////////////////////
//  Copyright 2012 John Maddock. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/random.hpp>
#include <boost/functional/hash.hpp>
#include <unordered_set>
#include <city.h>

//[hash1

/*`
All of the types in this library support hashing via boost::hash or std::hash.
That means we can use multiprecision types directly in hashed containers such as std::unordered_set:
*/
//]

void t1()
{
   //[hash2
   using namespace boost::multiprecision;
   using namespace boost::random;

   mt19937 mt;
   uniform_int_distribution<uint256_t> ui;

   std::unordered_set<uint256_t> set;
   // Put 1000 random values into the container:
   for(unsigned i = 0; i < 1000; ++i)
      set.insert(ui(mt));

   //]
}

//[hash3

/*` 
Or we can define our own hash function, for example in this case based on
Google's CityHash:
*/

struct cityhash
{
   std::size_t operator()(const boost::multiprecision::uint256_t& val)const
   {
      // create a hash from all the limbs of the argument, this function is probably x64 specific,
      // and requires that we access the internals of the data type:
      std::size_t result = CityHash64(reinterpret_cast<const char*>(val.backend().limbs()), val.backend().size() * sizeof(val.backend().limbs()[0]));
      // modify the returned hash based on sign:
      return val < 0 ? ~result : result;
   }
};

//]

void t2()
{
//[hash4

/*`As before insert some values into a container, this time using our custom hasher:*/

   std::unordered_set<uint256_t, cityhash> set2;
   for(unsigned i = 0; i < 1000; ++i)
      set2.insert(ui(mt));

//]
}

int main()
{
   t1();
   t2();
   return 0;
}