forked from ioriiod0/consistent_hash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consistent_hash_map.hpp
92 lines (63 loc) · 1.79 KB
/
consistent_hash_map.hpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <map>
#include <string>
#include <list>
#include <functional>
#include <algorithm>
#ifndef __CONSISTENT_HASH_H__
#define __CONSISTENT_HASH_H__
template <typename T,
typename Hash,
typename Alloc = std::allocator<std::pair<const typename Hash::result_type,T > > >
class consistent_hash_map
{
public:
typedef typename Hash::result_type size_type;
typedef std::map<size_type,T,std::less<size_type>,Alloc> map_type;
typedef typename map_type::value_type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename map_type::iterator iterator;
typedef typename map_type::reverse_iterator reverse_iterator;
typedef Alloc allocator_type;
public:
consistent_hash_map() {
}
~consistent_hash_map() {
}
public:
std::size_t size() const {
return nodes_.size();
}
bool empty() const {
return nodes_.empty();
}
std::pair<iterator,bool> insert(const T& node) {
size_type hash = hasher_(node);
return nodes_.insert(value_type(hash,node));
}
void erase(iterator it) {
nodes_.erase(it);
}
std::size_t erase(const T& node) {
size_type hash = hasher_(node);
return nodes_.erase(hash);
}
iterator find(size_type hash) {
if(nodes_.empty()) {
return nodes_.end();
}
iterator it = nodes_.lower_bound(hash);
if (it == nodes_.end()) {
it = nodes_.begin();
}
return it;
}
iterator begin() { return nodes_.begin(); }
iterator end() { return nodes_.end(); }
reverse_iterator rbegin() { return nodes_.rbegin(); }
reverse_iterator rend() { return nodes_.rend(); }
private:
Hash hasher_;
map_type nodes_;
};
#endif