-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
67 lines (59 loc) · 1.17 KB
/
hash.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
package hashmap
import (
"errors"
)
type entry struct {
key int
obj interface{}
}
const tableSize = 1024
type entries []entry
// HashMap is the structure to store and retrive key value pairs
type HashMap struct {
table []entries
}
// New creates a new hash map
func New() *HashMap {
return &HashMap{
table: make([]entries, tableSize),
}
}
// Get will return an value from a key. If the hash entry can not be found
// or the entry is not present, then an error is returned.
func (h *HashMap) Get(k int) (interface{}, error) {
idx := k & 0x3FF
list := h.table[idx]
switch len(list) {
case 0:
return nil, errors.New("hash map: unable to find entry")
default:
for _, en := range list {
if en.key == k {
return en.obj, nil
}
}
}
return nil, errors.New("hash map: key was not found in list")
}
// Put will place an key value pair into the hash map
func (h *HashMap) Put(k int, v interface{}) error {
e := entry{
key: k,
obj: v,
}
idx := k & 0x3FF
list := h.table[idx]
found := false
for i, en := range list {
if en.key == k {
list[i] = e
found = true
break
}
}
if found == false {
list = append(list, e)
}
h.table[idx] = list
return nil
}