generated from mpppk/cli-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
72 lines (59 loc) · 1.47 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
package storage
import (
"context"
"sync"
"github.com/mpppk/iroha/ktkn"
)
type MemoryCache struct {
m map[string][][]*ktkn.Word
mut *sync.RWMutex
}
func newMemoryCache() *MemoryCache {
return &MemoryCache{
m: map[string][][]*ktkn.Word{},
mut: new(sync.RWMutex),
}
}
func (mc MemoryCache) Get(key string) ([][]*ktkn.Word, bool) {
mc.mut.RLock()
wordsList, ok := mc.m[key]
mc.mut.RUnlock()
return wordsList, ok
}
func (mc MemoryCache) Set(key string, wordsList [][]*ktkn.Word) {
mc.mut.Lock()
mc.m[key] = wordsList
mc.mut.Unlock()
}
type Memory struct {
cache *MemoryCache
otherStorage Storage
}
func NewMemory() *Memory {
return &Memory{
otherStorage: &None{},
cache: newMemoryCache(),
}
}
func NewMemoryWithOtherStorage(storage Storage) *Memory {
m := NewMemory()
m.otherStorage = storage
return m
}
func (m *Memory) ResetProgress(ctx context.Context) error {
return m.otherStorage.ResetProgress(ctx)
}
func (m *Memory) Start(ctx context.Context, indices []int) error {
return m.otherStorage.Start(ctx, indices)
}
func (m *Memory) Set(ctx context.Context, indices []int, wordsList [][]*ktkn.Word) error {
m.cache.Set(toStorageStrKey(indices), wordsList)
return m.otherStorage.Set(ctx, indices, wordsList)
}
func (m *Memory) Get(ctx context.Context, indices []int) ([][]*ktkn.Word, bool, error) {
wordsList, ok := m.cache.Get(toStorageStrKey(indices))
if ok {
return wordsList, true, nil
}
return m.otherStorage.Get(ctx, indices)
}