-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathvalues.go
101 lines (83 loc) · 1.6 KB
/
values.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
97
98
99
100
101
package multimap
import (
"github.com/zyedidia/generic/avl"
"golang.org/x/exp/slices"
)
type valuesContainer[V any] interface {
Empty() bool
Size() int
Put(value V) int
Remove(value V) int
List() []V
Each(fn func(value V))
}
var (
_ valuesContainer[int] = valuesSet[int]{}
_ valuesContainer[int] = (*valuesSlice[int])(nil)
)
type valuesSet[V any] struct {
t *avl.Tree[V, struct{}]
}
func (vs valuesSet[V]) Empty() bool {
return vs.t.Height() == 0
}
func (vs valuesSet[V]) Size() int {
return vs.t.Size()
}
func (vs valuesSet[V]) has(value V) bool {
_, ok := vs.t.Get(value)
return ok
}
func (vs valuesSet[V]) Put(value V) int {
if vs.has(value) {
return 0
}
vs.t.Put(value, struct{}{})
return 1
}
func (vs valuesSet[V]) Remove(value V) int {
if !vs.has(value) {
return 0
}
vs.t.Remove(value)
return 1
}
func (vs valuesSet[V]) List() (values []V) {
vs.Each(func(value V) {
values = append(values, value)
})
return
}
func (vs valuesSet[V]) Each(fn func(value V)) {
vs.t.Each(func(value V, _ struct{}) {
fn(value)
})
}
type valuesSlice[V comparable] []V
func (vs *valuesSlice[V]) Empty() bool {
return len(*vs) == 0
}
func (vs *valuesSlice[V]) Size() int {
return len(*vs)
}
func (vs *valuesSlice[V]) Put(value V) int {
*vs = append(*vs, value)
return 1
}
func (vs *valuesSlice[V]) Remove(value V) int {
i := slices.Index(*vs, value)
if i < 0 {
return 0
}
(*vs)[i] = (*vs)[len(*vs)-1]
*vs = (*vs)[:len(*vs)-1]
return 1
}
func (vs *valuesSlice[V]) List() []V {
return *vs
}
func (vs *valuesSlice[V]) Each(fn func(value V)) {
for _, value := range *vs {
fn(value)
}
}