forked from celestiaorg/smt
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmapstore.go
57 lines (48 loc) · 1.23 KB
/
mapstore.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
package smt
import (
"fmt"
)
// MapStore is a key-value store.
type MapStore interface {
Get(key []byte) ([]byte, error) // Get gets the value for a key.
Set(key []byte, value []byte) error // Set updates the value for a key.
Delete(key []byte) error // Delete deletes a key.
}
// InvalidKeyError is thrown when a key that does not exist is being accessed.
type InvalidKeyError struct {
Key []byte
}
func (e *InvalidKeyError) Error() string {
return fmt.Sprintf("invalid key: %x", e.Key)
}
// SimpleMap is a simple in-memory map.
type SimpleMap struct {
m map[string][]byte
}
// NewSimpleMap creates a new empty SimpleMap.
func NewSimpleMap() *SimpleMap {
return &SimpleMap{
m: make(map[string][]byte),
}
}
// Get gets the value for a key.
func (sm *SimpleMap) Get(key []byte) ([]byte, error) {
if value, ok := sm.m[string(key)]; ok {
return value, nil
}
return nil, &InvalidKeyError{Key: key}
}
// Set updates the value for a key.
func (sm *SimpleMap) Set(key []byte, value []byte) error {
sm.m[string(key)] = value
return nil
}
// Delete deletes a key.
func (sm *SimpleMap) Delete(key []byte) error {
_, ok := sm.m[string(key)]
if ok {
delete(sm.m, string(key))
return nil
}
return &InvalidKeyError{Key: key}
}