aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/golang.org/x/text/internal/gen/bitfield/bitfield.go
blob: a8d0a48d8e02eee66bdf8843efa0adcc415fc6ed (plain) (blame)
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
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package bitfield converts annotated structs into integer values.
//
// Any field that is marked with a bitfield tag is compacted. The tag value has
// two parts. The part before the comma determines the method name for a
// generated type. If left blank the name of the field is used.
// The part after the comma determines the number of bits to use for the
// representation.
package bitfield

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

// Config determines settings for packing and generation. If a Config is used,
// the same Config should be used for packing and generation.
type Config struct {
	// NumBits fixes the maximum allowed bits for the integer representation.
	// If NumBits is not 8, 16, 32, or 64, the actual underlying integer size
	// will be the next largest available.
	NumBits uint

	// If Package is set, code generation will write a package clause.
	Package string

	// TypeName is the name for the generated type. By default it is the name
	// of the type of the value passed to Gen.
	TypeName string
}

var nullConfig = &Config{}

// Pack packs annotated bit ranges of struct x in an integer.
//
// Only fields that have a "bitfield" tag are compacted.
func Pack(x interface{}, c *Config) (packed uint64, err error) {
	packed, _, err = pack(x, c)
	return
}

func pack(x interface{}, c *Config) (packed uint64, nBit uint, err error) {
	if c == nil {
		c = nullConfig
	}
	nBits := c.NumBits
	v := reflect.ValueOf(x)
	v = reflect.Indirect(v)
	t := v.Type()
	pos := 64 - nBits
	if nBits == 0 {
		pos = 0
	}
	for i := 0; i < v.NumField(); i++ {
		v := v.Field(i)
		field := t.Field(i)
		f, err := parseField(field)

		if err != nil {
			return 0, 0, err
		}
		if f.nBits == 0 {
			continue
		}
		value := uint64(0)
		switch v.Kind() {
		case reflect.Bool:
			if v.Bool() {
				value = 1
			}
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			value = v.Uint()
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			x := v.Int()
			if x < 0 {
				return 0, 0, fmt.Errorf("bitfield: negative value for field %q not allowed", field.Name)
			}
			value = uint64(x)
		}
		if value > (1<<f.nBits)-1 {
			return 0, 0, fmt.Errorf("bitfield: value %#x of field %q does not fit in %d bits", value, field.Name, f.nBits)
		}
		shift := 64 - pos - f.nBits
		if pos += f.nBits; pos > 64 {
			return 0, 0, fmt.Errorf("bitfield: no more bits left for field %q", field.Name)
		}
		packed |= value << shift
	}
	if nBits == 0 {
		nBits = posToBits(pos)
		packed >>= (64 - nBits)
	}
	return packed, nBits, nil
}

type field struct {
	name  string
	value uint64
	nBits uint
}

// parseField parses a tag of the form [<name>][:<nBits>][,<pos>[..<end>]]
func parseField(field reflect.StructField) (f field, err error) {
	s, ok := field.Tag.Lookup("bitfield")
	if !ok {
		return f, nil
	}
	switch field.Type.Kind() {
	case reflect.Bool:
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
	default:
		return f, fmt.Errorf("bitfield: field %q is not an integer or bool type", field.Name)
	}
	bits := s
	f.name = ""

	if i := strings.IndexByte(s, ','); i >= 0 {
		bits = s[:i]
		f.name = s[i+1:]
	}
	if bits != "" {
		nBits, err := strconv.ParseUint(bits, 10, 8)
		if err != nil {
			return f, fmt.Errorf("bitfield: invalid bit size for field %q: %v", field.Name, err)
		}
		f.nBits = uint(nBits)
	}
	if f.nBits == 0 {
		if field.Type.Kind() == reflect.Bool {
			f.nBits = 1
		} else {
			f.nBits = uint(field.Type.Bits())
		}
	}
	if f.name == "" {
		f.name = field.Name
	}
	return f, err
}

func posToBits(pos uint) (bits uint) {
	switch {
	case pos <= 8:
		bits = 8
	case pos <= 16:
		bits = 16
	case pos <= 32:
		bits = 32
	case pos <= 64:
		bits = 64
	default:
		panic("unreachable")
	}
	return bits
}

// Gen generates code for unpacking integers created with Pack.
func Gen(w io.Writer, x interface{}, c *Config) error {
	if c == nil {
		c = nullConfig
	}
	_, nBits, err := pack(x, c)
	if err != nil {
		return err
	}

	t := reflect.TypeOf(x)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	if c.TypeName == "" {
		c.TypeName = t.Name()
	}
	firstChar := []rune(c.TypeName)[0]

	buf := &bytes.Buffer{}

	print := func(w io.Writer, format string, args ...interface{}) {
		if _, e := fmt.Fprintf(w, format+"\n", args...); e != nil && err == nil {
			err = fmt.Errorf("bitfield: write failed: %v", err)
		}
	}

	pos := uint(0)
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		f, _ := parseField(field)
		if f.nBits == 0 {
			continue
		}
		shift := nBits - pos - f.nBits
		pos += f.nBits

		retType := field.Type.Name()
		print(buf, "\nfunc (%c %s) %s() %s {", firstChar, c.TypeName, f.name, retType)
		if field.Type.Kind() == reflect.Bool {
			print(buf, "\tconst bit = 1 << %d", shift)
			print(buf, "\treturn %c&bit == bit", firstChar)
		} else {
			print(buf, "\treturn %s((%c >> %d) & %#x)", retType, firstChar, shift, (1<<f.nBits)-1)
		}
		print(buf, "}")
	}

	if c.Package != "" {
		print(w, "// Code generated by golang.org/x/text/internal/gen/bitfield. DO NOT EDIT.\n")
		print(w, "package %s\n", c.Package)
	}

	bits := posToBits(pos)

	print(w, "type %s uint%d", c.TypeName, bits)

	if _, err := io.Copy(w, buf); err != nil {
		return fmt.Errorf("bitfield: write failed: %v", err)
	}
	return nil
}