aboutsummaryrefslogtreecommitdiff
path: root/include/odhtdb/Hash.hpp
blob: 05e85d2027300e3bbc04e3382de90bc5dabbe65e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#pragma once

#include "utils.hpp"
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>

namespace odhtdb
{
    const int HASH_BYTE_SIZE = 32;
    
    // Source: https://stackoverflow.com/a/11414104 (public license)
    static size_t fnvHash(const unsigned char *key, int len)
    {
        size_t h = 2166136261;
        for (int i = 0; i < len; i++)
            h = (h * 16777619) ^ key[i];
        return h;
    }
    
    class HashException : public std::runtime_error
    {
    public:
        HashException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    // Uses blake2b to hash input
    class Hash
    {
    public:
        Hash();
        // Throws HashException on failure
        Hash(const void *input, const size_t inputSize);
        Hash(const Hash &other);
        
        void* getData() const { return (void*)data; }
        size_t getSize() const { return HASH_BYTE_SIZE; }
        
        size_t operator()() const;
        bool operator==(const Hash &other) const;
        bool operator!=(const Hash &other) const;
        
        bool isEmpty() const;
        
        std::string toString() const;
    private:
        char data[HASH_BYTE_SIZE];
    };
    
    struct HashHasher
    {
        size_t operator()(const Hash &hash) const
        {
            return hash();
        }
    };
    
    template <typename ValueType>
    using MapHash = std::unordered_map<Hash, ValueType, HashHasher>;
    
    using SetHash = std::unordered_set<Hash, HashHasher>;
}