-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperhash.go
90 lines (81 loc) · 1.38 KB
/
superhash.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
package superhash
import (
"sync"
)
type Node struct {
key interface{}
value interface{}
children map[interface{}]*Node
}
func newNode() (n *Node) {
n = &Node{}
n.children = make(map[interface{}]*Node)
return
}
type SuperHash struct {
root *Node
mutex *sync.Mutex
}
func New() (s *SuperHash) {
s = &SuperHash{
root: newNode(),
mutex: &sync.Mutex{},
}
return
}
func (s *SuperHash) Set(kv ...interface{}) bool {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(kv) < 2 {
return false
}
keys := kv[:len(kv)-1]
value := kv[len(kv)-1:][0]
cn := s.root
for _, key := range keys {
if n, ok := cn.children[key]; ok {
cn = n
} else {
n := newNode()
n.key = key
cn.children[key] = n
cn = n
}
}
cn.value = value
return true
}
func (s *SuperHash) Get(keys ...interface{}) interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(keys) < 1 {
return nil
}
cn := s.root
for _, key := range keys {
if n, ok := cn.children[key]; ok {
cn = n
} else {
return nil
}
}
return cn.value
}
func (s *SuperHash) Delete(keys ...interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(keys) < 1 {
return
}
cn := s.root
deletePath(cn, keys...)
}
func deletePath(parent *Node, keys ...interface{}) {
if len(keys) == 0 {
return
}
if n, ok := parent.children[keys[0]]; ok {
deletePath(n, keys[1:]...)
}
delete(parent.children, keys[0])
}