forked from lunixbochs/struc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fields.go
246 lines (231 loc) · 5.73 KB
/
fields.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
package struc
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"reflect"
"strings"
)
type Fields []*Field
func (f Fields) SetByteOrder(order binary.ByteOrder) {
for _, field := range f {
if field != nil {
field.Order = order
}
}
}
func (f Fields) String() string {
fields := make([]string, len(f))
for i, field := range f {
if field != nil {
fields[i] = field.String()
}
}
return "{" + strings.Join(fields, ", ") + "}"
}
func (f Fields) Sizeof(val reflect.Value, options *Options) int {
for val.Kind() == reflect.Ptr {
val = val.Elem()
}
size := 0
for i, field := range f {
if field != nil {
var sliceLength int
// Grab the size in the from field if one was specified
if field.Sizefrom != nil {
if n, ok := SizeFromField(val.FieldByIndex(field.Sizefrom)); ok {
sliceLength = n
}
}
size += field.Size(val.Field(i), options, sliceLength)
}
}
return size
}
func SizeFromField(field reflect.Value) (int, bool) {
switch field.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(field.Int()), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n := int(field.Uint())
// all the builtin array length types are native int
// so this guards against weird truncation
if n < 0 {
return 0, true
}
return n, true
default:
return 0, false
}
}
func (f Fields) sizefrom(val reflect.Value, index []int) int {
field := val.FieldByIndex(index)
if n, ok := SizeFromField(field); ok {
return n
}
name := val.Type().FieldByIndex(index).Name
panic(fmt.Sprintf("sizeof field %T.%s not an integer type", val.Interface(), name))
}
func (f Fields) Pack(buf []byte, val reflect.Value, options *Options) (int, error) {
for val.Kind() == reflect.Ptr {
val = val.Elem()
}
pos := 0
for i, field := range f {
if field == nil {
continue
}
v := val.Field(i)
length := field.Len
if field.Sizefrom != nil {
length = f.sizefrom(val, field.Sizefrom)
}
if length <= 0 && field.Slice {
length = v.Len()
}
if field.Sizeof != nil {
length := val.FieldByIndex(field.Sizeof).Len()
sizeofField := f[field.Sizeof[0]]
if sizeofField.NullString {
length += 1
}
switch field.kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// allocating a new int here has fewer side effects (doesn't update the original struct)
// but it's a wasteful allocation
// the old method might work if we just cast the temporary int/uint to the target type
v = reflect.New(v.Type()).Elem()
v.SetInt(int64(length))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = reflect.New(v.Type()).Elem()
v.SetUint(uint64(length))
default:
panic(fmt.Sprintf("sizeof field is not int or uint type: %s, %s", field.Name, v.Type()))
}
}
if n, err := field.Pack(buf[pos:], v, length, options); err != nil {
return n, err
} else {
pos += n
}
}
return pos, nil
}
func (f Fields) Unpack(r io.Reader, val reflect.Value, options *Options) error {
for val.Kind() == reflect.Ptr {
val = val.Elem()
}
var tmp [8]byte
var buf []byte
for i, field := range f {
if field == nil {
continue
}
v := val.Field(i)
length := field.Len
if field.Sizefrom != nil {
length = f.sizefrom(val, field.Sizefrom)
}
if v.Kind() == reflect.Ptr && !v.Elem().IsValid() {
v.Set(reflect.New(v.Type().Elem()))
}
if field.Type == Struct {
if field.Slice {
vals := reflect.MakeSlice(v.Type(), length, length)
for i := 0; i < length; i++ {
v := vals.Index(i)
// create a new element to unpack into if have a pointer slice
if v.Kind() == reflect.Ptr && !v.Elem().IsValid() {
v.Set(reflect.New(v.Type().Elem()))
}
fields, err := parseFields(v)
if err != nil {
return err
}
if err := fields.Unpack(r, v, options); err != nil {
return err
}
}
v.Set(vals)
} else {
// TODO: DRY (we repeat the inner loop above)
fields, err := parseFields(v)
if err != nil {
return err
}
if err := fields.Unpack(r, v, options); err != nil {
return err
}
}
continue
} else {
typ := field.Type.Resolve(options)
if typ == CustomType {
if err := v.Addr().Interface().(Custom).Unpack(r, length, options); err != nil {
return err
}
} else if typ == String {
if field.Slice {
vals := reflect.MakeSlice(v.Type(), length, length)
for i := 0; i < length; i++ {
v := vals.Index(i)
// create a new element to unpack into if have a pointer slice
if v.Kind() == reflect.Ptr && !v.Elem().IsValid() {
v.Set(reflect.New(v.Type().Elem()))
}
s := readString(r, -1)
v.SetString(s)
}
v.Set(vals)
} else {
max := -1
if field.Sizefrom != nil && length != 0 {
max = length
}
s := readString(r, max)
v.SetString(s)
}
} else {
size := length * field.Type.Resolve(options).Size()
if size < 8 {
buf = tmp[:size]
} else {
buf = make([]byte, size)
}
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
err := field.Unpack(buf[:size], v, length, options)
if err != nil {
return err
}
}
}
}
return nil
}
// readString reads a string byte by byte until either max characters are
// read or we reach a null string (if max == -1).
func readString(r io.Reader, max int) string {
stringBuf := bytes.Buffer{}
if max == 0 {
return ""
}
var err error
var n int
b := make([]uint8, 1)
for {
n, err = r.Read(b)
if err == io.EOF || n != 1 {
break
} else if max < 0 && b[0] == 0 {
break
}
stringBuf.Write(b)
if max > 0 && stringBuf.Len() >= max {
break
}
}
return string(stringBuf.Bytes())
}