-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.go
More file actions
70 lines (58 loc) · 1.22 KB
/
methods.go
File metadata and controls
70 lines (58 loc) · 1.22 KB
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
package kvdb
import (
. "github.com/tinywasm/fmt"
)
func (t *TinyDB) Get(key string) (string, error) {
t.mu.RLock()
defer t.mu.RUnlock()
for _, p := range t.data {
if p.Key == key {
return p.Value, nil
}
}
return "", Err("key not found: ", key)
}
func (t *TinyDB) Set(key, value string) error {
t.mu.Lock()
defer t.mu.Unlock()
// search if it exists
for i, p := range t.data {
if p.Key == key {
t.data[i].Value = value
// update requires full persist
return t.persist()
}
}
// insert new
newPair := pair{Key: key, Value: value}
t.data = append(t.data, newPair)
return t.append(newPair)
}
func (t *TinyDB) append(p pair) error {
t.raw.Reset()
t.raw.Write(p.Key)
t.raw.Write("=")
t.raw.Write(p.Value)
t.raw.Write("\n")
if err := t.store.AddToFile(t.name, t.raw.Bytes()); err != nil {
// log only on error
t.log("error appending:", err.Error())
return err
}
return nil
}
func (t *TinyDB) persist() error {
t.raw.Reset()
for _, p := range t.data {
t.raw.Write(p.Key)
t.raw.Write("=")
t.raw.Write(p.Value)
t.raw.Write("\n")
}
if err := t.store.SetFile(t.name, t.raw.Bytes()); err != nil {
// log only on error
t.log("error persisting:", err.Error())
return err
}
return nil
}