1 /*
2 * Copyright 2014 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef FRUIT_HASH_CODES_DEFN_H
18 #define FRUIT_HASH_CODES_DEFN_H
19
20 #include <fruit/impl/util/hash_codes.h>
21
22 namespace fruit {
23 namespace impl {
24
25 template <typename Tuple, int index>
hashTupleElement(const Tuple & x)26 inline std::size_t hashTupleElement(const Tuple& x) {
27 const auto& value = std::get<index>(x);
28 using T = typename std::remove_const<typename std::remove_reference<decltype(value)>::type>::type;
29 return std::hash<T>()(value);
30 }
31
32 template <typename Tuple, int last_index>
33 struct HashTupleHelper;
34
35 template <int last_index>
36 struct HashTupleHelper<std::tuple<>, last_index> {
37 std::size_t operator()(const std::tuple<>&) {
38 return 0;
39 }
40 };
41
42 template <typename... Args>
43 struct HashTupleHelper<std::tuple<Args...>, 1> {
44 std::size_t operator()(const std::tuple<Args...>& x) {
45 return hashTupleElement<std::tuple<Args...>, 0>(x);
46 }
47 };
48
49 template <typename... Args, int last_index>
50 struct HashTupleHelper<std::tuple<Args...>, last_index> {
51 std::size_t operator()(const std::tuple<Args...>& x) {
52 return combineHashes(hashTupleElement<std::tuple<Args...>, last_index - 1>(x),
53 HashTupleHelper<std::tuple<Args...>, last_index - 1>()(x));
54 }
55 };
56
57 template <typename... Args>
58 inline std::size_t hashTuple(const std::tuple<Args...>& x) {
59 return HashTupleHelper<std::tuple<Args...>, sizeof...(Args)>()(x);
60 }
61
62 inline std::size_t combineHashes(std::size_t h1, std::size_t h2) {
63 h1 ^= h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2);
64 return h1;
65 }
66
67 } // namespace impl
68 } // namespace fruit
69
70 #endif // FRUIT_HASH_CODES_DEFN_H
71