BinaryDecoder.swift 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. // Sources/SwiftProtobuf/BinaryDecoder.swift - Binary decoding
  2. //
  3. // Copyright (c) 2014 - 2016 Apple Inc. and the project authors
  4. // Licensed under Apache License v2.0 with Runtime Library Exception
  5. //
  6. // See LICENSE.txt for license information:
  7. // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
  8. //
  9. // -----------------------------------------------------------------------------
  10. ///
  11. /// Protobuf binary format decoding engine.
  12. ///
  13. /// This provides the Decoder interface that interacts directly
  14. /// with the generated code.
  15. ///
  16. // -----------------------------------------------------------------------------
  17. import Foundation
  18. internal struct BinaryDecoder: Decoder {
  19. // Current position
  20. private var p: UnsafeRawPointer
  21. // Remaining bytes in input.
  22. private var available: Int
  23. // Position of start of field currently being parsed
  24. private var fieldStartP: UnsafeRawPointer
  25. // Position of end of field currently being parsed, nil if we don't know.
  26. private var fieldEndP: UnsafeRawPointer?
  27. // Whether or not the field value has actually been parsed
  28. private var consumed = true
  29. // Wire format for last-examined field
  30. internal var fieldWireFormat = WireFormat.varint
  31. // Field number for last-parsed field tag
  32. private var fieldNumber: Int = 0
  33. // Collection of extension fields for this decode
  34. private var extensions: (any ExtensionMap)?
  35. // The current group number. See decodeFullGroup(group:fieldNumber:) for how
  36. // this is used.
  37. private var groupFieldNumber: Int?
  38. // The options for decoding.
  39. private var options: BinaryDecodingOptions
  40. private var recursionBudget: Int
  41. // Collects the unknown data found while decoding a message.
  42. private var unknownData: Data?
  43. // Custom data to use as the unknown data while parsing a field. Used only by
  44. // packed repeated enums; see below
  45. private var unknownOverride: Data?
  46. private var complete: Bool { available == 0 }
  47. internal init(
  48. forReadingFrom pointer: UnsafeRawPointer,
  49. count: Int,
  50. options: BinaryDecodingOptions,
  51. extensions: (any ExtensionMap)? = nil
  52. ) {
  53. // Assuming baseAddress is not nil.
  54. p = pointer
  55. available = count
  56. fieldStartP = p
  57. self.extensions = extensions
  58. self.options = options
  59. recursionBudget = options.messageDepthLimit
  60. }
  61. internal init(
  62. forReadingFrom pointer: UnsafeRawPointer,
  63. count: Int,
  64. parent: BinaryDecoder
  65. ) {
  66. self.init(
  67. forReadingFrom: pointer,
  68. count: count,
  69. options: parent.options,
  70. extensions: parent.extensions
  71. )
  72. recursionBudget = parent.recursionBudget
  73. }
  74. private mutating func incrementRecursionDepth() throws {
  75. recursionBudget -= 1
  76. if recursionBudget < 0 {
  77. throw BinaryDecodingError.messageDepthLimit
  78. }
  79. }
  80. private mutating func decrementRecursionDepth() {
  81. recursionBudget += 1
  82. // This should never happen, if it does, something is probably corrupting memory, and
  83. // simply throwing doesn't make much sense.
  84. if recursionBudget > options.messageDepthLimit {
  85. fatalError("Somehow BinaryDecoding unwound more objects than it started")
  86. }
  87. }
  88. internal mutating func handleConflictingOneOf() throws {
  89. /// Protobuf simply allows conflicting oneof values to overwrite
  90. }
  91. /// Return the next field number or nil if there are no more fields.
  92. internal mutating func nextFieldNumber() throws -> Int? {
  93. // Since this is called for every field, I've taken some pains
  94. // to optimize it, including unrolling a tweaked version of
  95. // the varint parser.
  96. if fieldNumber > 0 {
  97. if let override = unknownOverride {
  98. assert(!options.discardUnknownFields)
  99. assert(fieldWireFormat != .startGroup && fieldWireFormat != .endGroup)
  100. if unknownData == nil {
  101. unknownData = override
  102. } else {
  103. unknownData!.append(override)
  104. }
  105. unknownOverride = nil
  106. } else if !consumed {
  107. if options.discardUnknownFields {
  108. try skip()
  109. } else {
  110. let u = try getRawField()
  111. if unknownData == nil {
  112. unknownData = u
  113. } else {
  114. unknownData!.append(u)
  115. }
  116. }
  117. }
  118. }
  119. // Quit if end of input
  120. if available == 0 {
  121. return nil
  122. }
  123. // Get the next field number
  124. fieldStartP = p
  125. fieldEndP = nil
  126. let start = p
  127. let c0 = start[0]
  128. if let wireFormat = WireFormat(rawValue: c0 & 7) {
  129. fieldWireFormat = wireFormat
  130. } else {
  131. throw BinaryDecodingError.malformedProtobuf
  132. }
  133. if (c0 & 0x80) == 0 {
  134. p += 1
  135. available -= 1
  136. fieldNumber = Int(c0) >> 3
  137. } else {
  138. fieldNumber = Int(c0 & 0x7f) >> 3
  139. if available < 2 {
  140. throw BinaryDecodingError.malformedProtobuf
  141. }
  142. let c1 = start[1]
  143. if (c1 & 0x80) == 0 {
  144. p += 2
  145. available -= 2
  146. fieldNumber |= Int(c1) << 4
  147. } else {
  148. fieldNumber |= Int(c1 & 0x7f) << 4
  149. if available < 3 {
  150. throw BinaryDecodingError.malformedProtobuf
  151. }
  152. let c2 = start[2]
  153. fieldNumber |= Int(c2 & 0x7f) << 11
  154. if (c2 & 0x80) == 0 {
  155. p += 3
  156. available -= 3
  157. } else {
  158. if available < 4 {
  159. throw BinaryDecodingError.malformedProtobuf
  160. }
  161. let c3 = start[3]
  162. fieldNumber |= Int(c3 & 0x7f) << 18
  163. if (c3 & 0x80) == 0 {
  164. p += 4
  165. available -= 4
  166. } else {
  167. if available < 5 {
  168. throw BinaryDecodingError.malformedProtobuf
  169. }
  170. let c4 = start[4]
  171. if c4 > 15 {
  172. throw BinaryDecodingError.malformedProtobuf
  173. }
  174. fieldNumber |= Int(c4 & 0x7f) << 25
  175. p += 5
  176. available -= 5
  177. }
  178. }
  179. }
  180. }
  181. if fieldNumber != 0 {
  182. consumed = false
  183. if fieldWireFormat == .endGroup {
  184. if groupFieldNumber == fieldNumber {
  185. // Reached the end of the current group, single the
  186. // end of the message.
  187. return nil
  188. } else {
  189. // .endGroup when not in a group or for a different
  190. // group is an invalid binary.
  191. throw BinaryDecodingError.malformedProtobuf
  192. }
  193. }
  194. return fieldNumber
  195. }
  196. throw BinaryDecodingError.malformedProtobuf
  197. }
  198. internal mutating func decodeSingularFloatField(value: inout Float) throws {
  199. guard fieldWireFormat == WireFormat.fixed32 else {
  200. return
  201. }
  202. value = try decodeFloat()
  203. consumed = true
  204. }
  205. internal mutating func decodeSingularFloatField(value: inout Float?) throws {
  206. guard fieldWireFormat == WireFormat.fixed32 else {
  207. return
  208. }
  209. value = try decodeFloat()
  210. consumed = true
  211. }
  212. internal mutating func decodeRepeatedFloatField(value: inout [Float]) throws {
  213. switch fieldWireFormat {
  214. case WireFormat.fixed32:
  215. let i = try decodeFloat()
  216. value.append(i)
  217. consumed = true
  218. case WireFormat.lengthDelimited:
  219. let bodyBytes = try decodeVarint()
  220. if bodyBytes > 0 {
  221. let itemSize = UInt64(MemoryLayout<Float>.size)
  222. let itemCount = bodyBytes / itemSize
  223. if bodyBytes % itemSize != 0 || bodyBytes > available {
  224. throw BinaryDecodingError.truncated
  225. }
  226. value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount))
  227. for _ in 1...itemCount {
  228. value.append(try decodeFloat())
  229. }
  230. }
  231. consumed = true
  232. default:
  233. return
  234. }
  235. }
  236. internal mutating func decodeSingularDoubleField(value: inout Double) throws {
  237. guard fieldWireFormat == WireFormat.fixed64 else {
  238. return
  239. }
  240. value = try decodeDouble()
  241. consumed = true
  242. }
  243. internal mutating func decodeSingularDoubleField(value: inout Double?) throws {
  244. guard fieldWireFormat == WireFormat.fixed64 else {
  245. return
  246. }
  247. value = try decodeDouble()
  248. consumed = true
  249. }
  250. internal mutating func decodeRepeatedDoubleField(value: inout [Double]) throws {
  251. switch fieldWireFormat {
  252. case WireFormat.fixed64:
  253. let i = try decodeDouble()
  254. value.append(i)
  255. consumed = true
  256. case WireFormat.lengthDelimited:
  257. let bodyBytes = try decodeVarint()
  258. if bodyBytes > 0 {
  259. let itemSize = UInt64(MemoryLayout<Double>.size)
  260. let itemCount = bodyBytes / itemSize
  261. if bodyBytes % itemSize != 0 || bodyBytes > available {
  262. throw BinaryDecodingError.truncated
  263. }
  264. value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount))
  265. for _ in 1...itemCount {
  266. let i = try decodeDouble()
  267. value.append(i)
  268. }
  269. }
  270. consumed = true
  271. default:
  272. return
  273. }
  274. }
  275. internal mutating func decodeSingularInt32Field(value: inout Int32) throws {
  276. guard fieldWireFormat == WireFormat.varint else {
  277. return
  278. }
  279. let varint = try decodeVarint()
  280. value = Int32(truncatingIfNeeded: varint)
  281. consumed = true
  282. }
  283. internal mutating func decodeSingularInt32Field(value: inout Int32?) throws {
  284. guard fieldWireFormat == WireFormat.varint else {
  285. return
  286. }
  287. let varint = try decodeVarint()
  288. value = Int32(truncatingIfNeeded: varint)
  289. consumed = true
  290. }
  291. internal mutating func decodeRepeatedInt32Field(value: inout [Int32]) throws {
  292. switch fieldWireFormat {
  293. case WireFormat.varint:
  294. let varint = try decodeVarint()
  295. value.append(Int32(truncatingIfNeeded: varint))
  296. consumed = true
  297. case WireFormat.lengthDelimited:
  298. var n: Int = 0
  299. let p = try getFieldBodyBytes(count: &n)
  300. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  301. value.reserveCapacity(value.count + ints)
  302. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  303. while !decoder.complete {
  304. let varint = try decoder.decodeVarint()
  305. value.append(Int32(truncatingIfNeeded: varint))
  306. }
  307. consumed = true
  308. default:
  309. return
  310. }
  311. }
  312. internal mutating func decodeSingularInt64Field(value: inout Int64) throws {
  313. guard fieldWireFormat == WireFormat.varint else {
  314. return
  315. }
  316. let v = try decodeVarint()
  317. value = Int64(bitPattern: v)
  318. consumed = true
  319. }
  320. internal mutating func decodeSingularInt64Field(value: inout Int64?) throws {
  321. guard fieldWireFormat == WireFormat.varint else {
  322. return
  323. }
  324. let varint = try decodeVarint()
  325. value = Int64(bitPattern: varint)
  326. consumed = true
  327. }
  328. internal mutating func decodeRepeatedInt64Field(value: inout [Int64]) throws {
  329. switch fieldWireFormat {
  330. case WireFormat.varint:
  331. let varint = try decodeVarint()
  332. value.append(Int64(bitPattern: varint))
  333. consumed = true
  334. case WireFormat.lengthDelimited:
  335. var n: Int = 0
  336. let p = try getFieldBodyBytes(count: &n)
  337. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  338. value.reserveCapacity(value.count + ints)
  339. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  340. while !decoder.complete {
  341. let varint = try decoder.decodeVarint()
  342. value.append(Int64(bitPattern: varint))
  343. }
  344. consumed = true
  345. default:
  346. return
  347. }
  348. }
  349. internal mutating func decodeSingularUInt32Field(value: inout UInt32) throws {
  350. guard fieldWireFormat == WireFormat.varint else {
  351. return
  352. }
  353. let varint = try decodeVarint()
  354. value = UInt32(truncatingIfNeeded: varint)
  355. consumed = true
  356. }
  357. internal mutating func decodeSingularUInt32Field(value: inout UInt32?) throws {
  358. guard fieldWireFormat == WireFormat.varint else {
  359. return
  360. }
  361. let varint = try decodeVarint()
  362. value = UInt32(truncatingIfNeeded: varint)
  363. consumed = true
  364. }
  365. internal mutating func decodeRepeatedUInt32Field(value: inout [UInt32]) throws {
  366. switch fieldWireFormat {
  367. case WireFormat.varint:
  368. let varint = try decodeVarint()
  369. value.append(UInt32(truncatingIfNeeded: varint))
  370. consumed = true
  371. case WireFormat.lengthDelimited:
  372. var n: Int = 0
  373. let p = try getFieldBodyBytes(count: &n)
  374. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  375. value.reserveCapacity(value.count + ints)
  376. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  377. while !decoder.complete {
  378. let t = try decoder.decodeVarint()
  379. value.append(UInt32(truncatingIfNeeded: t))
  380. }
  381. consumed = true
  382. default:
  383. return
  384. }
  385. }
  386. internal mutating func decodeSingularUInt64Field(value: inout UInt64) throws {
  387. guard fieldWireFormat == WireFormat.varint else {
  388. return
  389. }
  390. value = try decodeVarint()
  391. consumed = true
  392. }
  393. internal mutating func decodeSingularUInt64Field(value: inout UInt64?) throws {
  394. guard fieldWireFormat == WireFormat.varint else {
  395. return
  396. }
  397. value = try decodeVarint()
  398. consumed = true
  399. }
  400. internal mutating func decodeRepeatedUInt64Field(value: inout [UInt64]) throws {
  401. switch fieldWireFormat {
  402. case WireFormat.varint:
  403. let varint = try decodeVarint()
  404. value.append(varint)
  405. consumed = true
  406. case WireFormat.lengthDelimited:
  407. var n: Int = 0
  408. let p = try getFieldBodyBytes(count: &n)
  409. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  410. value.reserveCapacity(value.count + ints)
  411. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  412. while !decoder.complete {
  413. let t = try decoder.decodeVarint()
  414. value.append(t)
  415. }
  416. consumed = true
  417. default:
  418. return
  419. }
  420. }
  421. internal mutating func decodeSingularSInt32Field(value: inout Int32) throws {
  422. guard fieldWireFormat == WireFormat.varint else {
  423. return
  424. }
  425. let varint = try decodeVarint()
  426. let t = UInt32(truncatingIfNeeded: varint)
  427. value = ZigZag.decoded(t)
  428. consumed = true
  429. }
  430. internal mutating func decodeSingularSInt32Field(value: inout Int32?) throws {
  431. guard fieldWireFormat == WireFormat.varint else {
  432. return
  433. }
  434. let varint = try decodeVarint()
  435. let t = UInt32(truncatingIfNeeded: varint)
  436. value = ZigZag.decoded(t)
  437. consumed = true
  438. }
  439. internal mutating func decodeRepeatedSInt32Field(value: inout [Int32]) throws {
  440. switch fieldWireFormat {
  441. case WireFormat.varint:
  442. let varint = try decodeVarint()
  443. let t = UInt32(truncatingIfNeeded: varint)
  444. value.append(ZigZag.decoded(t))
  445. consumed = true
  446. case WireFormat.lengthDelimited:
  447. var n: Int = 0
  448. let p = try getFieldBodyBytes(count: &n)
  449. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  450. value.reserveCapacity(value.count + ints)
  451. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  452. while !decoder.complete {
  453. let varint = try decoder.decodeVarint()
  454. let t = UInt32(truncatingIfNeeded: varint)
  455. value.append(ZigZag.decoded(t))
  456. }
  457. consumed = true
  458. default:
  459. return
  460. }
  461. }
  462. internal mutating func decodeSingularSInt64Field(value: inout Int64) throws {
  463. guard fieldWireFormat == WireFormat.varint else {
  464. return
  465. }
  466. let varint = try decodeVarint()
  467. value = ZigZag.decoded(varint)
  468. consumed = true
  469. }
  470. internal mutating func decodeSingularSInt64Field(value: inout Int64?) throws {
  471. guard fieldWireFormat == WireFormat.varint else {
  472. return
  473. }
  474. let varint = try decodeVarint()
  475. value = ZigZag.decoded(varint)
  476. consumed = true
  477. }
  478. internal mutating func decodeRepeatedSInt64Field(value: inout [Int64]) throws {
  479. switch fieldWireFormat {
  480. case WireFormat.varint:
  481. let varint = try decodeVarint()
  482. value.append(ZigZag.decoded(varint))
  483. consumed = true
  484. case WireFormat.lengthDelimited:
  485. var n: Int = 0
  486. let p = try getFieldBodyBytes(count: &n)
  487. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  488. value.reserveCapacity(value.count + ints)
  489. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  490. while !decoder.complete {
  491. let varint = try decoder.decodeVarint()
  492. value.append(ZigZag.decoded(varint))
  493. }
  494. consumed = true
  495. default:
  496. return
  497. }
  498. }
  499. internal mutating func decodeSingularFixed32Field(value: inout UInt32) throws {
  500. guard fieldWireFormat == WireFormat.fixed32 else {
  501. return
  502. }
  503. value = try decodeLittleEndianInteger()
  504. consumed = true
  505. }
  506. internal mutating func decodeSingularFixed32Field(value: inout UInt32?) throws {
  507. guard fieldWireFormat == WireFormat.fixed32 else {
  508. return
  509. }
  510. value = try decodeLittleEndianInteger()
  511. consumed = true
  512. }
  513. internal mutating func decodeRepeatedFixed32Field(value: inout [UInt32]) throws {
  514. switch fieldWireFormat {
  515. case WireFormat.fixed32:
  516. value.append(try decodeLittleEndianInteger())
  517. consumed = true
  518. case WireFormat.lengthDelimited:
  519. var n: Int = 0
  520. let p = try getFieldBodyBytes(count: &n)
  521. value.reserveCapacity(value.count + n / MemoryLayout<UInt32>.size)
  522. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  523. while !decoder.complete {
  524. value.append(try decoder.decodeLittleEndianInteger())
  525. }
  526. consumed = true
  527. default:
  528. return
  529. }
  530. }
  531. internal mutating func decodeSingularFixed64Field(value: inout UInt64) throws {
  532. guard fieldWireFormat == WireFormat.fixed64 else {
  533. return
  534. }
  535. value = try decodeLittleEndianInteger()
  536. consumed = true
  537. }
  538. internal mutating func decodeSingularFixed64Field(value: inout UInt64?) throws {
  539. guard fieldWireFormat == WireFormat.fixed64 else {
  540. return
  541. }
  542. value = try decodeLittleEndianInteger()
  543. consumed = true
  544. }
  545. internal mutating func decodeRepeatedFixed64Field(value: inout [UInt64]) throws {
  546. switch fieldWireFormat {
  547. case WireFormat.fixed64:
  548. value.append(try decodeLittleEndianInteger())
  549. consumed = true
  550. case WireFormat.lengthDelimited:
  551. var n: Int = 0
  552. let p = try getFieldBodyBytes(count: &n)
  553. value.reserveCapacity(value.count + n / MemoryLayout<UInt64>.size)
  554. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  555. while !decoder.complete {
  556. value.append(try decoder.decodeLittleEndianInteger())
  557. }
  558. consumed = true
  559. default:
  560. return
  561. }
  562. }
  563. internal mutating func decodeSingularSFixed32Field(value: inout Int32) throws {
  564. guard fieldWireFormat == WireFormat.fixed32 else {
  565. return
  566. }
  567. value = try decodeLittleEndianInteger()
  568. consumed = true
  569. }
  570. internal mutating func decodeSingularSFixed32Field(value: inout Int32?) throws {
  571. guard fieldWireFormat == WireFormat.fixed32 else {
  572. return
  573. }
  574. value = try decodeLittleEndianInteger()
  575. consumed = true
  576. }
  577. internal mutating func decodeRepeatedSFixed32Field(value: inout [Int32]) throws {
  578. switch fieldWireFormat {
  579. case WireFormat.fixed32:
  580. value.append(try decodeLittleEndianInteger())
  581. consumed = true
  582. case WireFormat.lengthDelimited:
  583. var n: Int = 0
  584. let p = try getFieldBodyBytes(count: &n)
  585. value.reserveCapacity(value.count + n / MemoryLayout<Int32>.size)
  586. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  587. while !decoder.complete {
  588. value.append(try decoder.decodeLittleEndianInteger())
  589. }
  590. consumed = true
  591. default:
  592. return
  593. }
  594. }
  595. internal mutating func decodeSingularSFixed64Field(value: inout Int64) throws {
  596. guard fieldWireFormat == WireFormat.fixed64 else {
  597. return
  598. }
  599. value = try decodeLittleEndianInteger()
  600. consumed = true
  601. }
  602. internal mutating func decodeSingularSFixed64Field(value: inout Int64?) throws {
  603. guard fieldWireFormat == WireFormat.fixed64 else {
  604. return
  605. }
  606. value = try decodeLittleEndianInteger()
  607. consumed = true
  608. }
  609. internal mutating func decodeRepeatedSFixed64Field(value: inout [Int64]) throws {
  610. switch fieldWireFormat {
  611. case WireFormat.fixed64:
  612. value.append(try decodeLittleEndianInteger())
  613. consumed = true
  614. case WireFormat.lengthDelimited:
  615. var n: Int = 0
  616. let p = try getFieldBodyBytes(count: &n)
  617. value.reserveCapacity(value.count + n / MemoryLayout<Int64>.size)
  618. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  619. while !decoder.complete {
  620. value.append(try decoder.decodeLittleEndianInteger())
  621. }
  622. consumed = true
  623. default:
  624. return
  625. }
  626. }
  627. internal mutating func decodeSingularBoolField(value: inout Bool) throws {
  628. guard fieldWireFormat == WireFormat.varint else {
  629. return
  630. }
  631. value = try decodeVarint() != 0
  632. consumed = true
  633. }
  634. internal mutating func decodeSingularBoolField(value: inout Bool?) throws {
  635. guard fieldWireFormat == WireFormat.varint else {
  636. return
  637. }
  638. value = try decodeVarint() != 0
  639. consumed = true
  640. }
  641. internal mutating func decodeRepeatedBoolField(value: inout [Bool]) throws {
  642. switch fieldWireFormat {
  643. case WireFormat.varint:
  644. let varint = try decodeVarint()
  645. value.append(varint != 0)
  646. consumed = true
  647. case WireFormat.lengthDelimited:
  648. var n: Int = 0
  649. let p = try getFieldBodyBytes(count: &n)
  650. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  651. value.reserveCapacity(value.count + ints)
  652. var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  653. while !decoder.complete {
  654. let t = try decoder.decodeVarint()
  655. value.append(t != 0)
  656. }
  657. consumed = true
  658. default:
  659. return
  660. }
  661. }
  662. internal mutating func decodeSingularStringField(value: inout String) throws {
  663. guard fieldWireFormat == WireFormat.lengthDelimited else {
  664. return
  665. }
  666. var n: Int = 0
  667. let p = try getFieldBodyBytes(count: &n)
  668. if let s = utf8ToString(bytes: p, count: n) {
  669. value = s
  670. consumed = true
  671. } else {
  672. throw BinaryDecodingError.invalidUTF8
  673. }
  674. }
  675. internal mutating func decodeSingularStringField(value: inout String?) throws {
  676. guard fieldWireFormat == WireFormat.lengthDelimited else {
  677. return
  678. }
  679. var n: Int = 0
  680. let p = try getFieldBodyBytes(count: &n)
  681. if let s = utf8ToString(bytes: p, count: n) {
  682. value = s
  683. consumed = true
  684. } else {
  685. throw BinaryDecodingError.invalidUTF8
  686. }
  687. }
  688. internal mutating func decodeRepeatedStringField(value: inout [String]) throws {
  689. switch fieldWireFormat {
  690. case WireFormat.lengthDelimited:
  691. var n: Int = 0
  692. let p = try getFieldBodyBytes(count: &n)
  693. if let s = utf8ToString(bytes: p, count: n) {
  694. value.append(s)
  695. consumed = true
  696. } else {
  697. throw BinaryDecodingError.invalidUTF8
  698. }
  699. default:
  700. return
  701. }
  702. }
  703. internal mutating func decodeSingularBytesField(value: inout Data) throws {
  704. guard fieldWireFormat == WireFormat.lengthDelimited else {
  705. return
  706. }
  707. var n: Int = 0
  708. let p = try getFieldBodyBytes(count: &n)
  709. value = Data(bytes: p, count: n)
  710. consumed = true
  711. }
  712. internal mutating func decodeSingularBytesField(value: inout Data?) throws {
  713. guard fieldWireFormat == WireFormat.lengthDelimited else {
  714. return
  715. }
  716. var n: Int = 0
  717. let p = try getFieldBodyBytes(count: &n)
  718. value = Data(bytes: p, count: n)
  719. consumed = true
  720. }
  721. internal mutating func decodeRepeatedBytesField(value: inout [Data]) throws {
  722. switch fieldWireFormat {
  723. case WireFormat.lengthDelimited:
  724. var n: Int = 0
  725. let p = try getFieldBodyBytes(count: &n)
  726. value.append(Data(bytes: p, count: n))
  727. consumed = true
  728. default:
  729. return
  730. }
  731. }
  732. internal mutating func decodeSingularEnumField<E: Enum>(value: inout E?) throws where E.RawValue == Int {
  733. guard fieldWireFormat == WireFormat.varint else {
  734. return
  735. }
  736. let varint = try decodeVarint()
  737. if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) {
  738. value = v
  739. consumed = true
  740. }
  741. }
  742. internal mutating func decodeSingularEnumField<E: Enum>(value: inout E) throws where E.RawValue == Int {
  743. guard fieldWireFormat == WireFormat.varint else {
  744. return
  745. }
  746. let varint = try decodeVarint()
  747. if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) {
  748. value = v
  749. consumed = true
  750. }
  751. }
  752. internal mutating func decodeRepeatedEnumField<E: Enum>(value: inout [E]) throws where E.RawValue == Int {
  753. switch fieldWireFormat {
  754. case WireFormat.varint:
  755. let varint = try decodeVarint()
  756. if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) {
  757. value.append(v)
  758. consumed = true
  759. }
  760. case WireFormat.lengthDelimited:
  761. var n: Int = 0
  762. var extras: [Int32]?
  763. let p = try getFieldBodyBytes(count: &n)
  764. let ints = Varint.countVarintsInBuffer(start: p, count: n)
  765. value.reserveCapacity(value.count + ints)
  766. var subdecoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self)
  767. while !subdecoder.complete {
  768. let u64 = try subdecoder.decodeVarint()
  769. let i32 = Int32(truncatingIfNeeded: u64)
  770. if let v = E(rawValue: Int(i32)) {
  771. value.append(v)
  772. } else if !options.discardUnknownFields {
  773. if extras == nil {
  774. extras = []
  775. }
  776. extras!.append(i32)
  777. }
  778. }
  779. if let extras = extras {
  780. let fieldTag = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
  781. let bodySize = extras.reduce(0) { $0 + Varint.encodedSize(of: Int64($1)) }
  782. let fieldSize =
  783. Varint.encodedSize(of: fieldTag.rawValue) + Varint.encodedSize(of: Int64(bodySize)) + bodySize
  784. var field = Data(count: fieldSize)
  785. field.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
  786. var encoder = BinaryEncoder(forWritingInto: body)
  787. encoder.startField(tag: fieldTag)
  788. encoder.putVarInt(value: Int64(bodySize))
  789. for v in extras {
  790. encoder.putVarInt(value: Int64(v))
  791. }
  792. }
  793. unknownOverride = field
  794. }
  795. consumed = true
  796. default:
  797. return
  798. }
  799. }
  800. internal mutating func decodeSingularMessageField<M: Message>(value: inout M?) throws {
  801. guard fieldWireFormat == WireFormat.lengthDelimited else {
  802. return
  803. }
  804. var count: Int = 0
  805. let p = try getFieldBodyBytes(count: &count)
  806. if value == nil {
  807. value = M()
  808. }
  809. var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
  810. try subDecoder.decodeFullMessage(message: &value!)
  811. consumed = true
  812. }
  813. internal mutating func decodeRepeatedMessageField<M: Message>(value: inout [M]) throws {
  814. guard fieldWireFormat == WireFormat.lengthDelimited else {
  815. return
  816. }
  817. var count: Int = 0
  818. let p = try getFieldBodyBytes(count: &count)
  819. var newValue = M()
  820. var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
  821. try subDecoder.decodeFullMessage(message: &newValue)
  822. value.append(newValue)
  823. consumed = true
  824. }
  825. internal mutating func decodeFullMessage<M: Message>(message: inout M) throws {
  826. assert(unknownData == nil)
  827. try incrementRecursionDepth()
  828. try message.decodeMessage(decoder: &self)
  829. decrementRecursionDepth()
  830. guard complete else {
  831. throw BinaryDecodingError.trailingGarbage
  832. }
  833. if let unknownData = unknownData {
  834. message.unknownFields.append(protobufData: unknownData)
  835. }
  836. }
  837. internal mutating func decodeSingularGroupField<G: Message>(value: inout G?) throws {
  838. var group = value ?? G()
  839. if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) {
  840. value = group
  841. consumed = true
  842. }
  843. }
  844. internal mutating func decodeRepeatedGroupField<G: Message>(value: inout [G]) throws {
  845. var group = G()
  846. if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) {
  847. value.append(group)
  848. consumed = true
  849. }
  850. }
  851. private mutating func decodeFullGroup<G: Message>(group: inout G, fieldNumber: Int) throws -> Bool {
  852. guard fieldWireFormat == WireFormat.startGroup else {
  853. return false
  854. }
  855. try incrementRecursionDepth()
  856. // This works by making a clone of the current decoder state and
  857. // setting `groupFieldNumber` to signal `nextFieldNumber()` to watch
  858. // for that as a marker for having reached the end of a group/message.
  859. // Groups within groups works because this effectively makes a stack
  860. // of decoders, each one looking for their ending tag.
  861. var subDecoder = self
  862. subDecoder.groupFieldNumber = fieldNumber
  863. // startGroup was read, so current tag/data is done (otherwise the
  864. // startTag will end up in the unknowns of the first thing decoded).
  865. subDecoder.consumed = true
  866. // The group (message) doesn't get any existing unknown fields from
  867. // the parent.
  868. subDecoder.unknownData = nil
  869. try group.decodeMessage(decoder: &subDecoder)
  870. guard subDecoder.fieldNumber == fieldNumber && subDecoder.fieldWireFormat == .endGroup else {
  871. throw BinaryDecodingError.truncated
  872. }
  873. if let groupUnknowns = subDecoder.unknownData {
  874. group.unknownFields.append(protobufData: groupUnknowns)
  875. }
  876. // Advance over what was parsed.
  877. consume(length: available - subDecoder.available)
  878. assert(recursionBudget == subDecoder.recursionBudget)
  879. decrementRecursionDepth()
  880. return true
  881. }
  882. internal mutating func decodeMapField<KeyType, ValueType: MapValueType>(
  883. fieldType: _ProtobufMap<KeyType, ValueType>.Type,
  884. value: inout _ProtobufMap<KeyType, ValueType>.BaseType
  885. ) throws {
  886. guard fieldWireFormat == WireFormat.lengthDelimited else {
  887. return
  888. }
  889. var k: KeyType.BaseType?
  890. var v: ValueType.BaseType?
  891. var count: Int = 0
  892. let p = try getFieldBodyBytes(count: &count)
  893. var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
  894. while let tag = try subdecoder.getTag() {
  895. if tag.wireFormat == .endGroup {
  896. throw BinaryDecodingError.malformedProtobuf
  897. }
  898. let fieldNumber = tag.fieldNumber
  899. switch fieldNumber {
  900. case 1:
  901. try KeyType.decodeSingular(value: &k, from: &subdecoder)
  902. case 2:
  903. try ValueType.decodeSingular(value: &v, from: &subdecoder)
  904. default: // Skip any other fields within the map entry object
  905. try subdecoder.skip()
  906. }
  907. }
  908. if !subdecoder.complete {
  909. throw BinaryDecodingError.trailingGarbage
  910. }
  911. // A map<> definition can't provide a default value for the keys/values,
  912. // so it is safe to use the proto3 default to get the right
  913. // integer/string/bytes. The one catch is a proto2 enum (which can be the
  914. // value) can have a non zero value, but that case is the next
  915. // custom decodeMapField<>() method and handles it.
  916. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType.proto3DefaultValue
  917. consumed = true
  918. }
  919. internal mutating func decodeMapField<KeyType, ValueType>(
  920. fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
  921. value: inout _ProtobufEnumMap<KeyType, ValueType>.BaseType
  922. ) throws where ValueType.RawValue == Int {
  923. guard fieldWireFormat == WireFormat.lengthDelimited else {
  924. return
  925. }
  926. var k: KeyType.BaseType?
  927. var v: ValueType?
  928. var count: Int = 0
  929. let p = try getFieldBodyBytes(count: &count)
  930. var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
  931. while let tag = try subdecoder.getTag() {
  932. if tag.wireFormat == .endGroup {
  933. throw BinaryDecodingError.malformedProtobuf
  934. }
  935. let fieldNumber = tag.fieldNumber
  936. switch fieldNumber {
  937. case 1: // Keys are basic types
  938. try KeyType.decodeSingular(value: &k, from: &subdecoder)
  939. case 2: // Value is an Enum type
  940. try subdecoder.decodeSingularEnumField(value: &v)
  941. if v == nil && tag.wireFormat == .varint {
  942. // Enum decode fail and wire format was varint, so this had to
  943. // have been a proto2 unknown enum value. This whole map entry
  944. // into the parent message's unknown fields. If the wire format
  945. // was wrong, treat it like an unknown field and drop it with
  946. // the map entry.
  947. return
  948. }
  949. default: // Skip any other fields within the map entry object
  950. try subdecoder.skip()
  951. }
  952. }
  953. if !subdecoder.complete {
  954. throw BinaryDecodingError.trailingGarbage
  955. }
  956. // A map<> definition can't provide a default value for the keys, so it
  957. // is safe to use the proto3 default to get the right integer/string/bytes.
  958. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType()
  959. consumed = true
  960. }
  961. internal mutating func decodeMapField<KeyType, ValueType>(
  962. fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
  963. value: inout _ProtobufMessageMap<KeyType, ValueType>.BaseType
  964. ) throws {
  965. guard fieldWireFormat == WireFormat.lengthDelimited else {
  966. return
  967. }
  968. var k: KeyType.BaseType?
  969. var v: ValueType?
  970. var count: Int = 0
  971. let p = try getFieldBodyBytes(count: &count)
  972. var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self)
  973. while let tag = try subdecoder.getTag() {
  974. if tag.wireFormat == .endGroup {
  975. throw BinaryDecodingError.malformedProtobuf
  976. }
  977. let fieldNumber = tag.fieldNumber
  978. switch fieldNumber {
  979. case 1: // Keys are basic types
  980. try KeyType.decodeSingular(value: &k, from: &subdecoder)
  981. case 2: // Value is a message type
  982. try subdecoder.decodeSingularMessageField(value: &v)
  983. default: // Skip any other fields within the map entry object
  984. try subdecoder.skip()
  985. }
  986. }
  987. if !subdecoder.complete {
  988. throw BinaryDecodingError.trailingGarbage
  989. }
  990. // A map<> definition can't provide a default value for the keys, so it
  991. // is safe to use the proto3 default to get the right integer/string/bytes.
  992. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType()
  993. consumed = true
  994. }
  995. internal mutating func decodeExtensionField(
  996. values: inout ExtensionFieldValueSet,
  997. messageType: any Message.Type,
  998. fieldNumber: Int
  999. ) throws {
  1000. if let ext = extensions?[messageType, fieldNumber] {
  1001. try decodeExtensionField(
  1002. values: &values,
  1003. messageType: messageType,
  1004. fieldNumber: fieldNumber,
  1005. messageExtension: ext
  1006. )
  1007. }
  1008. }
  1009. /// Helper to reuse between Extension decoding and MessageSet Extension decoding.
  1010. private mutating func decodeExtensionField(
  1011. values: inout ExtensionFieldValueSet,
  1012. messageType: any Message.Type,
  1013. fieldNumber: Int,
  1014. messageExtension ext: any AnyMessageExtension
  1015. ) throws {
  1016. assert(!consumed)
  1017. assert(fieldNumber == ext.fieldNumber)
  1018. try values.modify(index: fieldNumber) { fieldValue in
  1019. // Message/Group extensions both will call back into the matching
  1020. // decode methods, so the recursion depth will be tracked there.
  1021. if fieldValue != nil {
  1022. try fieldValue!.decodeExtensionField(decoder: &self)
  1023. } else {
  1024. fieldValue = try ext._protobuf_newField(decoder: &self)
  1025. }
  1026. if consumed && fieldValue == nil {
  1027. // Really things should never get here, if the decoder says
  1028. // the bytes were consumed, then there should have been a
  1029. // field that consumed them (existing or created). This
  1030. // specific error result is to allow this to be more detectable.
  1031. throw BinaryDecodingError.internalExtensionError
  1032. }
  1033. }
  1034. }
  1035. internal mutating func decodeExtensionFieldsAsMessageSet(
  1036. values: inout ExtensionFieldValueSet,
  1037. messageType: any Message.Type
  1038. ) throws {
  1039. // Spin looking for the Item group, everything else will end up in unknown fields.
  1040. while let fieldNumber = try self.nextFieldNumber() {
  1041. guard fieldNumber == WireFormat.MessageSet.FieldNumbers.item && fieldWireFormat == WireFormat.startGroup
  1042. else {
  1043. continue
  1044. }
  1045. // This is similar to decodeFullGroup
  1046. try incrementRecursionDepth()
  1047. var subDecoder = self
  1048. subDecoder.groupFieldNumber = fieldNumber
  1049. subDecoder.consumed = true
  1050. let itemResult = try subDecoder.decodeMessageSetItem(
  1051. values: &values,
  1052. messageType: messageType
  1053. )
  1054. switch itemResult {
  1055. case .success:
  1056. // Advance over what was parsed.
  1057. consume(length: available - subDecoder.available)
  1058. consumed = true
  1059. case .handleAsUnknown:
  1060. // Nothing to do.
  1061. break
  1062. case .malformed:
  1063. throw BinaryDecodingError.malformedProtobuf
  1064. }
  1065. assert(recursionBudget == subDecoder.recursionBudget)
  1066. decrementRecursionDepth()
  1067. }
  1068. }
  1069. private enum DecodeMessageSetItemResult {
  1070. case success
  1071. case handleAsUnknown
  1072. case malformed
  1073. }
  1074. private mutating func decodeMessageSetItem(
  1075. values: inout ExtensionFieldValueSet,
  1076. messageType: any Message.Type
  1077. ) throws -> DecodeMessageSetItemResult {
  1078. // This is loosely based on the C++:
  1079. // ExtensionSet::ParseMessageSetItem()
  1080. // WireFormat::ParseAndMergeMessageSetItem()
  1081. // (yes, there have two versions that are almost the same)
  1082. var msgExtension: (any AnyMessageExtension)?
  1083. var fieldData: Data?
  1084. // In this loop, if wire types are wrong, things don't decode,
  1085. // just bail instead of letting things go into unknown fields.
  1086. // Wrongly formed MessageSets don't seem don't have real
  1087. // spelled out behaviors.
  1088. while let fieldNumber = try self.nextFieldNumber() {
  1089. switch fieldNumber {
  1090. case WireFormat.MessageSet.FieldNumbers.typeId:
  1091. var extensionFieldNumber: Int32 = 0
  1092. try decodeSingularInt32Field(value: &extensionFieldNumber)
  1093. if extensionFieldNumber == 0 { return .malformed }
  1094. guard let ext = extensions?[messageType, Int(extensionFieldNumber)] else {
  1095. return .handleAsUnknown // Unknown extension.
  1096. }
  1097. msgExtension = ext
  1098. // If there already was fieldData, decode it.
  1099. if let data = fieldData {
  1100. var wasDecoded = false
  1101. try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in
  1102. if let baseAddress = body.baseAddress, body.count > 0 {
  1103. var extDecoder = BinaryDecoder(
  1104. forReadingFrom: baseAddress,
  1105. count: body.count,
  1106. parent: self
  1107. )
  1108. // Prime the decode to be correct.
  1109. extDecoder.consumed = false
  1110. extDecoder.fieldWireFormat = .lengthDelimited
  1111. try extDecoder.decodeExtensionField(
  1112. values: &values,
  1113. messageType: messageType,
  1114. fieldNumber: ext.fieldNumber,
  1115. messageExtension: ext
  1116. )
  1117. wasDecoded = extDecoder.consumed
  1118. }
  1119. }
  1120. if !wasDecoded {
  1121. return .malformed
  1122. }
  1123. fieldData = nil
  1124. }
  1125. case WireFormat.MessageSet.FieldNumbers.message:
  1126. if let ext = msgExtension {
  1127. assert(consumed == false)
  1128. try decodeExtensionField(
  1129. values: &values,
  1130. messageType: messageType,
  1131. fieldNumber: ext.fieldNumber,
  1132. messageExtension: ext
  1133. )
  1134. if !consumed {
  1135. return .malformed
  1136. }
  1137. } else {
  1138. // The C++ references ends up appending the blocks together as length
  1139. // delimited blocks, but the parsing will only use the first block.
  1140. // So just capture a block, and then skip any others that happen to
  1141. // be found.
  1142. if fieldData == nil {
  1143. var d: Data?
  1144. try decodeSingularBytesField(value: &d)
  1145. guard let data = d else { return .malformed }
  1146. // Save it as length delimited
  1147. let payloadSize = Varint.encodedSize(of: Int64(data.count)) + data.count
  1148. var payload = Data(count: payloadSize)
  1149. payload.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
  1150. var encoder = BinaryEncoder(forWritingInto: body)
  1151. encoder.putBytesValue(value: data)
  1152. }
  1153. fieldData = payload
  1154. } else {
  1155. guard fieldWireFormat == .lengthDelimited else { return .malformed }
  1156. try skip()
  1157. consumed = true
  1158. }
  1159. }
  1160. default:
  1161. // Skip everything else
  1162. try skip()
  1163. consumed = true
  1164. }
  1165. }
  1166. return .success
  1167. }
  1168. //
  1169. // Private building blocks for the parsing above.
  1170. //
  1171. // Having these be private gives the compiler maximum latitude for
  1172. // inlining.
  1173. //
  1174. /// Private: Advance the current position.
  1175. private mutating func consume(length: Int) {
  1176. available -= length
  1177. p += length
  1178. }
  1179. /// Private: Skip the body for the given tag. If the given tag is
  1180. /// a group, it parses up through the corresponding group end.
  1181. private mutating func skipOver(tag: FieldTag) throws {
  1182. switch tag.wireFormat {
  1183. case .varint:
  1184. // Don't need the value, just ensuring it is validly encoded.
  1185. let _ = try decodeVarint()
  1186. case .fixed64:
  1187. if available < 8 {
  1188. throw BinaryDecodingError.truncated
  1189. }
  1190. p += 8
  1191. available -= 8
  1192. case .lengthDelimited:
  1193. let n = try decodeVarint()
  1194. if n <= UInt64(available) {
  1195. p += Int(n)
  1196. available -= Int(n)
  1197. } else {
  1198. throw BinaryDecodingError.truncated
  1199. }
  1200. case .startGroup:
  1201. try incrementRecursionDepth()
  1202. while true {
  1203. if let innerTag = try getTagWithoutUpdatingFieldStart() {
  1204. if innerTag.wireFormat == .endGroup {
  1205. if innerTag.fieldNumber == tag.fieldNumber {
  1206. decrementRecursionDepth()
  1207. break
  1208. } else {
  1209. // .endGroup for a something other than the current
  1210. // group is an invalid binary.
  1211. throw BinaryDecodingError.malformedProtobuf
  1212. }
  1213. } else {
  1214. try skipOver(tag: innerTag)
  1215. }
  1216. } else {
  1217. throw BinaryDecodingError.truncated
  1218. }
  1219. }
  1220. case .endGroup:
  1221. throw BinaryDecodingError.truncated
  1222. case .fixed32:
  1223. if available < 4 {
  1224. throw BinaryDecodingError.truncated
  1225. }
  1226. p += 4
  1227. available -= 4
  1228. }
  1229. }
  1230. /// Private: Skip to the end of the current field.
  1231. ///
  1232. /// Assumes that fieldStartP was bookmarked by a previous
  1233. /// call to getTagType().
  1234. ///
  1235. /// On exit, fieldStartP points to the first byte of the tag, fieldEndP points
  1236. /// to the first byte after the field contents, and p == fieldEndP.
  1237. private mutating func skip() throws {
  1238. if let end = fieldEndP {
  1239. p = end
  1240. } else {
  1241. // Rewind to start of current field.
  1242. available += p - fieldStartP
  1243. p = fieldStartP
  1244. guard let tag = try getTagWithoutUpdatingFieldStart() else {
  1245. throw BinaryDecodingError.truncated
  1246. }
  1247. try skipOver(tag: tag)
  1248. fieldEndP = p
  1249. }
  1250. }
  1251. /// Private: Parse the next raw varint from the input.
  1252. private mutating func decodeVarint() throws -> UInt64 {
  1253. if available < 1 {
  1254. throw BinaryDecodingError.truncated
  1255. }
  1256. var start = p
  1257. var length = available
  1258. var c = start.load(fromByteOffset: 0, as: UInt8.self)
  1259. start += 1
  1260. length -= 1
  1261. if c & 0x80 == 0 {
  1262. p = start
  1263. available = length
  1264. return UInt64(c)
  1265. }
  1266. var value = UInt64(c & 0x7f)
  1267. var shift = UInt64(7)
  1268. while true {
  1269. if length < 1 || shift > 63 {
  1270. throw BinaryDecodingError.malformedProtobuf
  1271. }
  1272. c = start.load(fromByteOffset: 0, as: UInt8.self)
  1273. start += 1
  1274. length -= 1
  1275. value |= UInt64(c & 0x7f) << shift
  1276. if c & 0x80 == 0 {
  1277. p = start
  1278. available = length
  1279. return value
  1280. }
  1281. shift += 7
  1282. }
  1283. }
  1284. /// Private: Get the tag that starts a new field.
  1285. /// This also bookmarks the start of field for a possible skip().
  1286. internal mutating func getTag() throws -> FieldTag? {
  1287. fieldStartP = p
  1288. fieldEndP = nil
  1289. return try getTagWithoutUpdatingFieldStart()
  1290. }
  1291. /// Private: Parse and validate the next tag without
  1292. /// bookmarking the start of the field. This is used within
  1293. /// skip() to skip over fields within a group.
  1294. private mutating func getTagWithoutUpdatingFieldStart() throws -> FieldTag? {
  1295. if available < 1 {
  1296. return nil
  1297. }
  1298. let t = try decodeVarint()
  1299. if t < UInt64(UInt32.max) {
  1300. guard let tag = FieldTag(rawValue: UInt32(truncatingIfNeeded: t)) else {
  1301. throw BinaryDecodingError.malformedProtobuf
  1302. }
  1303. fieldWireFormat = tag.wireFormat
  1304. fieldNumber = tag.fieldNumber
  1305. return tag
  1306. } else {
  1307. throw BinaryDecodingError.malformedProtobuf
  1308. }
  1309. }
  1310. /// Private: Return a Data containing the entirety of
  1311. /// the current field, including tag.
  1312. private mutating func getRawField() throws -> Data {
  1313. try skip()
  1314. return Data(bytes: fieldStartP, count: fieldEndP! - fieldStartP)
  1315. }
  1316. /// Private: decode a fixed-length number.
  1317. private mutating func decodeLittleEndianInteger<T: FixedWidthInteger>() throws -> T {
  1318. let size = MemoryLayout<T>.size
  1319. assert(size == 4 || size == 8)
  1320. guard available >= size else { throw BinaryDecodingError.truncated }
  1321. defer { consume(length: size) }
  1322. return T(littleEndian: p.loadUnaligned(as: T.self))
  1323. }
  1324. private mutating func decodeFloat() throws -> Float {
  1325. let nativeEndianBytes: UInt32 = try decodeLittleEndianInteger()
  1326. return Float(bitPattern: nativeEndianBytes)
  1327. }
  1328. private mutating func decodeDouble() throws -> Double {
  1329. let nativeEndianBytes: UInt64 = try decodeLittleEndianInteger()
  1330. return Double(bitPattern: nativeEndianBytes)
  1331. }
  1332. /// Private: Get the start and length for the body of
  1333. /// a length-delimited field.
  1334. private mutating func getFieldBodyBytes(count: inout Int) throws -> UnsafeRawPointer {
  1335. let length = try decodeVarint()
  1336. // Bytes and Strings have a max size of 2GB. And since messages are on
  1337. // the wire as bytes/length delimited, they also have a 2GB size limit.
  1338. // The upstream C++ does the same sort of enforcement (see
  1339. // parse_context, delimited_message_util, message_lite, etc.).
  1340. // https://protobuf.dev/programming-guides/encoding/#cheat-sheet
  1341. //
  1342. // This function does get called in some package decode handling, but
  1343. // that is length delimited on the wire, so the spec would imply
  1344. // the limit still applies.
  1345. guard length < 0x7fff_ffff else {
  1346. // Reuse existing error to avoid breaking change of changing thrown error
  1347. throw BinaryDecodingError.malformedProtobuf
  1348. }
  1349. guard length <= UInt64(available) else {
  1350. throw BinaryDecodingError.truncated
  1351. }
  1352. count = Int(length)
  1353. let body = p
  1354. consume(length: count)
  1355. return body
  1356. }
  1357. }