-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtkvs.go
94 lines (84 loc) · 1.6 KB
/
tkvs.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
// Trivial Key Value Store with Json Backend
package tkvs
import (
"context"
"encoding/json"
"io"
"log"
"os"
)
type KeyVal map[string][]byte
type Container struct {
KeyVal `json:"keyval"`
}
func (j *TKVS) readJson() error {
j.Lock()
defer j.Unlock()
j.file.Seek(0, 0)
buf, err := io.ReadAll(j.file)
if err != nil {
return err
}
if len(buf) == 0 {
j.kvs = make(KeyVal)
return nil
}
c := Container{}
if err = json.Unmarshal(buf, &c); err != nil {
return err
}
j.kvs = c.KeyVal
return nil
}
func (j *TKVS) writeJson() error {
j.Lock()
defer j.Unlock()
c := Container{KeyVal: j.kvs}
out, err := json.Marshal(&c)
if err != nil {
return err
}
j.file.Seek(0, 0)
j.file.Truncate(0)
_, err = j.file.Write(out)
return err
}
func (j *TKVS) Get(_ context.Context, key string) ([]byte, error) {
val, ok := j.kvs[key]
if !ok {
return nil, j.misErr
}
return val, nil
}
func (j *TKVS) Put(_ context.Context, key string, data []byte) error {
j.kvs[key] = data
return j.writeJson()
}
func (j *TKVS) Delete(_ context.Context, key string) error {
delete(j.kvs, key)
return j.writeJson()
}
func (j *TKVS) Keys() []string {
s := []string{}
for n := range j.kvs {
s = append(s, n)
}
return s
}
func New(path string, misErr error) *TKVS {
k := &TKVS{misErr: misErr}
err := k.fsLock(path)
if err != nil {
log.Fatalf("unable to lock %q: %v", path, err)
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
log.Fatalf("unable to open %q: %v", path, err)
}
k.file = f
err = k.readJson()
if err != nil {
log.Fatalf("unable to read %q: %v", path, err)
}
return k
}