forked from elves/elvish
/
map.go
70 lines (61 loc) · 1.49 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
package types
import (
"github.com/xiaq/persistent/hashmap"
)
type mapIterable interface {
Iterator() hashmap.Iterator
}
type mapAssocable interface {
Assoc(k, v interface{}) hashmap.Map
}
type mapDissocable interface {
Without(interface{}) hashmap.Map
}
var (
_ mapIterable = hashmap.Map(nil)
_ Getter = hashmap.Map(nil)
_ mapAssocable = hashmap.Map(nil)
_ mapDissocable = hashmap.Map(nil)
)
// EmptyMap is an empty map.
var EmptyMap = hashmap.New(Equal, Hash)
// MakeMap converts a native Go map to Map.
func MakeMap(raw map[interface{}]interface{}) hashmap.Map {
m := EmptyMap
for k, v := range raw {
m = m.Assoc(k, v)
}
return m
}
// MakeMapFromKV creates a map from arguments that are alternately keys and
// values. It panics if the number of arguments is odd.
func MakeMapFromKV(a ...interface{}) hashmap.Map {
if len(a)%2 == 1 {
panic("Odd number of arguments to MakeMapFromKV")
}
m := EmptyMap
for i := 0; i < len(a); i += 2 {
m = m.Assoc(a[i], a[i+1])
}
return m
}
// MapReprBuilder helps building the Repr of a Map. It is also useful for
// implementing other Map-like values. The zero value of a MapReprBuilder is
// ready to use.
type MapReprBuilder struct {
ListReprBuilder
}
func (b *MapReprBuilder) WritePair(k string, indent int, v string) {
if indent > 0 {
b.WriteElem("&" + k + "=\t" + v)
} else {
b.WriteElem("&" + k + "=" + v)
}
}
func (b *MapReprBuilder) String() string {
s := b.ListReprBuilder.String()
if s == "[]" {
s = "[&]"
}
return s
}