/
nestedmaps.go
73 lines (60 loc) · 1.1 KB
/
nestedmaps.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
package nestedmaps
type next[NK comparable, M ~map[NK]NV, NV any] struct {
last Path[M]
key NK
}
func (me next[NK, CV, NV]) Exists() bool {
_, ok := me.last.Get()[me.key]
return ok
}
func (me next[NK, CV, NV]) Get() NV {
return me.last.Get()[me.key]
}
func (me next[NK, CV, NV]) Set(value NV) {
if me.last.Get() == nil {
me.last.Set(make(CV))
}
me.last.Get()[me.key] = value
}
func (me next[NK, CV, NV]) Delete() {
m := me.last.Get()
delete(m, me.key)
if len(m) == 0 {
me.last.Delete()
}
}
func Next[K comparable, M ~map[K]V, V any](
last Path[M],
key K,
) Path[V] {
ret := next[K, M, V]{}
ret.last = last
ret.key = key
return ret
}
type root[K comparable, V any, M ~map[K]V] struct {
m *M
}
func (me root[K, V, M]) Exists() bool {
return *me.m != nil
}
func (me root[K, V, M]) Get() M {
return *me.m
}
func (me root[K, V, M]) Set(value M) {
*me.m = value
}
func (me root[K, V, M]) Delete() {
*me.m = nil
}
func Begin[K comparable, M ~map[K]V, V any](m *M) Path[M] {
ret := root[K, V, M]{}
ret.m = m
return ret
}
type Path[V any] interface {
Set(V)
Get() V
Exists() bool
Delete()
}