-
Notifications
You must be signed in to change notification settings - Fork 198
/
memDbMock.go
119 lines (93 loc) · 2.43 KB
/
memDbMock.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package mock
import (
"encoding/base64"
"errors"
"fmt"
"sync"
)
// MemDbMock represents the memory database storage. It holds a map of key value pairs
// and a mutex to handle concurrent accesses to the map
type MemDbMock struct {
db map[string][]byte
mutx sync.RWMutex
}
// NewMemDbMock creates a new memorydb object
func NewMemDbMock() *MemDbMock {
return &MemDbMock{
db: make(map[string][]byte),
mutx: sync.RWMutex{},
}
}
// Put adds the value to the (key, val) storage medium
func (s *MemDbMock) Put(key, val []byte) error {
s.mutx.Lock()
defer s.mutx.Unlock()
s.db[string(key)] = val
return nil
}
// Get gets the value associated to the key, or reports an error
func (s *MemDbMock) Get(key []byte) ([]byte, error) {
s.mutx.RLock()
defer s.mutx.RUnlock()
val, ok := s.db[string(key)]
if !ok {
return nil, fmt.Errorf("key: %s not found", base64.StdEncoding.EncodeToString(key))
}
return val, nil
}
// Has returns true if the given key is present in the persistence medium, false otherwise
func (s *MemDbMock) Has(key []byte) error {
s.mutx.RLock()
defer s.mutx.RUnlock()
_, ok := s.db[string(key)]
if !ok {
return errors.New("key not present")
}
return nil
}
// Init initializes the storage medium and prepares it for usage
func (s *MemDbMock) Init() error {
// no special initialization needed
return nil
}
// Close closes the files/resources associated to the storage medium
func (s *MemDbMock) Close() error {
// nothing to do
return nil
}
// Remove removes the data associated to the given key
func (s *MemDbMock) Remove(key []byte) error {
s.mutx.Lock()
defer s.mutx.Unlock()
delete(s.db, string(key))
return nil
}
// Destroy removes the storage medium stored data
func (s *MemDbMock) Destroy() error {
s.mutx.Lock()
defer s.mutx.Unlock()
s.db = make(map[string][]byte)
return nil
}
// DestroyClosed removes the already closed storage medium stored data
func (s *MemDbMock) DestroyClosed() error {
return nil
}
// RangeKeys will iterate over all contained (key, value) pairs calling the handler for each pair
func (s *MemDbMock) RangeKeys(handler func(key []byte, value []byte) bool) {
if handler == nil {
return
}
s.mutx.RLock()
defer s.mutx.RUnlock()
for k, v := range s.db {
shouldContinue := handler([]byte(k), v)
if !shouldContinue {
return
}
}
}
// IsInterfaceNil returns true if there is no value under the interface
func (s *MemDbMock) IsInterfaceNil() bool {
return s == nil
}