-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinmemory.go
More file actions
61 lines (48 loc) · 964 Bytes
/
inmemory.go
File metadata and controls
61 lines (48 loc) · 964 Bytes
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
package dht
import (
"errors"
"sync"
)
//go:generate mockgen -destination mock_kv_test.go -package nameserver . kv
type kv interface {
get(string) ([]byte, error)
set(string, []byte) error
}
var (
errKeyNotFound = errors.New("key not found")
errKeyExists = errors.New("key exists")
)
type inmemory struct {
mu sync.RWMutex
values map[string][]byte
}
// interface compliance
var _ kv = (*inmemory)(nil)
func newInmemoryStore() kv {
return &inmemory{
mu: sync.RWMutex{},
values: make(map[string][]byte),
}
}
func (k *inmemory) get(key string) ([]byte, error) {
k.mu.RLock()
defer k.mu.RUnlock()
value, ok := k.values[key]
if !ok {
return nil, errKeyNotFound
}
return value, nil
}
func (k *inmemory) set(key string, value []byte) error {
if value == nil {
return errors.New("nil value")
}
k.mu.Lock()
defer k.mu.Unlock()
_, ok := k.values[key]
if ok {
return errKeyExists
}
k.values[key] = value
return nil
}