github.com/Psiphon-Inc/goarista@v0.0.0-20160825065156-d002785f4c67/key/stringify.go (about) 1 // Copyright (C) 2015 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package key 6 7 import ( 8 "errors" 9 "fmt" 10 "math" 11 "strconv" 12 "strings" 13 14 "github.com/aristanetworks/goarista/value" 15 ) 16 17 // StringifyInterface transforms an arbitrary interface into its string 18 // representation. We need to do this because some entities use the string 19 // representation of their keys as their names. 20 // Note: this API is deprecated and will be removed. 21 func StringifyInterface(key interface{}) (string, error) { 22 if key == nil { 23 return "", errors.New("Unable to stringify nil") 24 } 25 var str string 26 switch key := key.(type) { 27 case bool: 28 str = strconv.FormatBool(key) 29 case uint8: 30 str = strconv.FormatUint(uint64(key), 10) 31 case uint16: 32 str = strconv.FormatUint(uint64(key), 10) 33 case uint32: 34 str = strconv.FormatUint(uint64(key), 10) 35 case uint64: 36 str = strconv.FormatUint(key, 10) 37 case int8: 38 str = strconv.FormatInt(int64(key), 10) 39 case int16: 40 str = strconv.FormatInt(int64(key), 10) 41 case int32: 42 str = strconv.FormatInt(int64(key), 10) 43 case int64: 44 str = strconv.FormatInt(key, 10) 45 case float32: 46 str = "f" + strconv.FormatInt(int64(math.Float32bits(key)), 10) 47 case float64: 48 str = "f" + strconv.FormatInt(int64(math.Float64bits(key)), 10) 49 case string: 50 str = key 51 case map[string]interface{}: 52 keys := SortedKeys(key) 53 for i, k := range keys { 54 v := key[k] 55 keys[i] = stringify(v) 56 } 57 str = strings.Join(keys, "_") 58 case *map[string]interface{}: 59 return StringifyInterface(*key) 60 case map[Key]interface{}: 61 m := make(map[string]interface{}, len(key)) 62 for k, v := range key { 63 m[k.String()] = v 64 } 65 keys := SortedKeys(m) 66 for i, k := range keys { 67 keys[i] = stringify(k) + "=" + stringify(m[k]) 68 } 69 str = strings.Join(keys, "_") 70 71 case value.Value: 72 return key.String(), nil 73 74 default: 75 panic(fmt.Errorf("Unable to stringify type %T: %#v", key, key)) 76 } 77 78 return str, nil 79 } 80 81 func stringify(key interface{}) string { 82 s, err := StringifyInterface(key) 83 if err != nil { 84 panic(err) 85 } 86 return s 87 }