forked from keys-pub/keys-ext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.go
115 lines (101 loc) · 1.91 KB
/
mem.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package vault
import (
"sort"
"strings"
"github.com/pkg/errors"
)
// NewMem returns an in memory Store useful for testing or ephemeral keys.
func NewMem() Store {
return &mem{
entries: map[string][]byte{},
}
}
type mem struct {
open bool
entries map[string][]byte
}
func (m *mem) Name() string {
return "mem"
}
func (m *mem) Open() error {
if m.open {
return ErrAlreadyOpen
}
m.open = true
return nil
}
func (m *mem) Close() error {
m.open = false
return nil
}
func (m *mem) Reset() error {
m.entries = map[string][]byte{}
return nil
}
func (m *mem) Get(path string) ([]byte, error) {
if !m.open {
return nil, ErrNotOpen
}
if path == "" {
return nil, errors.Errorf("invalid path")
}
if b, ok := m.entries[path]; ok {
return b, nil
}
return nil, nil
}
func (m *mem) Set(path string, b []byte) error {
if !m.open {
return ErrNotOpen
}
if path == "" {
return errors.Errorf("invalid path")
}
m.entries[path] = b
return nil
}
func (m *mem) Exists(path string) (bool, error) {
if !m.open {
return false, ErrNotOpen
}
if path == "" {
return false, errors.Errorf("invalid path")
}
_, ok := m.entries[path]
return ok, nil
}
func (m *mem) Delete(path string) (bool, error) {
if !m.open {
return false, ErrNotOpen
}
if path == "" {
return false, errors.Errorf("invalid path")
}
if _, ok := m.entries[path]; ok {
delete(m.entries, path)
return true, nil
}
return false, nil
}
func (m *mem) List(opts *ListOptions) ([]*Entry, error) {
if !m.open {
return nil, ErrNotOpen
}
if opts == nil {
opts = &ListOptions{}
}
prefix := opts.Prefix
out := make([]*Entry, 0, len(m.entries))
for path, b := range m.entries {
if strings.HasPrefix(path, prefix) {
out = append(out, &Entry{Path: path, Data: b})
}
}
sort.Slice(out, func(i, j int) bool {
return out[i].Path < out[j].Path
})
if opts.Limit > 0 && len(out) > opts.Limit {
out = out[:opts.Limit]
}
return out, nil
}