-
Notifications
You must be signed in to change notification settings - Fork 99
/
codec_default.go
58 lines (48 loc) · 1.23 KB
/
codec_default.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
package avro
import (
"fmt"
"unsafe"
"github.com/modern-go/reflect2"
)
func createDefaultDecoder(d *decoderContext, field *Field, typ reflect2.Type) ValDecoder {
cfg := d.cfg
fn := func(def any) ([]byte, error) {
defaultType := reflect2.TypeOf(def)
if defaultType == nil {
defaultType = reflect2.TypeOf((*null)(nil))
}
defaultEncoder := encoderOfType(newEncoderContext(cfg), field.Type(), defaultType)
if defaultType.LikePtr() {
defaultEncoder = &onePtrEncoder{defaultEncoder}
}
w := cfg.borrowWriter()
defer cfg.returnWriter(w)
defaultEncoder.Encode(reflect2.PtrOf(def), w)
if w.Error != nil {
return nil, w.Error
}
b := w.Buffer()
data := make([]byte, len(b))
copy(data, b)
return data, nil
}
b, err := field.encodeDefault(fn)
if err != nil {
return &errorDecoder{err: fmt.Errorf("decode default: %w", err)}
}
return &defaultDecoder{
data: b,
decoder: decoderOfType(d, field.Type(), typ),
}
}
type defaultDecoder struct {
data []byte
decoder ValDecoder
}
// Decode implements ValDecoder.
func (d *defaultDecoder) Decode(ptr unsafe.Pointer, r *Reader) {
rr := r.cfg.borrowReader(d.data)
defer r.cfg.returnReader(rr)
d.decoder.Decode(ptr, rr)
}
var _ ValDecoder = &defaultDecoder{}