-
Notifications
You must be signed in to change notification settings - Fork 1
/
inmemory.go
73 lines (62 loc) · 1.76 KB
/
inmemory.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
package database
import (
"fmt"
"sync"
"github.com/ovcharovvladimir/essentiaHybrid/common"
"github.com/ovcharovvladimir/essentiaHybrid/essdb"
"github.com/sirupsen/logrus"
)
var log = logrus.WithField("prefix", "db")
// KVStore is an in-memory mapping of hashes to RLP encoded values.
type KVStore struct {
kv map[common.Hash][]byte
lock sync.RWMutex
}
// NewKVStore creates an in-memory, key-value store.
func NewKVStore() *KVStore {
return &KVStore{kv: make(map[common.Hash][]byte)}
}
// Get fetches a val from the mappping by key.
func (s *KVStore) Get(k []byte) ([]byte, error) {
s.lock.RLock()
defer s.lock.RUnlock()
v, ok := s.kv[common.BytesToHash(k)]
if !ok {
return []byte{}, fmt.Errorf("key not found: %v", k)
}
return v, nil
}
// Has checks if the key exists in the mapping.
func (s *KVStore) Has(k []byte) (bool, error) {
s.lock.RLock()
defer s.lock.RUnlock()
v := s.kv[common.BytesToHash(k)]
return v != nil, nil
}
// Put updates a key's value in the mapping.
func (s *KVStore) Put(k []byte, v []byte) error {
s.lock.Lock()
defer s.lock.Unlock()
// there is no error in a simple setting of a value in a go map.
s.kv[common.BytesToHash(k)] = v
return nil
}
// Delete removes the key and value from the mapping.
func (s *KVStore) Delete(k []byte) error {
s.lock.Lock()
defer s.lock.Unlock()
// There is no return value for deleting a simple key in a go map.
delete(s.kv, common.BytesToHash(k))
return nil
}
// Close satisfies essdb.Database.
func (s *KVStore) Close() {
//TODO: Implement Close for KVStore
log.Debug("ShardKV Close() isnt implemented yet")
}
// NewBatch satisfies essdb.Database.
func (s *KVStore) NewBatch() essdb.Batch {
//TODO: Implement NewBatch for KVStore
log.Debug("ShardKV NewBatch() isnt implemented yet")
return nil
}