-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (70 loc) · 1.91 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"os"
"sync"
)
// maximum size of the KVS
var CAPACITY = 1000
// thread safe and goroutine safe are assumed to be interchangable here.
// https://groups.google.com/g/golang-nuts/c/ZA0IK1k6UVk
// Theoretically, goroutine safe concurrency === thread safe concurrency
type KVS[V any] []*Node[V]
type ConcurrentKVS[V any] struct {
kvs KVS[V]
// https://pkg.go.dev/sync#RWMutex
// Can be held by arbitrary # of readers, single writer.
Mu sync.RWMutex
// for edge-triggered persistence: persist if conditional evaluates to true
cond func(kvs *KVS[V]) bool
}
type Node[V any] struct {
key string
value V
}
// Instantiate new concurrent map
func New[V any](f func(*KVS[V]) bool) *ConcurrentKVS[V] {
m := make([]*Node[V], CAPACITY)
return &ConcurrentKVS[V]{kvs: m, cond: f}
}
func (m *ConcurrentKVS[V]) Get(key string) V {
m.Mu.RLock()
defer m.Mu.RUnlock()
index := hashFunction(key)
return m.kvs[index].value
}
func (m *ConcurrentKVS[V]) Put(key string, value V) error {
m.Mu.Lock()
defer m.Mu.Unlock()
index := hashFunction(key)
// search for collision first
// fix: just fails, no resolution path here?
if m.kvs[index] != nil {
return fmt.Errorf("collision at index %d when trying to put key %s", index, key)
}
m.kvs[index] = &Node[V]{key, value}
// Persist to disk on every put if conditional is met
if m.cond(&m.kvs) {
m.Persist()
}
return nil
}
func (m *ConcurrentKVS[V]) Persist() error {
b, err := json.MarshalIndent(m.kvs, " ", " ")
if err != nil {
return fmt.Errorf("%v: could not marshal key-value store to json", err)
}
os.WriteFile("kvs.json", b, 0o644)
return nil
}
// Collisions are a potential issue with modular hashing.
// Can use linked lists or a better hashing function?
func hashFunction(in string) int {
var ret int
for i := 0; i < len(in); i++ {
// 31 is what java uses :)
ret = (31*ret + int(in[i])) % CAPACITY
}
return ret
}