-
Notifications
You must be signed in to change notification settings - Fork 5
/
memory.go
76 lines (62 loc) · 1.4 KB
/
memory.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
package memory
import (
"context"
"os"
"sort"
"strings"
"sync"
"github.com/PowerDNS/simpleblob"
)
type Backend struct {
mu sync.Mutex
blobs map[string][]byte
}
func (b *Backend) List(ctx context.Context, prefix string) (simpleblob.BlobList, error) {
var blobs simpleblob.BlobList
b.mu.Lock()
for name, data := range b.blobs {
if !strings.HasPrefix(name, prefix) {
continue
}
blobs = append(blobs, simpleblob.Blob{
Name: name,
Size: int64(len(data)),
})
}
b.mu.Unlock()
sort.Sort(blobs)
return blobs, nil
}
func (b *Backend) Load(ctx context.Context, name string) ([]byte, error) {
b.mu.Lock()
data, exists := b.blobs[name]
b.mu.Unlock()
if !exists {
return nil, os.ErrNotExist
}
dataCopy := make([]byte, len(data))
copy(dataCopy, data) // safe, because data was a copy itself
return dataCopy, nil
}
func (b *Backend) Store(ctx context.Context, name string, data []byte) error {
dataCopy := make([]byte, len(data))
copy(dataCopy, data)
b.mu.Lock()
b.blobs[name] = dataCopy
b.mu.Unlock()
return nil
}
func (b *Backend) Delete(ctx context.Context, name string) error {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.blobs, name)
return nil
}
func New() *Backend {
return &Backend{blobs: make(map[string][]byte)}
}
func init() {
simpleblob.RegisterBackend("memory", func(ctx context.Context, p simpleblob.InitParams) (simpleblob.Interface, error) {
return New(), nil
})
}