forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage_inmem.go
90 lines (71 loc) · 1.62 KB
/
storage_inmem.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
package logical
import (
"strings"
"sync"
radix "github.com/armon/go-radix"
)
// InmemStorage implements Storage and stores all data in memory. It is
// basically a straight copy of physical.Inmem, but it prevents backends from
// having to load all of physical's dependencies (which are legion) just to
// have some testing storage.
type InmemStorage struct {
sync.RWMutex
root *radix.Tree
once sync.Once
}
func (s *InmemStorage) Get(key string) (*StorageEntry, error) {
s.once.Do(s.init)
s.RLock()
defer s.RUnlock()
if raw, ok := s.root.Get(key); ok {
se := raw.(*StorageEntry)
return &StorageEntry{
Key: se.Key,
Value: se.Value,
}, nil
}
return nil, nil
}
func (s *InmemStorage) Put(entry *StorageEntry) error {
s.once.Do(s.init)
s.Lock()
defer s.Unlock()
s.root.Insert(entry.Key, &StorageEntry{
Key: entry.Key,
Value: entry.Value,
})
return nil
}
func (s *InmemStorage) Delete(key string) error {
s.once.Do(s.init)
s.Lock()
defer s.Unlock()
s.root.Delete(key)
return nil
}
func (s *InmemStorage) List(prefix string) ([]string, error) {
s.once.Do(s.init)
s.RLock()
defer s.RUnlock()
var out []string
seen := make(map[string]interface{})
walkFn := func(s string, v interface{}) bool {
trimmed := strings.TrimPrefix(s, prefix)
sep := strings.Index(trimmed, "/")
if sep == -1 {
out = append(out, trimmed)
} else {
trimmed = trimmed[:sep+1]
if _, ok := seen[trimmed]; !ok {
out = append(out, trimmed)
seen[trimmed] = struct{}{}
}
}
return false
}
s.root.WalkPrefix(prefix, walkFn)
return out, nil
}
func (s *InmemStorage) init() {
s.root = radix.New()
}