Dynalib Utils
HashCoder.h
Go to the documentation of this file.
1 //
2 // Created by Ken Kopelson on 20/10/17.
3 //
4 
5 #ifndef HASHCODER_H
6 #define HASHCODER_H
7 
8 #include <string>
9 #include "TypeDefs.h"
10 
11 namespace hashc {
12  const int HASH_SEED = 5381; // Starting point for first cycle
13  const int HASH_MULTIPLIER = 33; // Multiplier for each cycle
14  const unsigned HASH_MASK = unsigned(-1) >> 1u; // All 1 bits except the sign
15 
16  int hashSeed();
17  int hashMultiplier();
18  int hashMask();
19 
20  int hashCode(bool key);
21  int hashCode(char key);
22  int hashCode(double key);
23  int hashCode(float key);
24  int hashCode(int key);
25  int hashCode(long key);
26  int hashCode(long long key);
27  int hashCode(const char* str);
28  int hashCode(const std::string& str);
29  int hashCode(void* key);
30 
31  int getInitialCode();
32  int getFinalCode(int code);
33 
34  template <class T> int add(int code, T value) {
35  code += hashCode(value);
36  code *= hashMultiplier();
37  return code;
38  }
39 }
40 
41 class HashCoder {
42 
43  int _hashCode;
44 
45 public:
46 
47  explicit HashCoder(int seed) : _hashCode(seed) {
48  }
49 
51  }
52 
53  template <class T> void add(T value) {
54  _hashCode += hashc::hashCode(value);
55  _hashCode *= hashc::hashMultiplier();
56  }
57 
58  void init(int seed) {
59  _hashCode = seed;
60  }
61 
62  void init() {
63  init(hashc::HASH_SEED);
64  }
65 
66  int getCode() {
67  return hashc::getFinalCode(_hashCode);
68  }
69 };
70 
71 
72 #endif //HASHCODER_H
const unsigned HASH_MASK
Definition: HashCoder.h:14
void init(int seed)
Definition: HashCoder.h:58
const int HASH_MULTIPLIER
Definition: HashCoder.h:13
HashCoder()
Definition: HashCoder.h:50
Definition: HashCoder.h:41
int getInitialCode()
Definition: HashCoder.cpp:19
GeneratorWrapper< T > value(T &&value)
Definition: catch.hpp:4005
int hashSeed()
Definition: HashCoder.cpp:7
const int HASH_SEED
Definition: HashCoder.h:12
int hashMultiplier()
Definition: HashCoder.cpp:11
void add(T value)
Definition: HashCoder.h:53
return os str()
void init()
Definition: HashCoder.h:62
int add(int code, T value)
Definition: HashCoder.h:34
Definition: HashCoder.h:11
int getCode()
Definition: HashCoder.h:66
int hashMask()
Definition: HashCoder.cpp:15
int getFinalCode(int code)
Definition: HashCoder.cpp:23
HashCoder(int seed)
Definition: HashCoder.h:47
int hashCode(bool key)
Definition: HashCoder.cpp:27