aboutsummaryrefslogtreecommitdiff
path: root/include/Key.hpp
blob: f7a600b0eae71f0234cbe792b74f77e73458dfb1 (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
#pragma once

#include <opendht/infohash.h>
#include <unordered_map>

namespace odhtdb
{
    class Key
    {
    public:
        Key() {}
        Key(const char *key) : hashedKey(dht::InfoHash::get(key)) {}
        
        dht::InfoHash hashedKey;
    };
    
    // Source: https://stackoverflow.com/a/11414104 (public license)
    static unsigned int fnvHash(const unsigned char *key, int len)
    {
        unsigned int h = 2166136261;
        for (int i = 0; i < len; i++)
            h = (h * 16777619) ^ key[i];
        return h;
    }
    
    struct KeyHash
    {
        size_t operator()(const Key &key) const
        {
            return fnvHash(key.hashedKey.data(), key.hashedKey.size());
        }
    };
    
    struct KeyCompare
    {
        bool operator()(const Key &lhs, const Key &rhs) const
        {
            return lhs.hashedKey == rhs.hashedKey;
        }
    };
    
    template <typename ValueType>
    using KeyMap = std::unordered_map<Key, ValueType, KeyHash, KeyCompare>;
}