-
Notifications
You must be signed in to change notification settings - Fork 62
/
encoder.go
549 lines (482 loc) · 14 KB
/
encoder.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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
package csvutil
import (
"reflect"
"sort"
)
const defaultBufSize = 4096
type encField struct {
field
encodeFunc
}
type encCache struct {
fields []encField
buf []byte
index []int
record []string
}
func newEncCache(k typeKey, funcMap map[reflect.Type]marshalFunc, funcs []marshalFunc, header []string) (_ *encCache, err error) {
fields := cachedFields(k)
encFields := make([]encField, 0, len(fields))
// if header is not empty, we are going to track columns in a set and we will
// track which columns are covered by type fields.
set := make(map[string]bool, len(header))
for _, s := range header {
set[s] = false
}
for _, f := range fields {
if _, ok := set[f.name]; len(header) > 0 && !ok {
continue
}
set[f.name] = true
fn, err := encodeFn(f.baseType, true, funcMap, funcs)
if err != nil {
return nil, err
}
encFields = append(encFields, encField{
field: f,
encodeFunc: fn,
})
}
if len(header) > 0 {
// look for columns that were defined in a header but are not present
// in the provided data type. In case we find any, we will set it to
// a no-op encoder that always produces an empty column.
for k, b := range set {
if b {
continue
}
encFields = append(encFields, encField{
field: field{
name: k,
},
encodeFunc: nopEncode,
})
}
sortEncFields(header, encFields)
}
return &encCache{
fields: encFields,
buf: make([]byte, 0, defaultBufSize),
index: make([]int, len(encFields)),
record: make([]string, len(encFields)),
}, nil
}
// sortEncFields sorts the provided fields according to the given header.
// at this stage header expects to contain matching fields, so both slices
// are expected to be of the same length.
func sortEncFields(header []string, fields []encField) {
set := make(map[string]int, len(header))
for i, s := range header {
set[s] = i
}
sort.Slice(fields, func(i, j int) bool {
return set[fields[i].name] < set[fields[j].name]
})
}
// Encoder writes structs CSV representations to the output stream.
type Encoder struct {
// Tag defines which key in the struct field's tag to scan for names and
// options (Default: 'csv').
Tag string
// If AutoHeader is true, a struct header is encoded during the first call
// to Encode automatically (Default: true).
AutoHeader bool
w Writer
c *encCache
header []string
noHeader bool
typeKey typeKey
funcMap map[reflect.Type]marshalFunc
ifaceFuncs []marshalFunc
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w Writer) *Encoder {
return &Encoder{
w: w,
noHeader: true,
AutoHeader: true,
}
}
// Register registers a custom encoding function for a concrete type or interface.
// The argument f must be of type:
//
// func(T) ([]byte, error)
//
// T must be a concrete type such as Foo or *Foo, or interface that has at
// least one method.
//
// During encoding, fields are matched by the concrete type first. If match is not
// found then Encoder looks if field implements any of the registered interfaces
// in order they were registered.
//
// Register panics if:
// - f does not match the right signature
// - f is an empty interface
// - f was already registered
//
// Register is based on the encoding/json proposal:
// https://github.com/golang/go/issues/5901.
//
// Deprecated: use MarshalFunc function with type parameter instead. The benefits
// are type safety and much better performance.
func (e *Encoder) Register(f any) {
var (
fn = reflect.ValueOf(f)
typ = fn.Type()
)
if typ.Kind() != reflect.Func ||
typ.NumIn() != 1 || typ.NumOut() != 2 ||
typ.Out(0) != _bytes || typ.Out(1) != _error {
panic("csvutil: func must be of type func(T) ([]byte, error)")
}
var (
argType = typ.In(0)
isIface = argType.Kind() == reflect.Interface
isPtr = argType.Kind() == reflect.Pointer
)
if isIface && argType.NumMethod() == 0 {
panic("csvutil: func argument type must not be an empty interface")
}
wrappedFn := marshalFunc{
f: func(val any) ([]byte, error) {
v := reflect.ValueOf(val)
if !v.IsValid() && (isIface || isPtr) {
v = reflect.Zero(argType)
}
out := fn.Call([]reflect.Value{v})
err, _ := out[1].Interface().(error)
return out[0].Bytes(), err
},
argType: typ.In(0),
}
if e.funcMap == nil {
e.funcMap = make(map[reflect.Type]marshalFunc)
}
if _, ok := e.funcMap[argType]; ok {
panic("csvutil: func " + typ.String() + " already registered")
}
e.funcMap[argType] = wrappedFn
if isIface {
e.ifaceFuncs = append(e.ifaceFuncs, wrappedFn)
}
}
// SetHeader overrides the provided data type's default header. Fields are
// encoded in the order of the provided header. If a column specified in the
// header doesn't exist in the provided type, it will be encoded as an empty
// column. Fields that are not part of the provided header are ignored.
// Encoder can't guarantee the right order if the provided header contains
// duplicate column names.
//
// SetHeader must be called before EncodeHeader and/or Encode in order to take
// effect.
func (enc *Encoder) SetHeader(header []string) {
cp := make([]string, len(header))
copy(cp, header)
enc.header = cp
}
// WithMarshalers sets the provided Marshalers for the encoder.
//
// WithMarshalers are based on the encoding/json proposal:
// https://github.com/golang/go/issues/5901.
func (enc *Encoder) WithMarshalers(m *Marshalers) {
enc.funcMap = m.funcMap
enc.ifaceFuncs = m.ifaceFuncs
}
// Encode writes the CSV encoding of v to the output stream. The provided
// argument v must be a struct, struct slice or struct array.
//
// Only the exported fields will be encoded.
//
// First call to Encode will write a header unless EncodeHeader was called first
// or AutoHeader is false. Header names can be customized by using tags
// ('csv' by default), otherwise original Field names are used.
//
// If header was provided through SetHeader then it overrides the provided data
// type's default header. Fields are encoded in the order of the provided header.
// If a column specified in the header doesn't exist in the provided type, it will
// be encoded as an empty column. Fields that are not part of the provided header
// are ignored. Encoder can't guarantee the right order if the provided header
// contains duplicate column names.
//
// Header and fields are written in the same order as struct fields are defined.
// Embedded struct's fields are treated as if they were part of the outer struct.
// Fields that are embedded types and that are tagged are treated like any
// other field, but they have to implement Marshaler or encoding.TextMarshaler
// interfaces.
//
// Marshaler interface has the priority over encoding.TextMarshaler.
//
// Tagged fields have the priority over non tagged fields with the same name.
//
// Following the Go visibility rules if there are multiple fields with the same
// name (tagged or not tagged) on the same level and choice between them is
// ambiguous, then all these fields will be ignored.
//
// Nil values will be encoded as empty strings. Same will happen if 'omitempty'
// tag is set, and the value is a default value like 0, false or nil interface.
//
// Bool types are encoded as 'true' or 'false'.
//
// Float types are encoded using strconv.FormatFloat with precision -1 and 'G'
// format. NaN values are encoded as 'NaN' string.
//
// Fields of type []byte are being encoded as base64-encoded strings.
//
// Fields can be excluded from encoding by using '-' tag option.
//
// Examples of struct tags:
//
// // Field appears as 'myName' header in CSV encoding.
// Field int `csv:"myName"`
//
// // Field appears as 'Field' header in CSV encoding.
// Field int
//
// // Field appears as 'myName' header in CSV encoding and is an empty string
// // if Field is 0.
// Field int `csv:"myName,omitempty"`
//
// // Field appears as 'Field' header in CSV encoding and is an empty string
// // if Field is 0.
// Field int `csv:",omitempty"`
//
// // Encode ignores this field.
// Field int `csv:"-"`
//
// // Encode treats this field exactly as if it was an embedded field and adds
// // "my_prefix_" to each field's name.
// Field Struct `csv:"my_prefix_,inline"`
//
// // Encode treats this field exactly as if it was an embedded field.
// Field Struct `csv:",inline"`
//
// Fields with inline tags that have a non-empty prefix must not be cyclic
// structures. Passing such values to Encode will result in an infinite loop.
//
// Encode doesn't flush data. The caller is responsible for calling Flush() if
// the used Writer supports it.
func (e *Encoder) Encode(v any) error {
return e.encode(reflect.ValueOf(v))
}
// EncodeHeader writes the CSV header of the provided struct value to the output
// stream. The provided argument v must be a struct value.
//
// The first Encode method call will not write header if EncodeHeader was called
// before it. This method can be called in cases when a data set could be
// empty, but header is desired.
//
// EncodeHeader is like Header function, but it works with the Encoder and writes
// directly to the output stream. Look at Header documentation for the exact
// header encoding rules.
func (e *Encoder) EncodeHeader(v any) error {
typ, err := valueType(v)
if err != nil {
return err
}
return e.encodeHeader(typ)
}
func (e *Encoder) encode(v reflect.Value) error {
val := walkValue(v)
if !val.IsValid() {
return &InvalidEncodeError{}
}
switch val.Kind() {
case reflect.Struct:
return e.encodeStruct(val)
case reflect.Array, reflect.Slice:
if walkType(val.Type().Elem()).Kind() != reflect.Struct {
return &InvalidEncodeError{v.Type()}
}
return e.encodeArray(val)
default:
return &InvalidEncodeError{v.Type()}
}
}
func (e *Encoder) encodeStruct(v reflect.Value) error {
if e.AutoHeader && e.noHeader {
if err := e.encodeHeader(v.Type()); err != nil {
return err
}
}
return e.marshal(v)
}
func (e *Encoder) encodeArray(v reflect.Value) error {
l := v.Len()
for i := 0; i < l; i++ {
if err := e.encodeStruct(walkValue(v.Index(i))); err != nil {
return err
}
}
return nil
}
func (e *Encoder) encodeHeader(typ reflect.Type) error {
fields, _, _, record, err := e.cache(typ)
if err != nil {
return err
}
for i, f := range fields {
record[i] = f.name
}
if err := e.w.Write(record); err != nil {
return err
}
e.noHeader = false
return nil
}
func (e *Encoder) marshal(v reflect.Value) error {
fields, buf, index, record, err := e.cache(v.Type())
if err != nil {
return err
}
for i, f := range fields {
v := walkIndex(v, f.index)
omitempty := f.tag.omitEmpty
if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
// We should disable omitempty for pointer and interface values,
// because if it's nil we will automatically encode it as an empty
// string. However, the initialized pointer should not be affected,
// even if it's a default value.
omitempty = false
}
if !v.IsValid() {
index[i] = 0
continue
}
b, err := f.encodeFunc(buf, v, omitempty)
if err != nil {
return err
}
index[i], buf = len(b)-len(buf), b
}
out := string(buf)
for i, n := range index {
record[i], out = out[:n], out[n:]
}
e.c.buf = buf[:0]
return e.w.Write(record)
}
func (e *Encoder) tag() string {
if e.Tag == "" {
return defaultTag
}
return e.Tag
}
func (e *Encoder) cache(typ reflect.Type) ([]encField, []byte, []int, []string, error) {
if k := (typeKey{e.tag(), typ}); k != e.typeKey {
c, err := newEncCache(k, e.funcMap, e.ifaceFuncs, e.header)
if err != nil {
return nil, nil, nil, nil, err
}
e.c, e.typeKey = c, k
}
return e.c.fields, e.c.buf[:0], e.c.index, e.c.record, nil
}
// Marshalers stores custom unmarshal functions. Marshalers are immutable.
//
// Marshalers are based on the encoding/json proposal:
// https://github.com/golang/go/issues/5901.
type Marshalers struct {
funcMap map[reflect.Type]marshalFunc
ifaceFuncs []marshalFunc
}
// NewMarshalers merges the provided Marshalers into one and returns it.
// If Marshalers contain duplicate function signatures, the one that was
// provided first wins.
func NewMarshalers(ms ...*Marshalers) *Marshalers {
out := &Marshalers{
funcMap: make(map[reflect.Type]marshalFunc),
}
for _, u := range ms {
for k, v := range u.funcMap {
if _, ok := out.funcMap[k]; ok {
continue
}
out.funcMap[k] = v
}
out.ifaceFuncs = append(out.ifaceFuncs, u.ifaceFuncs...)
}
return out
}
// MarshalFunc stores the provided function in Marshalers and returns it.
//
// T must be a concrete type such as Foo or *Foo, or interface that has at
// least one method.
//
// During encoding, fields are matched by the concrete type first. If match is not
// found then Encoder looks if field implements any of the registered interfaces
// in order they were registered.
//
// UnmarshalFunc panics if T is an empty interface.
func MarshalFunc[T any](f func(T) ([]byte, error)) *Marshalers {
var (
v = reflect.ValueOf(f)
typ = v.Type()
argType = typ.In(0)
isIface = argType.Kind() == reflect.Interface
)
if isIface && argType.NumMethod() == 0 {
panic("csvutil: func argument type must not be an empty interface")
}
var zero T
wrappedFn := marshalFunc{
f: func(v any) ([]byte, error) {
if !isIface {
return f(v.(T))
}
if v == nil {
return f(zero)
}
return f(v.(T))
},
argType: typ.In(0),
}
funcMap := map[reflect.Type]marshalFunc{
argType: wrappedFn,
}
var ifaceFuncs []marshalFunc
if isIface {
ifaceFuncs = []marshalFunc{
wrappedFn,
}
}
return &Marshalers{
funcMap: funcMap,
ifaceFuncs: ifaceFuncs,
}
}
func walkIndex(v reflect.Value, index []int) reflect.Value {
for _, i := range index {
v = walkPtr(v)
if !v.IsValid() {
return reflect.Value{}
}
v = v.Field(i)
}
return v
}
func walkPtr(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v
}
func walkValue(v reflect.Value) reflect.Value {
for {
switch v.Kind() {
case reflect.Ptr, reflect.Interface:
v = v.Elem()
default:
return v
}
}
}
func walkType(typ reflect.Type) reflect.Type {
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ
}
type marshalFunc struct {
f func(any) ([]byte, error)
argType reflect.Type
}