This repository has been archived by the owner on Nov 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
memory.go
79 lines (62 loc) · 1.35 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
77
78
79
package store
import (
"sync"
"github.com/domodwyer/cryptic/encryptor"
)
type rwLocker interface {
sync.Locker
RLock()
RUnlock()
}
// Memory is an in-memory data store. Contents are not persisted in any way
// after the process ends.
type Memory struct {
secrets map[string]encryptor.EncryptedData
mu rwLocker
}
// NewMemory returns an initalised memory store.
func NewMemory() *Memory {
return &Memory{
secrets: map[string]encryptor.EncryptedData{},
mu: &sync.RWMutex{},
}
}
// Put stores data under the given name.
func (s *Memory) Put(name string, data *encryptor.EncryptedData) error {
if name == "" {
return ErrInvalidName
}
if _, err := s.Get(name); err != ErrNotFound {
return ErrAlreadyExists
}
s.mu.Lock()
defer s.mu.Unlock()
s.secrets[name] = *data
return nil
}
// Get fetches the EncryptedData stored under name.
func (s *Memory) Get(name string) (*encryptor.EncryptedData, error) {
if name == "" {
return nil, ErrInvalidName
}
s.mu.RLock()
defer s.mu.RUnlock()
d, ok := s.secrets[name]
if !ok {
return nil, ErrNotFound
}
return &d, nil
}
// Delete removes a secret from the memory store.
func (s *Memory) Delete(name string) error {
if name == "" {
return ErrInvalidName
}
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.secrets[name]; !ok {
return ErrNotFound
}
delete(s.secrets, name)
return nil
}