-
Notifications
You must be signed in to change notification settings - Fork 0
/
type_map.go
71 lines (62 loc) · 1.2 KB
/
type_map.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
package mtcl
import (
"errors"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
)
type Map map[String]Value
func (m Map) value() {}
func (m Map) Type() string {
return "dict"
}
func (m Map) Expand() Values {
keys := maps.Keys(m)
slices.Sort(keys)
values := make(Values, len(keys))
for i, key := range keys {
ki := i * 2
vi := ki + 1
values[ki], values[vi] = String(key), m[key]
}
return values
}
func (m Map) Len() int {
return len(m)
}
func (m Map) String() string {
items := make([]string, 0, len(m)*2)
for k, v := range m {
items = append(items, string(k), v.String())
}
return strings.Join(items, " ")
}
func (m Map) Iterator() Iterator {
keys := maps.Keys(m)
slices.Sort(keys)
return func(vals Values) (bool, error) {
switch len(vals) {
case 0:
return len(keys) > 0, nil
case 1, 2:
default:
return false, errors.New("map iterator only accepts one or two iterator parameters")
}
for i, key := range keys {
val, ok := m[key]
if !ok {
continue
}
keys = keys[i+1:]
switch len(vals) {
case 2:
vals[0], vals[1] = String(key), val
case 1:
vals[0] = String(key)
}
return true, nil
}
keys = nil
return false, nil
}
}