/
index.go
55 lines (44 loc) · 1016 Bytes
/
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
package util
import (
"fmt"
"sync"
)
type Index struct {
data map[string]string
lock *sync.RWMutex
}
func NewIndex() *Index {
return &Index{data: make(map[string]string), lock: &sync.RWMutex{}}
}
func (idx *Index) Add(key, value string) error {
if key == "" {
return fmt.Errorf("BUG: Invalid empty index key")
}
if value == "" {
return fmt.Errorf("BUG: Invalid empty index value")
}
idx.lock.Lock()
defer idx.lock.Unlock()
if oldValue, exists := idx.data[key]; exists {
if oldValue != value {
return fmt.Errorf("BUG: Conflict when updating index, %v was mapped to %v, but %v want to be mapped too", key, oldValue, value)
}
return nil
}
idx.data[key] = value
return nil
}
func (idx *Index) Delete(key string) error {
if key == "" {
return fmt.Errorf("BUG: Invalid empty index key")
}
idx.lock.Lock()
defer idx.lock.Unlock()
delete(idx.data, key)
return nil
}
func (idx *Index) Get(key string) string {
idx.lock.RLock()
defer idx.lock.RUnlock()
return idx.data[key]
}