-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvarint.go
331 lines (271 loc) · 7.96 KB
/
varint.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
package varint
import (
"errors"
"fmt"
"io"
"math"
)
const (
// max bytes that can be received for one integer
MaxVarintLen32 = 5
MaxVarintLen64 = 10
)
// PutVarint encodes an int32 into buf and returns the number of bytes written.
// If the buffer is too small, PutVarint will panic.
// Try to allocate a buffer of MaxVarintLen32 bytes to avoid panics.
// Format: ESDDDDDD EDDDDDDD EDD... Extended, Sign, Data
// E: is next byte part of the current integer
// S: Sign of integer
// Data, Integer bits that follow the sign
func PutVarint(buf []byte, x int) int {
if x < math.MinInt32 || math.MaxInt32 < x {
panic("ERROR: value to Pack is out of bounds, should be within range [-2147483648:2147483647] (32bit)")
}
const intSize = 4
// stack allocated buffer
data := [MaxVarintLen32]byte{} // predefined content of zeroes
index := 0
data[index] = byte(x>>(intSize*8-7)) & 0b01000000 // set sign bit if i<0
x = x ^ (x >> (intSize*8 - 1)) // if(i<0) i = ~i
data[index] |= byte(x) & 0b00111111 // pack 6bit into data
x >>= 6 // discard 6 bits
if x != 0 {
data[index] |= 0b10000000 // set extend bit
for {
index++
data[index] = byte(x) & 0b01111111 // pack 7 bits
x >>= 7 // discard 7 bits
if x != 0 {
data[index] |= 1 << 7 // set extend bit
} else {
break // break if x is 0
}
}
}
size := index + 1
if len(buf) < size {
panic(fmt.Sprintf("varint buffer needs to have at least %d bytes but has %d", len(data), len(buf)))
}
return copy(buf, data[:size])
}
// Varint decodes an int from buf and returns that value and the number of bytes read (> 0).
// If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:
//
// n == 0: buf too small
// n < 0: value larger than 32 bits (overflow)
// and -n is the number of bytes read
func Varint(buf []byte) (i int, n int) {
if len(buf) == 0 {
return 0, 0
}
index := 0
// handle first byte (most right side)
sign := int((buf[index] >> 6) & 0b00000001)
value := int(buf[index] & 0b00111111)
// no E bit set, return after parsing first byte
if buf[index] < 0b10000000 {
value ^= -sign // if(sign) value = ~(value)
index++
return value, index
}
// handle 2nd - nth byte
buf = buf[1:]
const maxAllowedLen = MaxVarintLen32 - 1
for i, b := range buf {
index++
// overflow check
// 1 sign bit + 6 data bits = 7 bits
// 7 bits * 4 bytes = 28 bits
// 7 + 28 = 35 bits, 3 too many
// last byte can only have 4 bits
if i == maxAllowedLen-1 && b > 0b00001111 {
return 0, -(i + 1)
}
value |= int(b&0b01111111) << (6 + 7*i)
if b < 0b10000000 {
// no extend bit set
break
}
}
value ^= -sign // if(sign) value = ~(value)
index++
return value, index
}
// AppendVarint appends the varint-encoded form of x, as generated by PutVarint, to buf and returns the extended buffer.
func AppendVarint(buf []byte, x int) []byte {
arr := [MaxVarintLen32]byte{}
sbuf := arr[:]
n := PutVarint(sbuf, x)
sbuf = sbuf[:n]
return append(buf, sbuf...)
}
// ReadVarint can decode a stream of bytes
func ReadVarint(r io.ByteReader) (int, error) {
b, err := r.ReadByte()
if err != nil {
return 0, err
}
index := 0
// handle first byte (most right side)
sign := int((b >> 6) & 0b00000001)
value := int(b & 0b00111111)
// no E bit set, return after parsing first byte
if b < 0b10000000 {
value ^= -sign // if(sign) value = ~(value)
index++
return value, nil
}
// handle 2nd - nth byte
const maxAllowedLen = MaxVarintLen32 - 1
for i := 0; i < MaxVarintLen32; i++ {
b, err := r.ReadByte()
if err != nil {
if errors.Is(err, io.EOF) {
return value, io.ErrUnexpectedEOF
}
return value, nil
}
index++
// overflow check
// 1 sign bit + 6 data bits = 7 bits
// 7 bits * 4 bytes = 28 bits
// 7 + 28 = 35 bits, 3 too many
// 7 - 3 = 7 - 3 = last byte can only have 4 bits
if i == maxAllowedLen-1 && b > 0b00001111 {
return 0, errors.New("overflow due to invalid last byte")
}
value |= int(b&0b01111111) << (6 + 7*i)
if b < 0b10000000 {
break
}
}
value ^= -sign // if(sign) value = ~(value)
index++
return value, nil
}
// PutBigVarint is a variant of varint that can encode 64-bit integers.
// It is out of the scope of the Teeworlds protocol but can be used to check for potential security issues.
func PutBigVarint(buf []byte, x int64) int {
const intSize = 8
// stack allocated buffer
data := [MaxVarintLen64]byte{} // predefined content of zeroes
index := 0
data[index] = byte(x>>(intSize*8-7)) & 0b01000000 // set sign bit if i<0
x = x ^ (x >> (intSize*8 - 1)) // if(i<0) i = ~i
data[index] |= byte(x) & 0b00111111 // pack 6bit into data
x >>= 6 // discard 6 bits
if x != 0 {
data[index] |= 0b10000000 // set extend bit
for {
index++
data[index] = byte(x) & 0b01111111 // pack 7 bits
x >>= 7 // discard 7 bits
if x != 0 {
data[index] |= 1 << 7 // set extend bit
} else {
break // break if x is 0
}
}
}
size := index + 1
if len(buf) < size {
panic(fmt.Sprintf("varint buffer needs to have at least %d bytes but has %d", len(data), len(buf)))
}
return copy(buf, data[:size])
}
// Big decodes an int from buf and returns that value and the number of bytes read (> 0).
// If an error occurred, the value is 0 and the number of bytes n is <= 0 with the following meaning:
//
// n == 0: buf too small
// n < 0: value larger than 64 bits (overflow/underflow)
// and -n is the number of bytes read
func BigVarint(buf []byte) (i int64, n int) {
if len(buf) == 0 {
return 0, 0
}
index := 0
// handle first byte (most right side)
sign := int64((buf[index] >> 6) & 0b00000001)
value := int64(buf[index] & 0b00111111)
// no E bit set, return after parsing first byte
if buf[index] < 0b10000000 {
value ^= -sign // if(sign) value = ~(value)
index++
return value, index
}
// handle 2nd - nth byte
buf = buf[1:]
const maxAllowedLen = MaxVarintLen64 - 1
for i, b := range buf {
index++
// overflow check
// 1 sign bit + 6 data bits = 7 bits
// 7 bits * 9 bytes = 63 bits
// 7 + 63 = 70 bits, 6 too many
// 7 - 6 = last byte can only have 1 bit
if i == maxAllowedLen-1 && b > 0b00000001 {
return 0, -(i + 1)
}
value |= int64(b&0b01111111) << (6 + 7*i)
if b < 0b10000000 {
// no extend bit set
break
}
}
value ^= -sign // if(sign) value = ~(value)
index++
return value, index
}
// AppendBigVarint appends the varint-encoded form of x, as generated by PutBigVarint, to buf and returns the extended buffer.
// It is out of the scope of the Teeworlds protocol but can be used to check for potential security issues.
func AppendBigVarint(buf []byte, x int64) []byte {
arr := [MaxVarintLen64]byte{}
sbuf := arr[:]
n := PutBigVarint(sbuf, x)
sbuf = sbuf[:n]
return append(buf, sbuf...)
}
// ReadVarint can decode a stream of bytes
func ReadBigVarint(r io.ByteReader) (int64, error) {
b, err := r.ReadByte()
if err != nil {
return 0, err
}
index := 0
// handle first byte (most right side)
sign := int64((b >> 6) & 0b00000001)
value := int64(b & 0b00111111)
// no E bit set, return after parsing first byte
if b < 0b10000000 {
value ^= -sign // if(sign) value = ~(value)
index++
return value, nil
}
// handle 2nd - nth byte
const maxAllowedLen = MaxVarintLen64 - 1
for i := 0; i < MaxVarintLen64; i++ {
b, err := r.ReadByte()
if err != nil {
if errors.Is(err, io.EOF) {
return value, io.ErrUnexpectedEOF
}
return value, nil
}
index++
// overflow check
// 1 sign bit + 6 data bits = 7 bits
// 7 bits * 4 bytes = 28 bits
// 7 + 28 = 35 bits, 3 too many
// 7 - 3 = 7 - 3 = last byte can only have 4 bits
if i == maxAllowedLen-1 && b > 0b00000001 {
return 0, errors.New("overflow due to invalid last byte")
}
value |= int64(b&0b01111111) << (6 + 7*i)
if b < 0b10000000 {
break
}
}
value ^= -sign // if(sign) value = ~(value)
index++
return value, nil
}