-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.go
70 lines (53 loc) · 1.15 KB
/
hashtable.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
package properties
import "sync"
type Hashtable interface {
New() Hashtable
Put(key, value interface{}) interface{}
Get(key interface{}) interface{}
Remove(key interface{})
Size() int
Keys() []interface{}
}
type hashtable struct {
mutex sync.RWMutex
mapper map[interface{}]interface{}
}
func NewHashtable() Hashtable {
return &hashtable{
mapper: map[interface{}]interface{}{},
}
}
func (h *hashtable) New() Hashtable {
return NewHashtable()
}
func (h *hashtable) Put(key, value interface{}) interface{} {
h.mutex.Lock()
defer h.mutex.Unlock()
var old = h.mapper[key]
h.mapper[key] = value
return old
}
func (h *hashtable) Get(key interface{}) interface{} {
h.mutex.RLock()
defer h.mutex.RUnlock()
return h.mapper[key]
}
func (h *hashtable) Remove(key interface{}) {
h.mutex.Lock()
defer h.mutex.Unlock()
delete(h.mapper, key)
}
func (h *hashtable) Size() int {
h.mutex.RLock()
defer h.mutex.RUnlock()
return len(h.mapper)
}
func (h *hashtable) Keys() []interface{} {
h.mutex.Lock()
defer h.mutex.Unlock()
var keys = make([]interface{}, 0, len(h.mapper))
for key := range h.mapper {
keys = append(keys, key)
}
return keys
}