-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdecode.go
More file actions
239 lines (184 loc) · 4.89 KB
/
decode.go
File metadata and controls
239 lines (184 loc) · 4.89 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package csv
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"reflect"
)
// Row is one row of CSV data, indexed by column name or position.
type Row struct {
Columns *[]string // The name of the columns, in order
Data []string // the data for the row
}
// At returns the rows data for the column positon i
func (r *Row) At(i int) string {
return r.Data[i]
}
// Named returns the row's data for the first columne named 'n'
func (r *Row) Named(n string) (string, error) {
for i, cn := range *r.Columns {
if cn == n {
return r.At(i), nil
}
}
return "", fmt.Errorf("no column found for %s", n)
}
type decoder struct {
csv *csv.Reader // the csv document for input
reflect.Type // the underlying struct to decode
out reflect.Value // the slice output
cfields []cfield //
cols []string // colum names
}
// Unmarshaler is the interface implemented by objects which can unmarshall the CSV row itself.
type Unmarshaler interface {
// UnmarshalCSV receives a string with the column value matching this field
// and a reference to the the current row.
// This allows composing a value from multiple columns.
UnmarshalCSV(string, *Row) error
}
// Unmarshal parses the CSV document and stores the result in the value pointed to by v. Only a slice of a struct is allowed for v.
//
// The first line of the CSV is document is used for column names. These are
// paired to matching exported fields in v's type. See Marshal on how to use tags
// to map to different names and additional options.
//
// Supported Types
//
// string, int, float and bool are supported. Any type which implements Unmarshal is also supported.
func Unmarshal(doc []byte, v interface{}) error {
rv, err := checkForSlice(v)
if err != nil {
return err
}
dec, err := newDecoder(doc, rv)
if err != nil {
return err
}
return dec.unmarshal()
}
func (dec *decoder) unmarshal() error {
for {
raw, err := dec.csv.Read()
if err != nil {
break
} else {
row := dec.newRow(raw)
o := reflect.New(dec.Type).Elem()
err := dec.set(row, &o)
if err != nil {
return err
}
dec.out.Set(reflect.Append(dec.out, o))
}
}
return nil
}
func (dec *decoder) newRow(raw []string) *Row {
return &Row{
Columns: &dec.cols,
Data: raw,
}
}
// checkForSlice validates that the interface is a slice type
func checkForSlice(v interface{}) (reflect.Value, error) {
pv := reflect.ValueOf(v)
if pv.Kind() != reflect.Ptr || pv.IsNil() {
return pv, errors.New("type is nil or not a pointer")
}
rv := reflect.ValueOf(v).Elem()
if rv.Kind() != reflect.Slice {
return rv, fmt.Errorf("only slices are allowed: %s", rv.Kind())
}
return rv, nil
}
const (
// interface is implemented on a value
impsVal int = 1
// interface is implemented on a pointer
impsPtr int = 2
)
// impsUnmarshaller checks if an object implements the Unmarshaler interface
func impsUnmarshaller(et reflect.Type, i interface{}) (int, error) {
el := reflect.New(et).Elem()
it := reflect.TypeOf(i).Elem()
if el.Type().Implements(it) {
return impsVal, nil
}
if el.Addr().Type().Implements(it) {
return impsPtr, nil
}
return 0, fmt.Errorf("%v el does not implement %s", el, it.Name())
}
// mapFields creates a set of fieldMap instances.
//
// A cfield is created when a column name matches an exported field name in the
// decoder's Type.
func (dec *decoder) mapFieldsToCols(cols []string) {
pFields := exportedFields(dec.Type)
cMap := map[string]int{}
for i, col := range cols {
cMap[col] = i
}
for _, f := range pFields {
name, ok := fieldHeaderName(*f)
if ok == false {
continue
}
index, ok := cMap[name]
if ok == true {
cf := newCfield(index, f)
if code, err := impsUnmarshaller(f.Type, new(Unmarshaler)); err == nil {
cf.assignUnmarshaller(code)
} else {
cf.assignDecoder()
}
dec.cfields = append(dec.cfields, cf)
}
}
}
// exportedFields returns a slice of exported fields
func exportedFields(t reflect.Type) []*reflect.StructField {
var out []*reflect.StructField
v := reflect.New(t).Elem()
flen := v.NumField()
for i := 0; i < flen; i++ {
// Get the StructField from the Type
sf := t.Field(i)
// Check if the field is CanSet from the value (v)
if v.Field(i).CanSet() == true {
out = append(out, &sf)
}
}
return out
}
func newDecoder(doc []byte, rv reflect.Value) (*decoder, error) {
b := bytes.NewReader(doc)
r := csv.NewReader(b)
cols, err := r.Read()
if err != nil {
return nil, err
}
el := rv.Type().Elem()
dec := decoder{
Type: el,
csv: r,
out: rv,
cols: cols,
}
dec.mapFieldsToCols(cols)
return &dec, nil
}
// Sets each field value for the el struct for the given row
func (dec *decoder) set(row *Row, el *reflect.Value) error {
for _, cf := range dec.cfields {
field := cf.structField
f := el.FieldByName(field.Name)
err := cf.decoder(&f, row)
if err != nil {
return err
}
}
return nil
}