blob: d7baa7f10a26bae0c77fcb10e953541c09a75936 [file] [log] [blame]
Joe Tsai22505a42018-08-01 13:12:49 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package wire parses and formats the protobuf wire encoding.
6//
7// See https://developers.google.com/protocol-buffers/docs/encoding.
8package wire
9
10import (
Joe Tsai22505a42018-08-01 13:12:49 -070011 "io"
Joe Tsai972d8732019-05-07 14:10:25 -070012 "math"
Joe Tsai22505a42018-08-01 13:12:49 -070013 "math/bits"
Joe Tsai0e6baaa2018-08-03 17:55:44 -070014
Damien Neile89e6242019-05-13 23:55:40 -070015 "google.golang.org/protobuf/internal/errors"
Joe Tsai22505a42018-08-01 13:12:49 -070016)
17
18// Number represents the field number.
19type Number int32
20
21const (
22 MinValidNumber Number = 1
23 FirstReservedNumber Number = 19000
24 LastReservedNumber Number = 19999
25 MaxValidNumber Number = 1<<29 - 1
26)
27
28// IsValid reports whether the field number is semantically valid.
29//
30// Note that while numbers within the reserved range are semantically invalid,
31// they are syntactically valid in the wire format.
32// Implementations may treat records with reserved field numbers as unknown.
33func (n Number) IsValid() bool {
34 return MinValidNumber <= n && n < FirstReservedNumber || LastReservedNumber < n && n <= MaxValidNumber
35}
36
37// Type represents the wire type.
38type Type int8
39
40const (
41 VarintType Type = 0
42 Fixed32Type Type = 5
43 Fixed64Type Type = 1
44 BytesType Type = 2
45 StartGroupType Type = 3
46 EndGroupType Type = 4
47)
48
49const (
50 _ = -iota
51 errCodeTruncated
52 errCodeFieldNumber
53 errCodeOverflow
54 errCodeReserved
55 errCodeEndGroup
56)
57
58var (
59 errFieldNumber = errors.New("invalid field number")
60 errOverflow = errors.New("variable length integer overflow")
61 errReserved = errors.New("cannot parse reserved wire type")
62 errEndGroup = errors.New("mismatching end group marker")
63 errParse = errors.New("parse error")
64)
65
66// ParseError converts an error code into an error value.
67// This returns nil if n is a non-negative number.
68func ParseError(n int) error {
69 if n >= 0 {
70 return nil
71 }
72 switch n {
73 case errCodeTruncated:
74 return io.ErrUnexpectedEOF
75 case errCodeFieldNumber:
76 return errFieldNumber
77 case errCodeOverflow:
78 return errOverflow
79 case errCodeReserved:
80 return errReserved
81 case errCodeEndGroup:
82 return errEndGroup
83 default:
84 return errParse
85 }
86}
87
88// ConsumeField parses an entire field record (both tag and value) and returns
89// the field number, the wire type, and the total length.
90// This returns a negative length upon an error (see ParseError).
91//
92// The total length includes the tag header and the end group marker (if the
93// field is a group).
94func ConsumeField(b []byte) (Number, Type, int) {
95 num, typ, n := ConsumeTag(b)
96 if n < 0 {
97 return 0, 0, n // forward error code
98 }
99 m := ConsumeFieldValue(num, typ, b[n:])
100 if m < 0 {
101 return 0, 0, m // forward error code
102 }
103 return num, typ, n + m
104}
105
106// ConsumeFieldValue parses a field value and returns its length.
107// This assumes that the field Number and wire Type have already been parsed.
108// This returns a negative length upon an error (see ParseError).
109//
110// When parsing a group, the length includes the end group marker and
111// the end group is verified to match the starting field number.
112func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) {
113 switch typ {
114 case VarintType:
115 _, n = ConsumeVarint(b)
116 return n
117 case Fixed32Type:
118 _, n = ConsumeFixed32(b)
119 return n
120 case Fixed64Type:
121 _, n = ConsumeFixed64(b)
122 return n
123 case BytesType:
124 _, n = ConsumeBytes(b)
125 return n
126 case StartGroupType:
127 n0 := len(b)
128 for {
129 num2, typ2, n := ConsumeTag(b)
130 if n < 0 {
131 return n // forward error code
132 }
133 b = b[n:]
134 if typ2 == EndGroupType {
135 if num != num2 {
136 return errCodeEndGroup
137 }
138 return n0 - len(b)
139 }
140
141 n = ConsumeFieldValue(num2, typ2, b)
142 if n < 0 {
143 return n // forward error code
144 }
145 b = b[n:]
146 }
147 case EndGroupType:
148 return errCodeEndGroup
149 default:
150 return errCodeReserved
151 }
152}
153
154// AppendTag encodes num and typ as a varint-encoded tag and appends it to b.
155func AppendTag(b []byte, num Number, typ Type) []byte {
156 return AppendVarint(b, EncodeTag(num, typ))
157}
158
159// ConsumeTag parses b as a varint-encoded tag, reporting its length.
160// This returns a negative length upon an error (see ParseError).
161func ConsumeTag(b []byte) (Number, Type, int) {
162 v, n := ConsumeVarint(b)
163 if n < 0 {
164 return 0, 0, n // forward error code
165 }
166 num, typ := DecodeTag(v)
167 if num < MinValidNumber {
168 return 0, 0, errCodeFieldNumber
169 }
170 return num, typ, n
171}
172
173func SizeTag(num Number) int {
174 return SizeVarint(EncodeTag(num, 0)) // wire type has no effect on size
175}
176
177// AppendVarint appends v to b as a varint-encoded uint64.
178func AppendVarint(b []byte, v uint64) []byte {
Joe Tsai22505a42018-08-01 13:12:49 -0700179 switch {
180 case v < 1<<7:
181 b = append(b, byte(v))
182 case v < 1<<14:
183 b = append(b,
184 byte((v>>0)&0x7f|0x80),
185 byte(v>>7))
186 case v < 1<<21:
187 b = append(b,
188 byte((v>>0)&0x7f|0x80),
189 byte((v>>7)&0x7f|0x80),
190 byte(v>>14))
191 case v < 1<<28:
192 b = append(b,
193 byte((v>>0)&0x7f|0x80),
194 byte((v>>7)&0x7f|0x80),
195 byte((v>>14)&0x7f|0x80),
196 byte(v>>21))
197 case v < 1<<35:
198 b = append(b,
199 byte((v>>0)&0x7f|0x80),
200 byte((v>>7)&0x7f|0x80),
201 byte((v>>14)&0x7f|0x80),
202 byte((v>>21)&0x7f|0x80),
203 byte(v>>28))
204 case v < 1<<42:
205 b = append(b,
206 byte((v>>0)&0x7f|0x80),
207 byte((v>>7)&0x7f|0x80),
208 byte((v>>14)&0x7f|0x80),
209 byte((v>>21)&0x7f|0x80),
210 byte((v>>28)&0x7f|0x80),
211 byte(v>>35))
212 case v < 1<<49:
213 b = append(b,
214 byte((v>>0)&0x7f|0x80),
215 byte((v>>7)&0x7f|0x80),
216 byte((v>>14)&0x7f|0x80),
217 byte((v>>21)&0x7f|0x80),
218 byte((v>>28)&0x7f|0x80),
219 byte((v>>35)&0x7f|0x80),
220 byte(v>>42))
221 case v < 1<<56:
222 b = append(b,
223 byte((v>>0)&0x7f|0x80),
224 byte((v>>7)&0x7f|0x80),
225 byte((v>>14)&0x7f|0x80),
226 byte((v>>21)&0x7f|0x80),
227 byte((v>>28)&0x7f|0x80),
228 byte((v>>35)&0x7f|0x80),
229 byte((v>>42)&0x7f|0x80),
230 byte(v>>49))
231 case v < 1<<63:
232 b = append(b,
233 byte((v>>0)&0x7f|0x80),
234 byte((v>>7)&0x7f|0x80),
235 byte((v>>14)&0x7f|0x80),
236 byte((v>>21)&0x7f|0x80),
237 byte((v>>28)&0x7f|0x80),
238 byte((v>>35)&0x7f|0x80),
239 byte((v>>42)&0x7f|0x80),
240 byte((v>>49)&0x7f|0x80),
241 byte(v>>56))
242 default:
243 b = append(b,
244 byte((v>>0)&0x7f|0x80),
245 byte((v>>7)&0x7f|0x80),
246 byte((v>>14)&0x7f|0x80),
247 byte((v>>21)&0x7f|0x80),
248 byte((v>>28)&0x7f|0x80),
249 byte((v>>35)&0x7f|0x80),
250 byte((v>>42)&0x7f|0x80),
251 byte((v>>49)&0x7f|0x80),
252 byte((v>>56)&0x7f|0x80),
253 1)
254 }
255 return b
256}
257
258// ConsumeVarint parses b as a varint-encoded uint64, reporting its length.
259// This returns a negative length upon an error (see ParseError).
260func ConsumeVarint(b []byte) (v uint64, n int) {
Joe Tsai22505a42018-08-01 13:12:49 -0700261 var y uint64
262 if len(b) <= 0 {
263 return 0, errCodeTruncated
264 }
265 v = uint64(b[0])
266 if v < 0x80 {
267 return v, 1
268 }
269 v -= 0x80
270
271 if len(b) <= 1 {
272 return 0, errCodeTruncated
273 }
274 y = uint64(b[1])
275 v += y << 7
276 if y < 0x80 {
277 return v, 2
278 }
279 v -= 0x80 << 7
280
281 if len(b) <= 2 {
282 return 0, errCodeTruncated
283 }
284 y = uint64(b[2])
285 v += y << 14
286 if y < 0x80 {
287 return v, 3
288 }
289 v -= 0x80 << 14
290
291 if len(b) <= 3 {
292 return 0, errCodeTruncated
293 }
294 y = uint64(b[3])
295 v += y << 21
296 if y < 0x80 {
297 return v, 4
298 }
299 v -= 0x80 << 21
300
301 if len(b) <= 4 {
302 return 0, errCodeTruncated
303 }
304 y = uint64(b[4])
305 v += y << 28
306 if y < 0x80 {
307 return v, 5
308 }
309 v -= 0x80 << 28
310
311 if len(b) <= 5 {
312 return 0, errCodeTruncated
313 }
314 y = uint64(b[5])
315 v += y << 35
316 if y < 0x80 {
317 return v, 6
318 }
319 v -= 0x80 << 35
320
321 if len(b) <= 6 {
322 return 0, errCodeTruncated
323 }
324 y = uint64(b[6])
325 v += y << 42
326 if y < 0x80 {
327 return v, 7
328 }
329 v -= 0x80 << 42
330
331 if len(b) <= 7 {
332 return 0, errCodeTruncated
333 }
334 y = uint64(b[7])
335 v += y << 49
336 if y < 0x80 {
337 return v, 8
338 }
339 v -= 0x80 << 49
340
341 if len(b) <= 8 {
342 return 0, errCodeTruncated
343 }
344 y = uint64(b[8])
345 v += y << 56
346 if y < 0x80 {
347 return v, 9
348 }
349 v -= 0x80 << 56
350
351 if len(b) <= 9 {
352 return 0, errCodeTruncated
353 }
354 y = uint64(b[9])
355 v += y << 63
356 if y < 2 {
357 return v, 10
358 }
359 return 0, errCodeOverflow
360}
361
362// SizeVarint returns the encoded size of a varint.
363// The size is guaranteed to be within 1 and 10, inclusive.
364func SizeVarint(v uint64) int {
365 return 1 + (bits.Len64(v)-1)/7
366}
367
368// AppendFixed32 appends v to b as a little-endian uint32.
369func AppendFixed32(b []byte, v uint32) []byte {
370 return append(b,
371 byte(v>>0),
372 byte(v>>8),
373 byte(v>>16),
374 byte(v>>24))
375}
376
377// ConsumeFixed32 parses b as a little-endian uint32, reporting its length.
378// This returns a negative length upon an error (see ParseError).
379func ConsumeFixed32(b []byte) (v uint32, n int) {
380 if len(b) < 4 {
381 return 0, errCodeTruncated
382 }
383 v = uint32(b[0])<<0 | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
384 return v, 4
385}
386
387// SizeFixed32 returns the encoded size of a fixed32; which is always 4.
388func SizeFixed32() int {
389 return 4
390}
391
392// AppendFixed64 appends v to b as a little-endian uint64.
393func AppendFixed64(b []byte, v uint64) []byte {
394 return append(b,
395 byte(v>>0),
396 byte(v>>8),
397 byte(v>>16),
398 byte(v>>24),
399 byte(v>>32),
400 byte(v>>40),
401 byte(v>>48),
402 byte(v>>56))
403}
404
405// ConsumeFixed64 parses b as a little-endian uint64, reporting its length.
406// This returns a negative length upon an error (see ParseError).
407func ConsumeFixed64(b []byte) (v uint64, n int) {
408 if len(b) < 8 {
409 return 0, errCodeTruncated
410 }
411 v = uint64(b[0])<<0 | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
412 return v, 8
413}
414
415// SizeFixed64 returns the encoded size of a fixed64; which is always 8.
416func SizeFixed64() int {
417 return 8
418}
419
420// AppendBytes appends v to b as a length-prefixed bytes value.
421func AppendBytes(b []byte, v []byte) []byte {
422 return append(AppendVarint(b, uint64(len(v))), v...)
423}
424
425// ConsumeBytes parses b as a length-prefixed bytes value, reporting its length.
426// This returns a negative length upon an error (see ParseError).
427func ConsumeBytes(b []byte) (v []byte, n int) {
428 m, n := ConsumeVarint(b)
429 if n < 0 {
430 return nil, n // forward error code
431 }
432 if m > uint64(len(b[n:])) {
433 return nil, errCodeTruncated
434 }
435 return b[n:][:m], n + int(m)
436}
437
438// SizeBytes returns the encoded size of a length-prefixed bytes value,
439// given only the length.
440func SizeBytes(n int) int {
441 return SizeVarint(uint64(n)) + n
442}
443
Damien Neile91877d2019-06-27 10:54:42 -0700444// AppendString appends v to b as a length-prefixed bytes value.
445func AppendString(b []byte, v string) []byte {
446 return append(AppendVarint(b, uint64(len(v))), v...)
447}
448
449// ConsumeString parses b as a length-prefixed bytes value, reporting its length.
450// This returns a negative length upon an error (see ParseError).
451func ConsumeString(b []byte) (v string, n int) {
452 bb, n := ConsumeBytes(b)
453 return string(bb), n
454}
455
Joe Tsai22505a42018-08-01 13:12:49 -0700456// AppendGroup appends v to b as group value, with a trailing end group marker.
457// The value v must not contain the end marker.
458func AppendGroup(b []byte, num Number, v []byte) []byte {
459 return AppendVarint(append(b, v...), EncodeTag(num, EndGroupType))
460}
461
462// ConsumeGroup parses b as a group value until the trailing end group marker,
463// and verifies that the end marker matches the provided num. The value v
464// does not contain the end marker, while the length does contain the end marker.
465// This returns a negative length upon an error (see ParseError).
466func ConsumeGroup(num Number, b []byte) (v []byte, n int) {
467 n = ConsumeFieldValue(num, StartGroupType, b)
468 if n < 0 {
469 return nil, n // forward error code
470 }
471 b = b[:n]
472
473 // Truncate off end group marker, but need to handle denormalized varints.
474 // Assuming end marker is never 0 (which is always the case since
475 // EndGroupType is non-zero), we can truncate all trailing bytes where the
476 // lower 7 bits are all zero (implying that the varint is denormalized).
477 for len(b) > 0 && b[len(b)-1]&0x7f == 0 {
478 b = b[:len(b)-1]
479 }
480 b = b[:len(b)-SizeTag(num)]
481 return b, n
482}
483
484// SizeGroup returns the encoded size of a group, given only the length.
485func SizeGroup(num Number, n int) int {
486 return n + SizeTag(num)
487}
488
489// DecodeTag decodes the field Number and wire Type from its unified form.
Damien Neilfe15dd42019-12-06 15:36:03 -0800490// The Number is -1 if the decoded field number overflows int32.
Joe Tsai22505a42018-08-01 13:12:49 -0700491// Other than overflow, this does not check for field number validity.
492func DecodeTag(x uint64) (Number, Type) {
Joe Tsai972d8732019-05-07 14:10:25 -0700493 // NOTE: MessageSet allows for larger field numbers than normal.
Damien Neilfe15dd42019-12-06 15:36:03 -0800494 if x>>3 > uint64(math.MaxInt32) {
495 return -1, 0
Joe Tsai22505a42018-08-01 13:12:49 -0700496 }
Joe Tsai972d8732019-05-07 14:10:25 -0700497 return Number(x >> 3), Type(x & 7)
Joe Tsai22505a42018-08-01 13:12:49 -0700498}
499
500// EncodeTag encodes the field Number and wire Type into its unified form.
501func EncodeTag(num Number, typ Type) uint64 {
502 return uint64(num)<<3 | uint64(typ&7)
503}
504
505// DecodeZigZag decodes a zig-zag-encoded uint64 as an int64.
506// Input: {…, 5, 3, 1, 0, 2, 4, 6, …}
507// Output: {…, -3, -2, -1, 0, +1, +2, +3, …}
508func DecodeZigZag(x uint64) int64 {
509 return int64(x>>1) ^ int64(x)<<63>>63
510}
511
512// EncodeZigZag encodes an int64 as a zig-zag-encoded uint64.
513// Input: {…, -3, -2, -1, 0, +1, +2, +3, …}
514// Output: {…, 5, 3, 1, 0, 2, 4, 6, …}
515func EncodeZigZag(x int64) uint64 {
516 return uint64(x<<1) ^ uint64(x>>63)
517}
518
519// DecodeBool decodes a uint64 as a bool.
520// Input: { 0, 1, 2, …}
521// Output: {false, true, true, …}
522func DecodeBool(x uint64) bool {
523 return x != 0
524}
525
526// EncodeBool encodes a bool as a uint64.
527// Input: {false, true}
528// Output: { 0, 1}
529func EncodeBool(x bool) uint64 {
530 if x {
531 return 1
532 }
533 return 0
534}