/
memory.go
65 lines (54 loc) · 1.25 KB
/
memory.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
package stores
import (
"fmt"
"sync"
)
var _ Store = (*memoryStore)(nil)
type memoryStore struct {
memory map[string][]byte
mtx *sync.RWMutex
}
func NewMemoryStore() *memoryStore {
return &memoryStore{
memory: make(map[string][]byte),
mtx: new(sync.RWMutex),
}
}
func (inv *memoryStore) Put(address []byte, data []byte) ([]byte, error) {
inv.mtx.Lock()
inv.memory[string(address)] = data
inv.mtx.Unlock()
return address, nil
}
func (inv *memoryStore) Delete(address []byte) error {
inv.mtx.Lock()
inv.memory[string(address)] = nil
inv.mtx.Unlock()
return nil
}
func (inv *memoryStore) Get(address []byte) ([]byte, error) {
data, exists := inv.get(address)
if !exists {
return nil, ErrorAddressNotFound(address)
}
return data, nil
}
func (inv *memoryStore) Stat(address []byte) (*StatInfo, error) {
data, exists := inv.get(address)
return &StatInfo{
Exists: exists,
Size_: uint64(len(data)),
}, nil
}
func (inv *memoryStore) Location(address []byte) string {
return fmt.Sprintf("memfs://%x", address)
}
func (inv *memoryStore) Name() string {
return "memoryStore"
}
func (inv *memoryStore) get(address []byte) ([]byte, bool) {
inv.mtx.RLock()
data, exists := inv.memory[string(address)]
inv.mtx.RUnlock()
return data, exists
}