Loading...
Searching...
No Matches
hashingUtils.hpp
Go to the documentation of this file.
1/*---------------------------------------------------------------------------*\
2 *
3 * bitpit
4 *
5 * Copyright (C) 2015-2021 OPTIMAD engineering Srl
6 *
7 * -------------------------------------------------------------------------
8 * License
9 * This file is part of bitpit.
10 *
11 * bitpit is free software: you can redistribute it and/or modify it
12 * under the terms of the GNU Lesser General Public License v3 (LGPL)
13 * as published by the Free Software Foundation.
14 *
15 * bitpit is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18 * License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with bitpit. If not, see <http://www.gnu.org/licenses/>.
22 *
23\*---------------------------------------------------------------------------*/
24
25#ifndef __BITPIT_HASHING_UTILS_HPP__
26#define __BITPIT_HASHING_UTILS_HPP__
27
30#include <functional>
31#include <tuple>
32
33namespace bitpit {
34
35namespace utils {
36
42namespace hashing {
43
44namespace
45{
46 // Code from boost
47 // Reciprocal of the golden ratio helps spread entropy
48 // and handles duplicates.
49 // See Mike Seymour in magic-numbers-in-boosthash-combine:
50 // http://stackoverflow.com/questions/4948780
51
52 template <class T>
53 inline void hash_combine(std::size_t& seed, T const& v)
54 {
55 seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
56 }
57
58 // Recursive template code derived from Matthieu M.
59 template <class Tuple, size_t Index = std::tuple_size<Tuple>::value - 1>
60 struct HashValueImpl
61 {
62 static void apply(size_t & seed, Tuple const & tuple)
63 {
64 HashValueImpl<Tuple, Index-1>::apply(seed, tuple);
65 hash_combine(seed, std::get<Index>(tuple));
66 }
67 };
68
69 template <class Tuple>
70 struct HashValueImpl<Tuple,0>
71 {
72 static void apply(size_t & seed, Tuple const & tuple)
73 {
74 hash_combine(seed, std::get<0>(tuple));
75 }
76 };
77}
78
79template <typename TT>
80struct hash
81{
82 size_t
83 operator()(TT const& tt) const
84 {
85 return std::hash<TT>()(tt);
86 }
87};
88
89template <typename ... TT>
90struct hash<std::tuple<TT...>>
91{
92 size_t
93 operator()(std::tuple<TT...> const & tt) const
94 {
95 size_t seed = 0;
96 HashValueImpl<std::tuple<TT...> >::apply(seed, tt);
97 return seed;
98 }
99};
100
101template <typename T, typename U>
102struct hash<std::pair<T, U>>
103{
104 size_t
105 operator()(std::pair<T, U> const &value) const
106 {
107 std::size_t seed = 0;
108 hash_combine(seed, value.first);
109 hash_combine(seed, value.second);
110 return seed;
111 }
112};
113
114}
115
116}
117
118}
119
120#endif
--- layout: doxygen_footer ---