-
Notifications
You must be signed in to change notification settings - Fork 1
/
map_backend.go
51 lines (44 loc) · 1.14 KB
/
map_backend.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
package bstore
import (
"encoding/hex"
"errors"
)
// MapBackend implements a key-value store backed by a simple map
type MapBackend struct {
storage map[string][]byte
}
// NewMapBackend creates and returns a reference to a map backend instance
func NewMapBackend() *MapBackend {
return &MapBackend{make(map[string][]byte)}
}
// Reset resets the database
func (backend *MapBackend) Reset() error {
backend.storage = make(map[string][]byte)
return nil
}
// Put adds the requested value to the database
func (backend *MapBackend) Put(key []byte, value []byte) error {
if key == nil {
return errors.New("Cannot put a nil value key")
}
if value == nil {
return errors.New("Cannot put a nil value")
}
k := hex.EncodeToString(key)
//fmt.Println("Putting key:", k)
backend.storage[k] = value
return nil
}
// Get fetches the requested value from the database
func (backend *MapBackend) Get(key []byte) ([]byte, error) {
if len(key) == 0 {
return nil, errors.New("Key cannot be empty")
}
k := hex.EncodeToString(key)
//fmt.Println("Getting key:", k)
val, ok := backend.storage[k]
if ok {
return val, nil
}
return make([]byte, 0), nil
}