| 1 | package encoding |
| 2 | |
| 3 | import "reflect" |
| 4 | |
| 5 | func getTypeKind(t reflect.Type) reflect.Kind { |
| 6 | kind := t.Kind() |
| 7 | |
| 8 | switch { |
| 9 | case kind >= reflect.Int && kind <= reflect.Int64: |
| 10 | return reflect.Int |
| 11 | case kind >= reflect.Uint && kind <= reflect.Uint64: |
| 12 | return reflect.Uint |
| 13 | case kind >= reflect.Float32 && kind <= reflect.Float64: |
| 14 | return reflect.Float32 |
| 15 | default: |
| 16 | return kind |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | func isEmptyValue(v reflect.Value) bool { |
| 21 | switch v.Kind() { |
| 22 | case reflect.Array, reflect.Map, reflect.Slice, reflect.String: |
| 23 | return v.Len() == 0 |
| 24 | case reflect.Bool: |
| 25 | return !v.Bool() |
| 26 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 27 | return v.Int() == 0 |
| 28 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 29 | return v.Uint() == 0 |
| 30 | case reflect.Float32, reflect.Float64: |
| 31 | return v.Float() == 0 |
| 32 | case reflect.Interface, reflect.Ptr: |
| 33 | return v.IsNil() |
| 34 | } |
| 35 | return false |
| 36 | } |
| 37 | |
| 38 | func fieldByIndex(v reflect.Value, index []int) reflect.Value { |
| 39 | for _, i := range index { |
| 40 | if v.Kind() == reflect.Ptr { |
| 41 | if v.IsNil() { |
| 42 | v.Set(reflect.New(v.Type().Elem())) |
| 43 | } |
| 44 | v = v.Elem() |
| 45 | } |
| 46 | v = v.Field(i) |
| 47 | } |
| 48 | |
| 49 | return v |
| 50 | } |
| 51 | |
| 52 | func typeByIndex(t reflect.Type, index []int) reflect.Type { |
| 53 | for _, i := range index { |
| 54 | if t.Kind() == reflect.Ptr { |
| 55 | t = t.Elem() |
| 56 | } |
| 57 | t = t.Field(i).Type |
| 58 | } |
| 59 | return t |
| 60 | } |
| 61 | |
| 62 | // valueByString sorts reflect.Value by the string value, this is useful for |
| 63 | // sorting the result of MapKeys |
| 64 | type valueByString []reflect.Value |
| 65 | |
| 66 | func (x valueByString) Len() int { return len(x) } |
| 67 | |
| 68 | func (x valueByString) Swap(i, j int) { x[i], x[j] = x[j], x[i] } |
| 69 | |
| 70 | func (x valueByString) Less(i, j int) bool { |
| 71 | return x[i].String() < x[j].String() |
| 72 | } |