OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_HASH_UTIL_H_ |
| 6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_HASH_UTIL_H_ |
| 7 |
| 8 #include <cstring> |
| 9 #include <functional> |
| 10 #include <type_traits> |
| 11 #include <vector> |
| 12 |
| 13 #include "mojo/public/cpp/bindings/lib/template_util.h" |
| 14 |
| 15 namespace mojo { |
| 16 namespace internal { |
| 17 |
| 18 template <typename T> |
| 19 size_t HashCombine(size_t seed, const T& value) { |
| 20 // Based on proposal in: |
| 21 // http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf |
| 22 return seed ^ (std::hash<T>()(value) + (seed << 6) + (seed >> 2)); |
| 23 } |
| 24 |
| 25 template <typename T> |
| 26 struct HasHashMethod { |
| 27 template <typename U> |
| 28 static char Test(decltype(&U::Hash)); |
| 29 template <typename U> |
| 30 static int Test(...); |
| 31 static const bool value = sizeof(Test<T>(0)) == sizeof(char); |
| 32 |
| 33 private: |
| 34 EnsureTypeIsComplete<T> check_t_; |
| 35 }; |
| 36 |
| 37 template <typename T, bool has_hash_method = HasHashMethod<T>::value> |
| 38 struct HashTraits; |
| 39 |
| 40 template <typename T> |
| 41 size_t Hash(size_t seed, const T& value); |
| 42 |
| 43 template <typename T> |
| 44 struct HashTraits<T, true> { |
| 45 static size_t Hash(size_t seed, const T& value) { return value.Hash(seed); } |
| 46 }; |
| 47 |
| 48 template <typename T> |
| 49 struct HashTraits<T, false> { |
| 50 static size_t Hash(size_t seed, const T& value) { |
| 51 return HashCombine(seed, value); |
| 52 } |
| 53 }; |
| 54 |
| 55 template <typename T> |
| 56 struct HashTraits<std::vector<T>, false> { |
| 57 static size_t Hash(size_t seed, const std::vector<T>& value) { |
| 58 for (const auto& element : value) { |
| 59 seed = HashCombine(seed, element); |
| 60 } |
| 61 return seed; |
| 62 } |
| 63 }; |
| 64 |
| 65 template <typename T> |
| 66 size_t Hash(size_t seed, const T& value) { |
| 67 return HashTraits<T>::Hash(seed, value); |
| 68 } |
| 69 |
| 70 } // namespace internal |
| 71 } // namespace mojo |
| 72 |
| 73 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_HASH_UTIL_H_ |
OLD | NEW |