forked from hamba/avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec_marshaler.go
70 lines (62 loc) · 1.64 KB
/
codec_marshaler.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
package avro
import (
"encoding"
"unsafe"
"github.com/modern-go/reflect2"
)
var (
textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem()
textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem()
)
func createDecoderOfMarshaler(schema Schema, typ reflect2.Type) ValDecoder {
if typ.Implements(textUnmarshalerType) && schema.Type() == String {
return &textMarshalerCodec{typ}
}
ptrType := reflect2.PtrTo(typ)
if ptrType.Implements(textUnmarshalerType) && schema.Type() == String {
return &referenceDecoder{
&textMarshalerCodec{ptrType},
}
}
return nil
}
func createEncoderOfMarshaler(schema Schema, typ reflect2.Type) ValEncoder {
if typ.Implements(textMarshalerType) && schema.Type() == String {
return &textMarshalerCodec{
typ: typ,
}
}
return nil
}
type textMarshalerCodec struct {
typ reflect2.Type
}
func (c textMarshalerCodec) Decode(ptr unsafe.Pointer, r *Reader) {
obj := c.typ.UnsafeIndirect(ptr)
if reflect2.IsNil(obj) {
ptrType := c.typ.(*reflect2.UnsafePtrType)
newPtr := ptrType.Elem().UnsafeNew()
*((*unsafe.Pointer)(ptr)) = newPtr
obj = c.typ.UnsafeIndirect(ptr)
}
unmarshaler := (obj).(encoding.TextUnmarshaler)
b := r.ReadBytes()
err := unmarshaler.UnmarshalText(b)
if err != nil {
r.ReportError("textMarshalerCodec", err.Error())
}
}
func (c textMarshalerCodec) Encode(ptr unsafe.Pointer, w *Writer) {
obj := c.typ.UnsafeIndirect(ptr)
if c.typ.IsNullable() && reflect2.IsNil(obj) {
w.WriteBytes(nil)
return
}
marshaler := (obj).(encoding.TextMarshaler)
b, err := marshaler.MarshalText()
if err != nil {
w.Error = err
return
}
w.WriteBytes(b)
}