-
Notifications
You must be signed in to change notification settings - Fork 22
/
unmarshal.go
362 lines (304 loc) · 8.25 KB
/
unmarshal.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
package binstruct
import (
"errors"
"fmt"
"io"
"reflect"
"strings"
)
type unmarshal struct {
r Reader
}
// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type InvalidUnmarshalError struct {
Type reflect.Type
}
func (e *InvalidUnmarshalError) Error() string {
if e.Type == nil {
return "binstruct: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "binstruct: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "binstruct: Unmarshal(nil " + e.Type.String() + ")"
}
func (u *unmarshal) Unmarshal(v interface{}) error {
return u.unmarshal(v, nil)
}
func (u *unmarshal) unmarshal(v interface{}, parentStructValues []reflect.Value) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(v)}
}
structValue := rv.Elem()
numField := structValue.NumField()
valueType := structValue.Type()
for i := 0; i < numField; i++ {
fieldType := valueType.Field(i)
tags, err := parseTag(fieldType.Tag.Get(tagName))
if err != nil {
return fmt.Errorf(`failed parseTag for field "%s": %w`, fieldType.Name, err)
}
fieldData, err := parseReadDataFromTags(structValue, tags)
if err != nil {
return fmt.Errorf(`failed parse ReadData from tags for field "%s": %w`, fieldType.Name, err)
}
fieldValue := structValue.Field(i)
err = u.setValueToField(structValue, fieldValue, fieldData, parentStructValues)
if err != nil {
return fmt.Errorf(`failed set value to field "%s": %w`, fieldType.Name, err)
}
}
return nil
}
func (u *unmarshal) setValueToField(
structValue, fieldValue reflect.Value, fieldData *fieldReadData, parentStructValues []reflect.Value,
) error {
if fieldData == nil {
fieldData = &fieldReadData{}
}
if fieldData.Ignore {
return nil
}
r := u.r
if fieldData.Order != nil {
r = r.WithOrder(fieldData.Order)
}
if fieldData.OffsetRestore {
currentOffset, err := r.Seek(0, io.SeekCurrent)
if err != nil {
return fmt.Errorf("get current offset: %w", err)
}
defer r.Seek(currentOffset, io.SeekStart)
}
err := setOffset(r, fieldData)
if err != nil {
return fmt.Errorf("set offset: %w", err)
}
if fieldData.FuncName != "" {
var okCallFunc bool
okCallFunc, err = callFunc(r, fieldData.FuncName, structValue, fieldValue)
if err != nil {
return fmt.Errorf("call custom func(%s): %w", structValue.Type().Name(), err)
}
if !okCallFunc {
// Try call function from parent structs
for i := len(parentStructValues) - 1; i >= 0; i-- {
sv := parentStructValues[i]
okCallFunc, err = callFunc(r, fieldData.FuncName, sv, fieldValue)
if err != nil {
return fmt.Errorf("call custom func from parent(%s): %w", sv.Type().Name(), err)
}
if okCallFunc {
return nil
}
}
message := `
failed call method, expected methods:
func (*{{Struct}}) {{MethodName}}(r binstruct.Reader) error {}
or
func (*{{Struct}}) {{MethodName}}(r binstruct.Reader) ({{FieldType}}, error) {}
`
message = strings.NewReplacer(
`{{Struct}}`, structValue.Type().Name(),
`{{MethodName}}`, fieldData.FuncName,
`{{FieldType}}`, fieldValue.Type().String(),
).Replace(message)
return errors.New(message)
}
return nil
}
switch fieldValue.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var value int64
var err error
if fieldData.Length != nil {
value, err = r.ReadIntX(int(*fieldData.Length))
} else {
switch fieldValue.Kind() {
case reflect.Int8:
v, e := r.ReadInt8()
value = int64(v)
err = e
case reflect.Int16:
v, e := r.ReadInt16()
value = int64(v)
err = e
case reflect.Int32:
v, e := r.ReadInt32()
value = int64(v)
err = e
case reflect.Int64:
v, e := r.ReadInt64()
value = v
err = e
default: // reflect.Int:
return errors.New("need set tag with len or use int8/int16/int32/int64")
}
}
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetInt(value)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
var value uint64
var err error
if fieldData.Length != nil {
value, err = r.ReadUintX(int(*fieldData.Length))
} else {
switch fieldValue.Kind() {
case reflect.Uint8:
v, e := r.ReadUint8()
value = uint64(v)
err = e
case reflect.Uint16:
v, e := r.ReadUint16()
value = uint64(v)
err = e
case reflect.Uint32:
v, e := r.ReadUint32()
value = uint64(v)
err = e
case reflect.Uint64:
v, e := r.ReadUint64()
value = v
err = e
default: // reflect.Uint:
return errors.New("need set tag with len or use uint8/uint16/uint32/uint64")
}
}
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetUint(value)
}
case reflect.Float32:
f, err := r.ReadFloat32()
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetFloat(float64(f))
}
case reflect.Float64:
f, err := r.ReadFloat64()
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetFloat(f)
}
case reflect.Bool:
b, err := r.ReadBool()
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetBool(b)
}
case reflect.String:
if fieldData.Length == nil {
return errors.New("need set tag with len for string")
}
_, b, err := r.ReadBytes(int(*fieldData.Length))
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.SetString(string(b))
}
case reflect.Slice:
if fieldData.Length == nil {
return errors.New("need set tag with len for slice")
}
arrLen := int(*fieldData.Length)
// If slice of bytes, read bytes and set to slice.
if fieldValue.Type().Elem().Kind() == reflect.Uint8 {
n, b, err := u.r.ReadBytes(arrLen)
if err != nil {
return err
}
if n != arrLen {
return fmt.Errorf("expected %d, got %d", *fieldData.Length, n)
}
if fieldValue.CanSet() {
fieldValue.SetBytes(b)
}
return nil
}
if fieldValue.CanSet() {
// Create slice before populate.
fieldValue.Set(reflect.MakeSlice(fieldValue.Type(), arrLen, arrLen))
}
return u.setArrayValueToField(arrLen, structValue, fieldValue, fieldData, parentStructValues)
case reflect.Array:
arrLen := fieldValue.Len()
if fieldData.Length != nil {
arrLen = int(*fieldData.Length)
}
return u.setArrayValueToField(arrLen, structValue, fieldValue, fieldData, parentStructValues)
case reflect.Struct:
err = u.unmarshal(fieldValue.Addr().Interface(), append(parentStructValues, structValue))
if err != nil {
return fmt.Errorf("unmarshal struct: %w", err)
}
default:
return errors.New(`type "` + fieldValue.Kind().String() + `" not supported`)
}
return nil
}
func (u *unmarshal) setArrayValueToField(
arrLen int, structValue, fieldValue reflect.Value, fieldData *fieldReadData, parentStructValues []reflect.Value,
) error {
for i := 0; i < arrLen; i++ {
tmpV := reflect.New(fieldValue.Type().Elem()).Elem()
err := u.setValueToField(structValue, tmpV, fieldData.ElemFieldData, parentStructValues)
if err != nil {
return err
}
if fieldValue.CanSet() {
fieldValue.Index(i).Set(tmpV)
}
}
return nil
}
func callFunc(r Reader, funcName string, structValue, fieldValue reflect.Value) (bool, error) {
// Call methods
m := structValue.Addr().MethodByName(funcName)
readerType := reflect.TypeOf((*Reader)(nil)).Elem()
if m.IsValid() && m.Type().NumIn() == 1 && m.Type().In(0) == readerType {
ret := m.Call([]reflect.Value{reflect.ValueOf(r)})
errorType := reflect.TypeOf((*error)(nil)).Elem()
// Method(r binstruct.Reader) error
if len(ret) == 1 && ret[0].Type() == errorType {
if !ret[0].IsNil() {
return true, ret[0].Interface().(error)
}
return true, nil
}
// Method(r binstruct.Reader) (FieldType, error)
if len(ret) == 2 && ret[0].Type() == fieldValue.Type() && ret[1].Type() == errorType {
if !ret[1].IsNil() {
return true, ret[1].Interface().(error)
}
if fieldValue.CanSet() {
fieldValue.Set(ret[0])
}
return true, nil
}
}
return false, nil
}
func setOffset(r Reader, fieldData *fieldReadData) error {
for _, v := range fieldData.Offsets {
_, err := r.Seek(v.Offset, v.Whence)
if err != nil {
return fmt.Errorf("seek: %w", err)
}
}
return nil
}