-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstore.go
More file actions
89 lines (68 loc) · 1.4 KB
/
store.go
File metadata and controls
89 lines (68 loc) · 1.4 KB
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
package main
import (
"math/rand"
)
type Store struct {
keyList []string
MAX_KEY_COUNT int64
keyCount int64
currKeyIndex int64
}
type StorePacket struct {
storeOp int
key string
ok bool
}
var storeRequest chan StorePacket
var storeResponse chan StorePacket
func (s *Store) Init() {
s.MAX_KEY_COUNT = 5000000
s.keyList = make([]string, s.MAX_KEY_COUNT)
s.keyCount = 0
s.currKeyIndex = 0
}
func (s *Store) StoreKeeper() {
for {
p := <-storeRequest
switch p.storeOp {
case CREATE:
s.keyList[s.currKeyIndex] = p.key
s.currKeyIndex++
if s.keyCount < s.MAX_KEY_COUNT {
s.keyCount++
}
if s.currKeyIndex == s.MAX_KEY_COUNT {
s.currKeyIndex = s.MAX_KEY_COUNT / 2
}
case READ:
p.key, _ = s.generateValidRandomKey(p.storeOp)
p.ok = true
storeResponse <- p
case DELETE:
var idx int64
p.key, idx = s.generateValidRandomKey(p.storeOp)
s.deleteFromStore(idx)
p.ok = true
storeResponse <- p
}
}
}
func (s *Store) generateValidRandomKey(op int) (key string, index int64) {
key = ""
if s.keyCount == 0 {
return key, 0
}
var i int64
if op == READ {
i = rand.Int63n(s.keyCount)
} else if op == DELETE {
i = s.keyCount/2 + rand.Int63n(s.keyCount/2)
}
key = s.keyList[i]
return key, i
}
func (s *Store) deleteFromStore(index int64) {
s.keyList[index] = s.keyList[s.keyCount-1]
s.keyCount--
s.currKeyIndex = s.keyCount
}