-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.go
86 lines (70 loc) · 1.83 KB
/
index.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 indexmap
import (
"github.com/yah01/container"
)
type PrimaryIndex[K comparable, V any] struct {
extractField func(value *V) K
inner map[K]*V
}
// Create an primary index,
// the extractField func must guarantee it makes the index one-to-one.
func NewPrimaryIndex[K comparable, V any](extractField func(value *V) K) *PrimaryIndex[K, V] {
return &PrimaryIndex[K, V]{
extractField: extractField,
inner: make(map[K]*V),
}
}
func (index *PrimaryIndex[K, V]) get(key K) *V {
return index.inner[key]
}
func (index *PrimaryIndex[K, V]) insert(elem *V) {
index.inner[index.extractField(elem)] = elem
}
func (index *PrimaryIndex[K, V]) remove(key K) {
delete(index.inner, key)
}
func (index *PrimaryIndex[K, V]) iterate(handler func(key K, value *V)) {
for key, value := range index.inner {
handler(key, value)
}
}
type SecondaryIndex[V any] struct {
extractField func(value *V) []any
inner map[any]container.Set[*V]
}
// Create a secondary index,
// the extractField func returns the keys for seeking the value,
// It's OK that the same key seeks more than one values.
func NewSecondaryIndex[V any](extractField func(value *V) []any) *SecondaryIndex[V] {
return &SecondaryIndex[V]{
extractField: extractField,
inner: make(map[any]container.Set[*V]),
}
}
func (index *SecondaryIndex[V]) get(key any) container.Set[*V] {
set, ok := index.inner[key]
if !ok {
return nil
}
return set
}
func (index *SecondaryIndex[V]) insert(elem *V) {
keys := index.extractField(elem)
for i := range keys {
elems, ok := index.inner[keys[i]]
if !ok {
elems = make(container.Set[*V])
index.inner[keys[i]] = elems
}
elems.Insert(elem)
}
}
func (index *SecondaryIndex[V]) remove(elem *V) {
keys := index.extractField(elem)
for i := range keys {
elems, ok := index.inner[keys[i]]
if ok {
elems.Remove(elem)
}
}
}