...
1 package keyvals
2
3 import (
4 "fmt"
5 "reflect"
6 )
7
8
9
10
11 func ToMap(kvs []interface{}) map[string]interface{} {
12 m := map[string]interface{}{}
13
14 if len(kvs) == 0 {
15 return m
16 }
17
18 if len(kvs)%2 == 1 {
19 kvs = append(kvs, nil)
20 }
21
22 for i := 0; i < len(kvs); i += 2 {
23 merge(m, kvs[i], kvs[i+1])
24 }
25
26 return m
27 }
28
29 func merge(dst map[string]interface{}, k, v interface{}) {
30 var key string
31
32 switch x := k.(type) {
33 case string:
34 key = x
35 case fmt.Stringer:
36 key = safeString(x)
37 default:
38 key = fmt.Sprint(x)
39 }
40
41 dst[key] = v
42 }
43
44 func safeString(str fmt.Stringer) (s string) {
45 defer func() {
46 if panicVal := recover(); panicVal != nil {
47 if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() {
48 s = "NULL"
49 } else {
50 panic(panicVal)
51 }
52 }
53 }()
54
55 s = str.String()
56
57 return
58 }
59
View as plain text