-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencode.go
77 lines (66 loc) · 1.63 KB
/
encode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package xsv
import (
"errors"
"fmt"
"io"
"reflect"
)
var (
ErrChannelIsClosed = errors.New("channel is closed")
)
type encoder struct {
out io.Writer
}
func ensureStructOrPtr(t reflect.Type) error {
switch t.Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
return nil
}
return fmt.Errorf("cannot use " + t.String() + ", only slice or array supported")
}
// Check if the inType is an array or a slice
func ensureInType(outType reflect.Type) error {
switch outType.Kind() {
case reflect.Slice:
fallthrough
case reflect.Array:
return nil
}
return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported")
}
// Check if the inInnerType is of type struct
func ensureInInnerType(outInnerType reflect.Type) error {
switch outInnerType.Kind() {
case reflect.Struct:
return nil
}
return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
}
func getInnerField(outInner reflect.Value, outInnerWasPointer bool, index []int) (string, error) {
oi := outInner
if outInnerWasPointer {
if oi.IsNil() {
return "", nil
}
oi = outInner.Elem()
}
if oi.Kind() == reflect.Slice || oi.Kind() == reflect.Array {
i := index[0]
if i >= oi.Len() {
return "", nil
}
item := oi.Index(i)
if len(index) > 1 {
return getInnerField(item, false, index[1:])
}
return getFieldAsString(item)
}
// because pointers can be nil need to recurse one index at a time and perform nil check
if len(index) > 1 {
nextField := oi.Field(index[0])
return getInnerField(nextField, nextField.Kind() == reflect.Ptr, index[1:])
}
return getFieldAsString(oi.FieldByIndex(index))
}