This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightstore.go
117 lines (91 loc) · 2.18 KB
/
lightstore.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package lightstore
import (
"sync"
)
type Index struct {
Fn func(interface{}) []interface{}
Name string
Unique bool
data map[interface{}][]interface{}
mu sync.Mutex
}
type LightStore struct {
indexes map[string]*Index
data []interface{}
mu sync.Mutex
}
func NewStore() *LightStore {
return &LightStore{
indexes: make(map[string]*Index),
data: make([]interface{}, 0),
}
}
func rm(haystack []interface{}, needle interface{}) []interface{} {
found := -1
for i, v := range haystack {
if v == needle {
found = i
break
}
}
if found == -1 {
return haystack
}
return append(haystack[:found], haystack[found+1:]...)
}
func (l *LightStore) DefineIndex(indexDefinition *Index) {
l.mu.Lock()
defer l.mu.Unlock()
l.indexes[indexDefinition.Name] = indexDefinition
}
func (l *LightStore) AddRecord(r interface{}) {
l.mu.Lock()
l.data = append(l.data, r)
l.mu.Unlock()
ch := make(chan bool, len(l.indexes))
for _, index := range l.indexes {
index := index
go func() {
index.mu.Lock()
defer index.mu.Unlock()
if index.data == nil {
index.data = make(map[interface{}][]interface{})
}
indexKeys := index.Fn(r)
for _, indexKey := range indexKeys {
if index.Unique == true || index.data[indexKey] == nil {
index.data[indexKey] = []interface{}{r}
} else {
index.data[indexKey] = append(index.data[indexKey], r)
}
}
ch <- true
}()
}
<-ch
}
func (l *LightStore) RemoveRecord(r interface{}) {
l.mu.Lock()
l.data = rm(l.data, r)
l.mu.Unlock()
for _, index := range l.indexes {
indexKeys := index.Fn(r)
for _, indexKey := range indexKeys {
if index.data[indexKey] != nil {
index.mu.Lock()
index.data[indexKey] = rm(index.data[indexKey], r)
index.mu.Unlock()
}
}
}
}
func (l *LightStore) Query(indexName string, key interface{}) []interface{} {
index := l.indexes[indexName]
if index.data == nil || index.data[key] == nil {
return make([]interface{}, 0)
}
return index.data[key]
}
func (l *LightStore) Data() []interface{} {
return l.data
}