PolyFEM
Loading...
Searching...
No Matches
HashUtils.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef> // size_t
4#include <array>
5#include <vector>
6
7namespace polyfem::utils
8{
9 struct HashPair
10 {
11 template <typename T1, typename T2>
12 size_t operator()(const std::pair<T1, T2> &p) const noexcept
13 {
14 auto hash1 = std::hash<T1>{}(p.first);
15 auto hash2 = std::hash<T2>{}(p.second);
16 if (hash1 != hash2)
17 return hash1 ^ hash2;
18 // If hash1 == hash2, their XOR is zero.
19 return hash1;
20 }
21 };
22
23 template <>
24 inline size_t HashPair::operator()<int, int>(const std::pair<int, int> &p) const noexcept
25 {
26 size_t h = (size_t(p.first) << 32) + size_t(p.second);
27 h *= 1231231557ull; // "random" uneven integer
28 h ^= (h >> 32);
29 return h;
30 }
31
33 template <typename T, int N>
35 {
36 size_t operator()(std::array<T, N> v) const noexcept
37 {
38 std::sort(v.begin(), v.end()); // Sort the array to make the order irrelevant.
39 std::hash<T> hasher;
40 size_t hash = 0;
41 for (int i : v)
42 hash ^= hasher(i) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
43 return hash;
44 }
45 };
46
47 template <typename T, int N>
49 {
50 bool operator()(std::array<T, N> v1, std::array<T, N> v2) const noexcept
51 {
52 // Sort the array to make the order irrelevant.
53 std::sort(v1.begin(), v1.end());
54 std::sort(v2.begin(), v2.end());
55 return v1 == v2;
56 }
57 };
58
60 {
61 template <typename T>
62 size_t operator()(const std::vector<T> &v) const
63 {
64 std::hash<T> hasher;
65 size_t hash = 0;
66 for (int i : v)
67 hash ^= hasher(i) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
68 return hash;
69 }
70 };
71
72 // https://github.com/ethz-asl/map_api/blob/master/map-api-common/include/map-api-common/eigen-hash.h
74 {
75 // https://wjngkoh.wordpress.com/2015/03/04/c-hash-function-for-eigen-matrix-and-vector/
76 template <typename Scalar, int Rows, int Cols>
77 size_t operator()(const Eigen::Matrix<Scalar, Rows, Cols> &matrix) const
78 {
79 size_t seed = 0;
80 for (size_t i = 0; i < matrix.size(); ++i)
81 {
82 Scalar elem = *(matrix.data() + i);
83 seed ^=
84 std::hash<Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
85 }
86 return seed;
87 }
88 };
89
90} // namespace polyfem::utils
bool operator()(std::array< T, N > v1, std::array< T, N > v2) const noexcept
Definition HashUtils.hpp:50
size_t operator()(const Eigen::Matrix< Scalar, Rows, Cols > &matrix) const
Definition HashUtils.hpp:77
size_t operator()(const std::pair< T1, T2 > &p) const noexcept
Definition HashUtils.hpp:12
Hash function for an array where the order does not matter.
Definition HashUtils.hpp:35
size_t operator()(std::array< T, N > v) const noexcept
Definition HashUtils.hpp:36
size_t operator()(const std::vector< T > &v) const
Definition HashUtils.hpp:62