summaryrefslogtreecommitdiff
path: root/pkg/binstruct/structs.go
blob: 8ecea6a69c07c39b3d9839b0732f39aeb06ff30b (plain)
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
package binstruct

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

type End struct{}

var endType = reflect.TypeOf(End{})

type tag struct {
	skip bool

	off int
	siz int
}

func parseStructTag(str string) (tag, error) {
	var ret tag
	for _, part := range strings.Split(str, ",") {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		if part == "-" {
			return tag{skip: true}, nil
		}
		keyval := strings.SplitN(part, "=", 2)
		if len(keyval) != 2 {
			return tag{}, fmt.Errorf("option is not a key=value pair: %q", part)
		}
		key := keyval[0]
		val := keyval[1]
		switch key {
		case "off":
			vint, err := strconv.ParseInt(val, 0, 0)
			if err != nil {
				return tag{}, err
			}
			ret.off = int(vint)
		case "siz":
			vint, err := strconv.ParseInt(val, 0, 0)
			if err != nil {
				return tag{}, err
			}
			ret.siz = int(vint)
		default:
			return tag{}, fmt.Errorf("unrecognized option %q", key)
		}
	}
	return ret, nil
}

type structHandler struct {
	name   string
	Size   int
	fields []structField
}

type structField struct {
	name string
	tag
}

func (sh structHandler) Unmarshal(dat []byte, dst reflect.Value) (int, error) {
	var n int
	for i, field := range sh.fields {
		if field.skip {
			continue
		}
		_n, err := Unmarshal(dat[n:], dst.Field(i).Addr().Interface())
		if err != nil {
			if _n >= 0 {
				n += _n
			}
			return n, fmt.Errorf("struct %q field %d %q: %w",
				sh.name, i, field.name, err)
		}
		if _n != field.siz {
			return n, fmt.Errorf("struct %q field %d %q: consumed %d bytes but should have consumed %d bytes",
				sh.name, i, field.name, _n, field.siz)
		}
		n += _n
	}
	return n, nil
}

func (sh structHandler) Marshal(val reflect.Value) ([]byte, error) {
	ret := make([]byte, 0, sh.Size)
	for i, field := range sh.fields {
		if field.skip {
			continue
		}
		bs, err := Marshal(val.Field(i).Interface())
		ret = append(ret, bs...)
		if err != nil {
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				sh.name, i, field.name, err)
		}
	}
	return ret, nil
}

func genStructHandler(structInfo reflect.Type) (structHandler, error) {
	var ret structHandler

	ret.name = structInfo.String()

	var curOffset, endOffset int
	for i := 0; i < structInfo.NumField(); i++ {
		var fieldInfo reflect.StructField = structInfo.Field(i)

		if fieldInfo.Anonymous && fieldInfo.Type != endType {
			err := fmt.Errorf("binstruct does not support embedded fields")
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				ret.name, i, fieldInfo.Name, err)
		}

		fieldTag, err := parseStructTag(fieldInfo.Tag.Get("bin"))
		if err != nil {
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				ret.name, i, fieldInfo.Name, err)
		}
		if fieldTag.skip {
			ret.fields = append(ret.fields, structField{
				tag:  fieldTag,
				name: fieldInfo.Name,
			})
			continue
		}

		if fieldTag.off != curOffset {
			err := fmt.Errorf("tag says off=0x%x but curOffset=0x%x", fieldTag.off, curOffset)
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				ret.name, i, fieldInfo.Name, err)
		}
		if fieldInfo.Type == endType {
			endOffset = curOffset
		}

		fieldSize, err := staticSize(fieldInfo.Type)
		if err != nil {
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				ret.name, i, fieldInfo.Name, err)
		}

		if fieldTag.siz != fieldSize {
			err := fmt.Errorf("tag says siz=0x%x but StaticSize(typ)=0x%x", fieldTag.siz, fieldSize)
			return ret, fmt.Errorf("struct %q field %d %q: %w",
				ret.name, i, fieldInfo.Name, err)
		}
		curOffset += fieldTag.siz

		ret.fields = append(ret.fields, structField{
			name: fieldInfo.Name,
			tag:  fieldTag,
		})
	}
	ret.Size = curOffset

	if ret.Size != endOffset {
		return ret, fmt.Errorf("struct %q: .Size=%v but endOffset=%v",
			ret.name, ret.Size, endOffset)
	}

	return ret, nil
}

var structCache = make(map[reflect.Type]structHandler)

func getStructHandler(typ reflect.Type) structHandler {
	h, ok := structCache[typ]
	if ok {
		return h
	}

	h, err := genStructHandler(typ)
	if err != nil {
		panic(err)
	}
	structCache[typ] = h
	return h
}