wire.go 12 KB

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