amuz.es/src/infra/goutils@v0.1.3/tmpl/map.go (about) 1 package tmpl 2 3 import ( 4 "reflect" 5 _ "unsafe" 6 ) 7 8 type TmplMap struct { 9 reflect.Value 10 } 11 12 func (m TmplMap) Keys() ([]reflect.Value) { 13 return m.MapKeys() 14 } 15 16 func (m TmplMap) MapWithDefaults(arg0 reflect.Value, args ...reflect.Value) (v reflect.Value) { 17 if iarg0 := indirectInterface(arg0); evalTrue(iarg0) { 18 if v = m.MapIndex(iarg0); evalTrue(v) { 19 return 20 } 21 } 22 23 for _, v = range args { 24 if truth(v) { 25 break 26 } 27 } 28 return 29 } 30 31 func (m TmplMap) Map(arg0 reflect.Value, args ...reflect.Value) (v reflect.Value) { 32 if iarg0 := indirectInterface(arg0); evalTrue(iarg0) { 33 if v = m.MapIndex(iarg0); evalTrue(v) { 34 return 35 } 36 } 37 argLen := len(args) 38 if argLen == 0 { 39 return 40 } 41 keys, defaultValue := args[:argLen-1], args[argLen-1] 42 for _, k := range keys { 43 if ik := indirectInterface(k); !evalTrue(ik) { 44 } else if v = m.Value.MapIndex(ik); evalTrue(v) { 45 return 46 } 47 } 48 v = defaultValue 49 return 50 } 51 52 func MakeMapFunc(arg ...reflect.Value) TmplMap { 53 if len(arg)%2 != 0 { 54 panic("bad makemap") 55 } 56 57 m := reflect.MakeMapWithSize(reflect.TypeOf(map[interface{}]interface{}{}), len(arg)/2) 58 for i := 0; i < len(arg); i += 2 { 59 k, v := indirectInterface(arg[i]), indirectInterface(arg[i+1]) 60 if !(evalTrue(k) && evalTrue(v)) { 61 continue 62 } 63 m.SetMapIndex(k, v) 64 } 65 return TmplMap{m} 66 }