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
|
package dict
import (
"iter"
"slices"
)
type Entry[V any] struct {
Key string
Val V
}
type Dict[V any] struct {
s []Entry[V]
m map[string]int
}
func NewDict[V any]() *Dict[V] {
return &Dict[V]{
s: make([]Entry[V], 0),
m: make(map[string]int),
}
}
func (d *Dict[V]) Len() int {
return len(d.s)
}
func (d *Dict[V]) Set(key string, val V) {
if i, ok := d.m[key]; ok {
d.s[i].Val = val
return
}
d.s = append(d.s, Entry[V]{
Key: key,
Val: val,
})
d.m[key] = len(d.s) - 1
}
func (d *Dict[V]) Get(key string) (V, bool) {
i, ok := d.m[key]
if !ok {
var zero V
return zero, false
}
return d.s[i].Val, true
}
func (d *Dict[V]) GetBytes(key []byte) (V, bool) {
if i, ok := d.m[string(key)]; ok {
return d.s[i].Val, true
}
var zero V
return zero, false
}
func (d *Dict[V]) Values() iter.Seq2[int, V] {
return func(yield func(int, V) bool) {
for i, entry := range d.s {
if !yield(i, entry.Val) {
return
}
}
}
}
func (d *Dict[V]) Sort(cmp func(a, b Entry[V]) int) {
slices.SortFunc(d.s, cmp)
for i, entry := range d.s {
d.m[entry.Key] = i
}
}
// func CmpKey[V any](a, b Entry[V]) int {
// return strings.Compare(a.Key, b.Key)
// }
// func CmpVal[V cmp.Ordered](a, b Entry[V]) int {
// return cmp.Compare(a.Val, b.Val)
// }
|