-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshalerenc.go
102 lines (95 loc) · 2.25 KB
/
marshalerenc.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
package astconf
import (
"encoding"
"errors"
"reflect"
)
type marshalerEncoder int
const (
mtBlock marshalerEncoder = iota
mtSetting
mtObject
mtText
mtPreamble
)
var (
errMarshalerNotImplemented = errors.New("type does not implement Marshaler as expected")
errObjectMarshalerNotImplemented = errors.New("type does not implement ObjectMarshaler as expected")
errSettingMarshalerNotImplemented = errors.New("type does not implement ValueMarshaler as expected")
errTextMarshalerNotImplemented = errors.New("type does not implement TextMarshaler as expected")
errPreambleMarshalerNotImplemented = errors.New("type does not implement PreambleMarshaler as expected")
)
func (me marshalerEncoder) encode(v reflect.Value, e *Encoder) error {
if v.Kind() == reflect.Ptr && v.IsNil() {
return nil
}
var err error
switch me {
case mtBlock:
m, ok := v.Interface().(Marshaler)
if ok {
err = m.MarshalAsterisk(e)
} else {
err = errMarshalerNotImplemented
}
case mtObject:
m, ok := v.Interface().(ObjectMarshaler)
if ok {
err = m.MarshalAsteriskObject(e.w)
} else {
err = errObjectMarshalerNotImplemented
}
case mtSetting:
m, ok := v.Interface().(SettingMarshaler)
if ok {
err = m.MarshalAsteriskSetting(e.w)
} else {
err = errSettingMarshalerNotImplemented
}
case mtText:
m, ok := v.Interface().(encoding.TextMarshaler)
if ok {
var b []byte
b, err = m.MarshalText()
if err == nil {
_, err = e.w.Write(b)
}
} else {
err = errTextMarshalerNotImplemented
}
case mtPreamble:
m, ok := v.Interface().(PreambleMarshaler)
if ok {
err = m.MarshalAsteriskPreamble(e)
} else {
err = errPreambleMarshalerNotImplemented
}
}
if err != nil {
return &MarshalerError{v.Type(), err, me.Call()}
}
return nil
}
func (me marshalerEncoder) addrEncode(v reflect.Value, e *Encoder) error {
va := v.Addr()
if va.IsNil() {
return nil
}
return me.encode(va, e)
}
func (me marshalerEncoder) Call() string {
switch me {
case mtBlock:
return "MarshalAsterisk"
case mtObject:
return "MarshalAsteriskObject"
case mtSetting:
return "MarshalAsteriskSetting"
case mtText:
return "MarshalText"
case mtPreamble:
return "MarshalAsteriskPreamble"
default:
return "UnknownMarshalingFunction"
}
}