-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
util.go
96 lines (82 loc) · 1.63 KB
/
util.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
96
package linq
import "errors"
func isEOC(err error) bool {
return errors.Is(err, EOC)
}
func isOutOfRange(err error) bool {
return errors.Is(err, OutOfRange)
}
func isInvalidOperation(err error) bool {
return errors.Is(err, InvalidOperation)
}
type hashMap[H comparable, V any] struct {
m map[H][]V
hash func(V) (H, error)
eq func(V, V) (bool, error)
}
func newHashMap[H comparable, V any](hash func(V) (H, error), eq func(V, V) (bool, error)) *hashMap[H, V] {
return &hashMap[H, V]{
m: make(map[H][]V),
hash: hash,
eq: eq,
}
}
func newKeyMap[K comparable, V any](ks func(V) (K, error)) *hashMap[K, V] {
return newHashMap(ks, alwaysEqual[V])
}
func alwaysEqual[T any](_, _ T) (bool, error) {
return true, nil
}
func alwaysNotEqual[T any](_, _ T) (bool, error) {
return false, nil
}
func (hm *hashMap[H, V]) gets(h H) []V {
return hm.m[h]
}
func (hm *hashMap[H, V]) has(v V) (bool, error) {
h, err := hm.hash(v)
if err != nil {
return false, err
}
for _, u := range hm.m[h] {
eq, err := hm.eq(u, v)
if err != nil {
return false, err
}
if eq {
return true, nil
}
}
return false, nil
}
func (hm *hashMap[H, V]) add(v V) (bool, error) {
h, err := hm.hash(v)
if err != nil {
return false, err
}
for _, u := range hm.m[h] {
eq, err := hm.eq(u, v)
if err != nil {
return false, err
}
if eq {
return false, nil
}
}
hm.m[h] = append(hm.m[h], v)
return true, nil
}
func (hm *hashMap[H, V]) addAll(e Enumerator[V]) error {
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return nil
}
return err
}
if _, err = hm.add(v); err != nil {
return err
}
}
}