-
Notifications
You must be signed in to change notification settings - Fork 4
/
simplemap.go
75 lines (63 loc) · 1.56 KB
/
simplemap.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
63
64
65
66
67
68
69
70
71
72
73
74
75
package simplemap
import (
"github.com/pokt-network/smt/kvstore"
)
// Ensure that the SimpleMap can be used as an SMT node store
var _ kvstore.MapStore = (*simpleMap)(nil)
// simpleMap is a simple in-memory map.
type simpleMap struct {
m map[string][]byte
}
// NewSimpleMap creates a new SimpleMap instance.
func NewSimpleMap() kvstore.MapStore {
return &simpleMap{
m: make(map[string][]byte),
}
}
// NewSimpleMap creates a new SimpleMap instance using the map provided.
// This is useful for testing & debugging purposes.
func NewSimpleMapWithMap(m map[string][]byte) kvstore.MapStore {
return &simpleMap{
m: m,
}
}
// Get gets the value for a key.
func (sm *simpleMap) Get(key []byte) ([]byte, error) {
if len(key) == 0 {
return nil, ErrKVStoreEmptyKey
}
if value, ok := sm.m[string(key)]; ok {
return value, nil
}
return nil, ErrKVStoreKeyNotFound
}
// Set updates the value for a key.
func (sm *simpleMap) Set(key []byte, value []byte) error {
if len(key) == 0 {
return ErrKVStoreEmptyKey
}
sm.m[string(key)] = value
return nil
}
// Delete deletes a key.
func (sm *simpleMap) Delete(key []byte) error {
if len(key) == 0 {
return ErrKVStoreEmptyKey
}
_, ok := sm.m[string(key)]
if ok {
delete(sm.m, string(key))
return nil
}
return nil
}
// Len returns the number of key-value pairs in the store.
func (sm *simpleMap) Len() (int, error) {
return len(sm.m), nil
}
// ClearAll clears all key-value pairs
// NB: This should only be used for testing purposes.
func (sm *simpleMap) ClearAll() error {
sm.m = make(map[string][]byte)
return nil
}