github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/vals/map.go (about) 1 package vals 2 3 import ( 4 "github.com/u-root/u-root/cmds/core/elvish/hashmap" 5 ) 6 7 type mapIterable interface { 8 Iterator() hashmap.Iterator 9 } 10 type mapAssocable interface { 11 Assoc(k, v interface{}) hashmap.Map 12 } 13 type mapDissocable interface { 14 Dissoc(interface{}) hashmap.Map 15 } 16 17 var ( 18 _ mapIterable = hashmap.Map(nil) 19 _ Indexer = hashmap.Map(nil) 20 _ mapAssocable = hashmap.Map(nil) 21 _ mapDissocable = hashmap.Map(nil) 22 ) 23 24 // EmptyMap is an empty map. 25 var EmptyMap = hashmap.New(Equal, Hash) 26 27 // MakeMap converts a native Go map to Map. 28 func MakeMap(raw map[interface{}]interface{}) hashmap.Map { 29 m := EmptyMap 30 for k, v := range raw { 31 m = m.Assoc(k, v) 32 } 33 return m 34 } 35 36 // MakeMapFromKV creates a map from arguments that are alternately keys and 37 // values. It panics if the number of arguments is odd. 38 func MakeMapFromKV(a ...interface{}) hashmap.Map { 39 if len(a)%2 == 1 { 40 panic("Odd number of arguments to MakeMapFromKV") 41 } 42 m := EmptyMap 43 for i := 0; i < len(a); i += 2 { 44 m = m.Assoc(a[i], a[i+1]) 45 } 46 return m 47 } 48 49 // MapReprBuilder helps building the Repr of a Map. It is also useful for 50 // implementing other Map-like values. The zero value of a MapReprBuilder is 51 // ready to use. 52 type MapReprBuilder struct { 53 ListReprBuilder 54 } 55 56 func (b *MapReprBuilder) WritePair(k string, indent int, v string) { 57 if indent > 0 { 58 b.WriteElem("&" + k + "=\t" + v) 59 } else { 60 b.WriteElem("&" + k + "=" + v) 61 } 62 } 63 64 func (b *MapReprBuilder) String() string { 65 s := b.ListReprBuilder.String() 66 if s == "[]" { 67 s = "[&]" 68 } 69 return s 70 }