/
hashmap.go
95 lines (81 loc) · 2.1 KB
/
hashmap.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
91
92
93
94
95
// MIT License
// Copyright (c) 2022 Brian Reece
package hashmap
import (
"hash/maphash"
"github.com/bdreece/gollections/errors"
"github.com/bdreece/gollections/iterator"
"github.com/bdreece/gollections/vector"
)
// MapPair is a key-value pair for the HashMap
// structure
type MapPair[K, V any] struct {
Key K
Val V
}
// HashMap is a hash map data structure,
// using hash/maphash for key hashing.
type HashMap[K comparable, V any] struct {
*vector.Vector[map[K]V]
maphash.Hash
loadFactor float32
}
// New constructs a new HashMap
func New[K comparable, V any](loadFactor float32, capacity int) *HashMap[K, V] {
vec := vector.New[map[K]V]()
vec.Reserve(5)
iterator.ForEach(vec.IntoIterator(), func(bucket *map[K]V) {
*bucket = make(map[K]V)
})
return &HashMap[K, V]{
vec,
maphash.Hash{},
loadFactor,
}
}
func (m *HashMap[K, V]) hash(key K) int {
bytes := any(key).([]byte)
m.Hash.Write(bytes)
return int(m.Hash.Sum64()) % len(*m.Vector)
}
// Get retrieves the value associated with a specified
// key. Returns nil, errors.NotFound if key does not
// exist.
func (m HashMap[K, V]) Get(key K) (*V, error) {
hash := m.hash(key)
bucket, err := m.Vector.Get(hash)
if err != nil {
return nil, err
}
val, ok := (*bucket)[key]
if !ok {
return nil, errors.NotFound[K]{Key: key}
}
return &val, nil
}
// Set inserts a key value pair into the hash map,
// overwriting the value if the key already exists.
// Returns error on vector error.
func (m *HashMap[K, V]) Set(key K, val V) error {
hash := m.hash(key)
bucket, err := m.Vector.Get(hash)
if err != nil {
return err
}
(*bucket)[key] = val
return nil
}
// Collect inserts a variable number of key-value pairs
// into the hash map. This method implements part of the
// iterator.Collection interface.
func (m *HashMap[K, V]) Collect(pairs ...MapPair[K, V]) {
for _, pair := range pairs {
m.Set(pair.Key, pair.Val)
}
}
// Iterator returns an iterator over the key-value pairs
// in the hash map. This method implements part of the
// iterator.Collection interface.
func (m *HashMap[K, V]) Iterator() *Iterator[K, V] {
return &Iterator[K, V]{m}
}