-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.go
More file actions
47 lines (35 loc) · 780 Bytes
/
Copy pathmemory.go
File metadata and controls
47 lines (35 loc) · 780 Bytes
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
package kvsync
import (
"fmt"
"reflect"
"sync"
)
// InMemoryStore is an in-memory implementation of KVStore
type InMemoryStore struct {
Store map[string]any
mutex sync.Mutex
}
func copyFields(val interface{}, dest interface{}) error {
vVal := reflect.ValueOf(val)
vDest := reflect.ValueOf(dest)
vDest = vDest.Elem()
for i := 0; i < vDest.NumField(); i++ {
vDest.Field(i).Set(vVal.Field(i))
}
return nil
}
func (m *InMemoryStore) Fetch(key string, dest any) error {
m.mutex.Lock()
defer m.mutex.Unlock()
val, ok := m.Store[key]
if !ok {
return fmt.Errorf("key %s not found", key)
}
return copyFields(val, dest)
}
func (m *InMemoryStore) Put(key string, value any) error {
m.mutex.Lock()
defer m.mutex.Unlock()
m.Store[key] = value
return nil
}