-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
62 lines (52 loc) · 1.11 KB
/
store.go
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
package main
import (
"bytes"
"encoding/json"
"errors"
)
type kvStore struct {
content map[string]string
}
func newKvStore() *kvStore {
return &kvStore{make(map[string]string)}
}
func (s *kvStore) Put(key, val string) error {
hashedKey := hash(key)
s.content[string(hashedKey)] = val
return nil
}
func (s *kvStore) Get(key string) (string, error) {
hashedKey := hash(key)
v, ok := s.content[string(hashedKey)]
if !ok {
return "", errors.New("Key not found")
}
return v, nil
}
func (s *kvStore) Delete(key string) error {
hashedKey := hash(key)
_, ok := s.content[string(hashedKey)]
if !ok {
return errors.New("Key not found")
}
delete(s.content, string(hashedKey))
return nil
}
func (s *kvStore) TransferKeys(from, to *remoteNode) {
for k, v := range s.content {
hashedKey := hash(k)
if between(hashedKey, from.Id, to.Id) || bytes.Compare(hashedKey, to.Id) == 1 {
to.PutRemote(k, v)
}
}
}
func (s *kvStore) DeleteAll() {
for k := range s.content {
delete(s.content, k)
}
}
func (s *kvStore) Marshal() string {
data, err := json.Marshal(s.content)
checkErrPanic(err)
return string(data)
}