LeechCraft  0.6.70-15082-g543737046d
Modular cross-platform feature rich live environment.
statichash.h
Go to the documentation of this file.
1 /**********************************************************************
2  * LeechCraft - modular cross-platform feature rich internet client.
3  * Copyright (C) 2006-2014 Georg Rudoy
4  *
5  * Distributed under the Boost Software License, Version 1.0.
6  * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7  **********************************************************************/
8 
9 #pragma once
10 
11 #include <string_view>
12 
13 namespace LC::Util
14 {
15  namespace
16  {
17  template<typename K, typename V>
18  struct KVPair
19  {
20  const K Key_;
21  const V Val_;
22 
23  consteval KVPair (K name, V val)
24  : Key_ { name }
25  , Val_ { val }
26  {
27  }
28  };
29 
30  template<size_t N, typename V>
31  KVPair (const char (&) [N], V) -> KVPair<std::string_view, V>;
32  }
33 
34  template<typename K>
35  constexpr uint64_t DefaultHashImpl (K);
36 
37  template<>
38  constexpr uint64_t DefaultHashImpl (std::string_view name)
39  {
40  uint64_t res = 0;
41  for (auto ch : name)
42  res = (res << 8) + ch;
43  return res;
44  }
45 
46  template<std::convertible_to<uint64_t> K>
47  constexpr uint64_t DefaultHashImpl (K val)
48  {
49  return static_cast<uint64_t> (val);
50  }
51 
52  constexpr uint64_t DefaultHash (auto val)
53  {
54  return DefaultHashImpl (val);
55  }
56 
57  template<typename K, typename V, auto Hasher = DefaultHash<K>>
58  consteval auto MakeHash (auto&&... commands)
59  {
60  const std::initializer_list<KVPair<K, V>> commandsList { commands... };
61  for (auto i = commandsList.begin (); i != std::prev (commandsList.end ()); ++i)
62  for (auto j = std::next (i); j != commandsList.end (); ++j)
63  if (Hasher (i->Key_) == Hasher (j->Key_))
64  throw "duplicate hashes";
65 
66  return [=] (K key, V defValue = V {})
67  {
68  const auto keyHash = Hasher (key);
69  V result = defValue;
70  K foundKey {};
71  (void) ((Hasher (commands.Key_) == keyHash && (result = commands.Val_, foundKey = commands.Key_, true)) || ...);
72  if (foundKey != key)
73  return defValue;
74  return result;
75  };
76  }
77 
78  template<typename V>
79  consteval auto MakeStringHash (auto&&... commands)
80  {
81  return MakeHash<std::string_view, V> (std::forward<decltype (commands)> (commands)...);
82  }
83 }
LC::Util::MakeHash
consteval auto MakeHash(auto &&... commands)
Definition: statichash.h:64
LC::Util
Definition: icoreproxy.h:33
Key_
const K Key_
Definition: statichash.h:38
LC::Util::MakeStringHash
consteval auto MakeStringHash(auto &&... commands)
Definition: statichash.h:85
LC::Util::DefaultHashImpl
constexpr uint64_t DefaultHashImpl(K)
Definition: statichash.h:53
LC::Util::DefaultHash
constexpr uint64_t DefaultHash(auto val)
Definition: statichash.h:58
Val_
const V Val_
Definition: statichash.h:39