-
Notifications
You must be signed in to change notification settings - Fork 32
/
encode.go
210 lines (185 loc) · 5.11 KB
/
encode.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
package fixedwidth
import (
"bufio"
"bytes"
"encoding"
"io"
"reflect"
"strconv"
)
// Marshal returns the fixed-width encoding of v.
//
// v must be an encodable type or a slice of an encodable
// type. If v is a slice, each item will be treated as a
// line. If v is a single encodable type, a single line
// will be encoded.
//
// In order for a type to be encodable, it must implement
// the encoding.TextMarshaler interface or be based on one
// of the following builtin types: string, int, int64,
// int32, int16, int8, float64, float32, or struct.
// Pointers to encodable types and interfaces containing
// encodable types are also encodable.
//
// nil pointers and interfaces will be omitted. zero vales
// will be encoded normally.
//
// A struct is encoded to a single slice of bytes. Each
// field in a struct will be encoded and placed at the
// position defined by its struct tags. The tags should be
// formatted as `fixed:"{startPos},{endPos}"`. Positions
// start at 1. The interval is inclusive. Fields without
// tags and Fields of an un-encodable type are ignored.
//
// If the encoded value of a field is longer than the
// length of the position interval, the overflow is
// truncated.
func Marshal(v interface{}) ([]byte, error) {
buff := bytes.NewBuffer(nil)
err := NewEncoder(buff).Encode(v)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
// MarshalInvalidTypeError describes an invalid type being marshaled.
type MarshalInvalidTypeError struct {
typeName string
}
func (e *MarshalInvalidTypeError) Error() string {
return "fixedwidth: cannot marshal unknown Type " + e.typeName
}
// An Encoder writes fixed-width formatted data to an output
// stream.
type Encoder struct {
w *bufio.Writer
lineTerminator []byte
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{
w: bufio.NewWriter(w),
lineTerminator: []byte("\n"),
}
}
// SetLineTerminator sets the character(s) that will be used to terminate lines.
//
// The default value is "\n".
func (e *Encoder) SetLineTerminator(lineTerminator []byte) {
e.lineTerminator = lineTerminator
}
// Encode writes the fixed-width encoding of v to the
// stream.
// See the documentation for Marshal for details about
// encoding behavior.
func (e *Encoder) Encode(i interface{}) (err error) {
if i == nil {
return nil
}
// check to see if i should be encoded into multiple lines
v := reflect.ValueOf(i)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.Kind() == reflect.Slice {
// encode each slice element to a line
err = e.writeLines(v)
} else {
// this is a single object so encode the original vale to a line
err = e.writeLine(reflect.ValueOf(i))
}
if err != nil {
return err
}
return e.w.Flush()
}
func (e *Encoder) writeLines(v reflect.Value) error {
for i := 0; i < v.Len(); i++ {
err := e.writeLine(v.Index(i))
if err != nil {
return err
}
if i != v.Len()-1 {
_, err := e.w.Write(e.lineTerminator)
if err != nil {
return err
}
}
}
return nil
}
func (e *Encoder) writeLine(v reflect.Value) (err error) {
b, err := newValueEncoder(v.Type())(v)
if err != nil {
return err
}
_, err = e.w.Write(b)
return err
}
type valueEncoder func(v reflect.Value) ([]byte, error)
func newValueEncoder(t reflect.Type) valueEncoder {
if t == nil {
return nilEncoder
}
if t.Implements(reflect.TypeOf(new(encoding.TextMarshaler)).Elem()) {
return textMarshalerEncoder
}
switch t.Kind() {
case reflect.Ptr, reflect.Interface:
return ptrInterfaceEncoder
case reflect.Struct:
return structEncoder
case reflect.String:
return stringEncoder
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
return intEncoder
case reflect.Float64:
return floatEncoder(2, 64)
case reflect.Float32:
return floatEncoder(2, 32)
}
return unknownTypeEncoder(t)
}
func structEncoder(v reflect.Value) ([]byte, error) {
ss := cachedStructSpec(v.Type())
dst := bytes.Repeat([]byte(" "), ss.ll)
for i, spec := range ss.fieldSpecs {
if !spec.ok {
continue
}
val, err := spec.encoder(v.Field(i))
if err != nil {
return nil, err
}
copy(dst[spec.startPos-1:spec.endPos:spec.endPos], val)
}
return dst, nil
}
func textMarshalerEncoder(v reflect.Value) ([]byte, error) {
return v.Interface().(encoding.TextMarshaler).MarshalText()
}
func ptrInterfaceEncoder(v reflect.Value) ([]byte, error) {
if v.IsNil() {
return nilEncoder(v)
}
return newValueEncoder(v.Elem().Type())(v.Elem())
}
func stringEncoder(v reflect.Value) ([]byte, error) {
return []byte(v.String()), nil
}
func intEncoder(v reflect.Value) ([]byte, error) {
return []byte(strconv.Itoa(int(v.Int()))), nil
}
func floatEncoder(perc, bitSize int) valueEncoder {
return func(v reflect.Value) ([]byte, error) {
return []byte(strconv.FormatFloat(v.Float(), 'f', perc, bitSize)), nil
}
}
func nilEncoder(v reflect.Value) ([]byte, error) {
return nil, nil
}
func unknownTypeEncoder(t reflect.Type) valueEncoder {
return func(value reflect.Value) ([]byte, error) {
return nil, &MarshalInvalidTypeError{typeName: t.Name()}
}
}