-
Notifications
You must be signed in to change notification settings - Fork 67
/
map.go
132 lines (122 loc) · 2.24 KB
/
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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package core
import (
"bytes"
"fmt"
"io"
)
type (
Map interface {
Associative
Seqable
Counted
Without(key Object) Map
Keys() Seq
Vals() Seq
Merge(m Map) Map
Iter() MapIterator
}
MapIterator interface {
HasNext() bool
Next() *Pair
}
EmptyMapIterator struct {
}
Pair struct {
Key Object
Value Object
}
)
var (
emptyMapIterator = &EmptyMapIterator{}
)
func (iter *EmptyMapIterator) HasNext() bool {
return false
}
func (iter *EmptyMapIterator) Next() *Pair {
panic(newIteratorError())
}
func mapConj(m Map, obj Object) Conjable {
switch obj := obj.(type) {
case *Vector:
if obj.count != 2 {
panic(RT.NewError("Vector argument to map's conj must be a vector with two elements"))
}
return m.Assoc(obj.at(0), obj.at(1))
case Map:
return m.Merge(obj)
default:
panic(RT.NewError("Argument to map's conj must be a vector with two elements or a map"))
}
}
func mapEquals(m Map, other interface{}) bool {
if m == other {
return true
}
switch otherMap := other.(type) {
case Nil:
return false
case Map:
if m.Count() != otherMap.Count() {
return false
}
for iter := m.Iter(); iter.HasNext(); {
p := iter.Next()
success, value := otherMap.Get(p.Key)
if !success || !value.Equals(p.Value) {
return false
}
}
return true
default:
return false
}
}
func mapToString(m Map, escape bool) string {
var b bytes.Buffer
b.WriteRune('{')
if m.Count() > 0 {
for iter := m.Iter(); ; {
p := iter.Next()
b.WriteString(p.Key.ToString(escape))
b.WriteRune(' ')
b.WriteString(p.Value.ToString(escape))
if iter.HasNext() {
b.WriteString(", ")
} else {
break
}
}
}
b.WriteRune('}')
return b.String()
}
func callMap(m Map, args []Object) Object {
CheckArity(args, 1, 2)
if ok, v := m.Get(args[0]); ok {
return v
}
if len(args) == 2 {
return args[1]
}
return NIL
}
func pprintMap(m Map, w io.Writer, indent int) int {
i := indent + 1
fmt.Fprint(w, "{")
if m.Count() > 0 {
for iter := m.Iter(); ; {
p := iter.Next()
i = pprintObject(p.Key, indent+1, w)
fmt.Fprint(w, " ")
i = pprintObject(p.Value, i+1, w)
if iter.HasNext() {
fmt.Fprint(w, "\n")
writeIndent(w, indent+1)
} else {
break
}
}
}
fmt.Fprint(w, "}")
return i + 1
}