_MessageStorage.swift 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. // Sources/SwiftProtobuf/_MessageStorage.swift - Table-driven message storage
  2. //
  3. // Copyright (c) 2014 - 2025 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. /// Manages the in-memory storage of the fields of a message.
  12. ///
  13. // -----------------------------------------------------------------------------
  14. import Foundation
  15. /// Manages the in-memory storage for a table-driven message.
  16. ///
  17. /// The in-memory storage of a message is a region of raw memory whose layout is determined by the
  18. /// `_MessageLayout` that it is initialized with. While fields may be laid out at different offsets
  19. /// in different messages, all layouts share some common properties:
  20. ///
  21. /// * The first subregion contains the has-bits for each field. Within this subregion, the
  22. /// has-bits for required fields are ordered first.
  23. /// * Following the has-bits, there is a subregion for each size-group of fields: Boolean values,
  24. /// 32-bit values, 64-bit values, pointer-sized values, and larger complex Swift values.
  25. ///
  26. /// Even though has-bits are not strictly required for the implementation of certain fields (e.g.,
  27. /// repeated fields), we use them anyway because the extra space is negligible and it is more
  28. /// efficient to test has-bits to determine if a field is set instead of loading and testing
  29. /// complex values. Furthermore, this allows us to properly track whether a field's memory is
  30. /// initialized or not (in the Swift sense of initialized memory w.r.t. unsafe pointers), ensuring
  31. /// that complex values are retained/released appropriately at all times.
  32. ///
  33. /// This type is public because it needs to be referenced and initialized from generated messages.
  34. /// Clients should not access it or its members directly.
  35. @_spi(ForGeneratedCodeOnly) public final class _MessageStorage {
  36. /// The layout of this instance of storage.
  37. @usableFromInline let layout: _MessageLayout
  38. /// The memory buffer that contain's the data for the message's fields.
  39. @usableFromInline let buffer: UnsafeMutableRawBufferPointer
  40. /// The storage used for unknown fields.
  41. public var unknownFields: UnknownStorage
  42. /// The storage used for extension field values.
  43. /// TODO: This will very likely change as the table-driven implementation evolves.
  44. public var extensionFieldValues: ExtensionFieldValueSet
  45. /// Creates a new message storage instance for a message with the given layout.
  46. public init(layout: _MessageLayout) {
  47. self.layout = layout
  48. self.buffer = UnsafeMutableRawBufferPointer.allocate(
  49. byteCount: layout.size,
  50. alignment: MemoryLayout<Int>.alignment
  51. )
  52. self.buffer.withMemoryRebound(to: UInt8.self) { byteBuffer in
  53. byteBuffer.initialize(repeating: 0)
  54. }
  55. self.unknownFields = UnknownStorage()
  56. self.extensionFieldValues = ExtensionFieldValueSet()
  57. }
  58. deinit {
  59. for field in layout.fields {
  60. deinitializeField(field)
  61. }
  62. buffer.deallocate()
  63. }
  64. /// Deinitializes the given field.
  65. @usableFromInline func deinitializeField(_ field: FieldLayout) {
  66. switch field.fieldMode.cardinality {
  67. case .map:
  68. // TODO: Support map fields.
  69. break
  70. case .array:
  71. switch field.rawFieldType {
  72. case .bool: deinitializeField(field, type: [Bool].self)
  73. case .bytes: deinitializeField(field, type: [Data].self)
  74. case .double: deinitializeField(field, type: [Double].self)
  75. case .enum, .group, .message:
  76. layout.deinitializeField(
  77. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  78. field,
  79. self
  80. )
  81. case .fixed32, .uint32: deinitializeField(field, type: [UInt32].self)
  82. case .fixed64, .uint64: deinitializeField(field, type: [UInt64].self)
  83. case .float: deinitializeField(field, type: [Float].self)
  84. case .int32, .sfixed32, .sint32: deinitializeField(field, type: [Int32].self)
  85. case .int64, .sfixed64, .sint64: deinitializeField(field, type: [Int64].self)
  86. case .string: deinitializeField(field, type: [String].self)
  87. default: preconditionFailure("Unreachable")
  88. }
  89. case .scalar:
  90. switch field.rawFieldType {
  91. case .bytes: deinitializeField(field, type: Data.self)
  92. case .string: deinitializeField(field, type: String.self)
  93. case .group, .message:
  94. layout.deinitializeField(
  95. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  96. field,
  97. self
  98. )
  99. default:
  100. // Ignore trivial fields; no deinitialization is necessary.
  101. break
  102. }
  103. default:
  104. preconditionFailure("Unreachable")
  105. }
  106. }
  107. /// Deinitializes the field associated with the given concrete type information.
  108. public func deinitializeField<T>(_ field: FieldLayout, type: T.Type) {
  109. guard isPresent(field) else { return }
  110. (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1).deinitialize(count: 1)
  111. }
  112. /// Returns a value indicating whether the field with the given presence has been explicitly
  113. /// set.
  114. ///
  115. /// For oneof fields, this checks the currently set field against the field number being
  116. /// queried. For other fields, it checks the appropriate has-bit.
  117. ///
  118. /// Generated accessors do not use this function. Since they can encode their presence
  119. /// information directly, they use more efficient code paths that do not require the full
  120. /// field layout.
  121. func isPresent(_ field: FieldLayout) -> Bool {
  122. switch field.presence {
  123. case .oneOfMember(let oneofOffset):
  124. return populatedOneofMember(at: oneofOffset) == field.fieldNumber
  125. case .hasBit(let byteOffset, let mask):
  126. return isPresent(hasBit: (byteOffset, mask))
  127. }
  128. }
  129. }
  130. // MARK: - Whole-message operations
  131. extension _MessageStorage {
  132. /// Creates and returns an independent copy of the values in this storage.
  133. ///
  134. /// This is used to implement copy-on-write behavior.
  135. @inline(never)
  136. public func copy() -> _MessageStorage {
  137. let destination = _MessageStorage(layout: layout)
  138. // Loops through the fields, copy-initializing any that are non-trivial types. We ignore
  139. // the trivial ones here, instead tracking the byte offset of the first non-trivial field
  140. // so that we can bitwise copy those as a block afterward.
  141. var firstNontrivialStorageOffset = layout.size
  142. for field in layout.fields {
  143. switch field.fieldMode.cardinality {
  144. case .map:
  145. if field.offset < firstNontrivialStorageOffset {
  146. firstNontrivialStorageOffset = field.offset
  147. }
  148. // TODO: Support map fields.
  149. break
  150. case .array:
  151. if field.offset < firstNontrivialStorageOffset {
  152. firstNontrivialStorageOffset = field.offset
  153. }
  154. switch field.rawFieldType {
  155. case .bool: copyField(field, to: destination, type: [Bool].self)
  156. case .bytes: copyField(field, to: destination, type: [Data].self)
  157. case .double: copyField(field, to: destination, type: [Double].self)
  158. case .enum, .group, .message:
  159. layout.copyField(
  160. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  161. field,
  162. self,
  163. destination
  164. )
  165. case .fixed32, .uint32: copyField(field, to: destination, type: [UInt32].self)
  166. case .fixed64, .uint64: copyField(field, to: destination, type: [UInt64].self)
  167. case .float: copyField(field, to: destination, type: [Float].self)
  168. case .int32, .sfixed32, .sint32: copyField(field, to: destination, type: [Int32].self)
  169. case .int64, .sfixed64, .sint64: copyField(field, to: destination, type: [Int64].self)
  170. case .string: copyField(field, to: destination, type: [String].self)
  171. default: preconditionFailure("Unreachable")
  172. }
  173. case .scalar:
  174. switch field.rawFieldType {
  175. case .bytes:
  176. if field.offset < firstNontrivialStorageOffset {
  177. firstNontrivialStorageOffset = field.offset
  178. }
  179. copyField(field, to: destination, type: Data.self)
  180. case .group, .message:
  181. if field.offset < firstNontrivialStorageOffset {
  182. firstNontrivialStorageOffset = field.offset
  183. }
  184. layout.copyField(
  185. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  186. field,
  187. self,
  188. destination
  189. )
  190. case .string:
  191. if field.offset < firstNontrivialStorageOffset {
  192. firstNontrivialStorageOffset = field.offset
  193. }
  194. copyField(field, to: destination, type: String.self)
  195. default:
  196. // Do nothing. Trivial fields will be bitwise-copied as a block below.
  197. break
  198. }
  199. default:
  200. preconditionFailure("Unreachable")
  201. }
  202. }
  203. // Copy all of the trivial field values, has-bits, and any oneof tracking in bitwise
  204. // fashion.
  205. destination.buffer.copyMemory(from: .init(rebasing: buffer[..<firstNontrivialStorageOffset]))
  206. destination.unknownFields = unknownFields
  207. // TODO: Handle extension fields.
  208. return destination
  209. }
  210. /// Copy-initializes the field associated with the given layout information in the destination
  211. /// storage using its value from this storage.
  212. public func copyField<T>(_ field: FieldLayout, to destination: _MessageStorage, type: T.Type) {
  213. guard isPresent(field) else { return }
  214. let sourcePointer = (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1)
  215. let destinationPointer = (destination.buffer.baseAddress! + field.offset).bindMemory(
  216. to: T.self,
  217. capacity: 1
  218. )
  219. destinationPointer.initialize(from: sourcePointer, count: 1)
  220. }
  221. }
  222. // MARK: - Non-specific submessage storage operations
  223. extension _MessageStorage {
  224. /// Called by generated trampoline functions to invoke the given closure on the storage of a
  225. /// singular submessage, providing the type hint of the concrete message type.
  226. ///
  227. /// - Precondition: For read operations, the field is already known to be present.
  228. ///
  229. /// - Returns: The value returned from the closure.
  230. public func performOnSubmessageStorage<T: _MessageImplementationBase>(
  231. of field: FieldLayout,
  232. operation: TrampolineFieldOperation,
  233. type: T.Type,
  234. perform: (_MessageStorage) throws -> Bool
  235. ) rethrows -> Bool {
  236. switch operation {
  237. case .read:
  238. let submessage = (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1).pointee
  239. return try perform(submessage.storageForRuntime)
  240. case .mutate:
  241. // If the submessage isn't already present, we need to initialize a new one first.
  242. // Otherwise, ensure that the storage is unique before we mutate it for CoW.
  243. let pointer = (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1)
  244. if !isPresent(field) {
  245. pointer.initialize(to: T.init())
  246. switch field.presence {
  247. case .hasBit(let hasByteOffset, let hasMask):
  248. _ = updatePresence(hasBit: (hasByteOffset, hasMask), willBeSet: true)
  249. case .oneOfMember(let oneofOffset):
  250. _ = updatePopulatedOneofMember((oneofOffset, field.fieldNumber))
  251. }
  252. } else {
  253. pointer.pointee._protobuf_ensureUniqueStorage(accessToken: _MessageStorageToken())
  254. }
  255. return try perform(pointer.pointee.storageForRuntime)
  256. case .append:
  257. preconditionFailure("Internal error: singular performOnSubmessageStorage should not be called to append")
  258. }
  259. }
  260. /// Called by generated trampoline functions to invoke the given closure on the storage of each
  261. /// submessage in a repeated field, providing the type hint of the concrete message type.
  262. ///
  263. /// The closure can return false to stop iteration over the submessages early. Likewise, if the
  264. /// closure throws an error, that error will be propagated all the way to the caller.
  265. ///
  266. /// - Precondition: For the read and mutate operations, the field is already known to be
  267. /// present.
  268. ///
  269. /// - Returns: The value returned from the last invocation of the closure.
  270. public func performOnSubmessageStorage<T: _MessageImplementationBase>(
  271. of field: FieldLayout,
  272. operation: TrampolineFieldOperation,
  273. type: [T].Type,
  274. perform: (_MessageStorage) throws -> Bool
  275. ) rethrows -> Bool {
  276. switch operation {
  277. case .read, .mutate:
  278. let submessages = (buffer.baseAddress! + field.offset).bindMemory(to: [T].self, capacity: 1).pointee
  279. for submessage in submessages {
  280. guard try perform(submessage.storageForRuntime) else { return false }
  281. }
  282. return true
  283. case .append:
  284. let pointer = (buffer.baseAddress! + field.offset).bindMemory(to: [T].self, capacity: 1)
  285. if !isPresent(field) {
  286. pointer.initialize(to: [])
  287. switch field.presence {
  288. case .hasBit(let hasByteOffset, let hasMask):
  289. _ = updatePresence(hasBit: (hasByteOffset, hasMask), willBeSet: true)
  290. case .oneOfMember(let oneofOffset):
  291. _ = updatePopulatedOneofMember((oneofOffset, field.fieldNumber))
  292. }
  293. }
  294. // Below, we are mutating the underlying storage of an otherwise immutable message
  295. // without guaranteeing uniqueness. This is fine because we've just created the
  296. // message so there can be no other references to its storage.
  297. let submessage = T.init()
  298. guard try perform(submessage.storageForRuntime) else { return false }
  299. pointer.pointee.append(submessage)
  300. return true
  301. }
  302. }
  303. /// Called by generated trampoline functions to invoke the given closure on the raw value of a
  304. /// singular enum field, providing the type hint of the concrete enum type.
  305. ///
  306. /// - Precondition: For read operations, the field is already known to be present.
  307. ///
  308. /// - Parameters:
  309. /// - field: The enum field being operated on.
  310. /// - operation: The specific operation to perform on the field.
  311. /// - type: The concrete type of the enum.
  312. /// - perform: A closure called with the (possibly mutable) value of the field. For `.read`
  313. /// operations, the incoming value will be the actual value of the field, and mutating it
  314. /// will be ignored. For `.mutate`, the incoming value is not specified and the closure
  315. /// must mutate it to supply the desired value.
  316. /// - onInvalidValue: A closure that is called during `.mutate` operations if the raw value
  317. /// returned by the `perform` closure is not a valid enum case.
  318. public func performOnRawEnumValues<T: Enum>(
  319. of field: FieldLayout,
  320. operation: TrampolineFieldOperation,
  321. type: T.Type,
  322. perform: (inout Int32) throws -> Bool,
  323. onInvalidValue: (Int32) -> Void
  324. ) rethrows {
  325. switch operation {
  326. case .read:
  327. // When reading, we can get the raw value directly from storage, and we don't need to
  328. // verify it against the defined values in the actual enum.
  329. var rawValue = assumedPresentValue(at: field.offset, as: Int32.self)
  330. _ = try perform(&rawValue)
  331. case .mutate:
  332. // When updating a singular enum field, verify that it is a defined enum case. If not,
  333. // call the invalid value handler.
  334. var rawValue: Int32 = 0
  335. _ = try perform(&rawValue)
  336. if T(rawValue: Int(rawValue)) != nil {
  337. updateValue(of: field, to: rawValue)
  338. } else {
  339. onInvalidValue(rawValue)
  340. }
  341. case .append:
  342. preconditionFailure("Internal error: singular performOnRawEnumValues should not be called to append")
  343. }
  344. }
  345. /// Called by generated trampoline functions to invoke the given closure on the raw value of
  346. /// each element in a repeated enum field, providing the type hint of the concrete enum type.
  347. ///
  348. /// The closure can return false to stop iteration over the values early. Furthermore, when the
  349. /// operation is `.append`, the closure will be called repeatedly **until** it returns false.
  350. /// Likewise, if the closure throws an error, that error will be propagated all the way to the
  351. /// caller.
  352. ///
  353. /// - Precondition: For the read and mutate operations, the field is already known to be
  354. /// present.
  355. ///
  356. /// - Parameters:
  357. /// - field: The enum field being operated on.
  358. /// - operation: The specific operation to perform on the field.
  359. /// - type: The concrete type of the enum.
  360. /// - perform: A closure called with the (possibly mutable) value of the field. For `.read`
  361. /// operations, the incoming value will be the actual value of the field, and mutating it
  362. /// will be ignored. For `.mutate` and `.append`, the incoming value is not specified, and
  363. /// the closure must mutate it to supply the desired value.
  364. /// - onInvalidValue: A closure that is called during `.mutate` and `.append` operations if
  365. /// the raw value returned by the `perform` closure is not a valid enum case.
  366. public func performOnRawEnumValues<T: Enum>(
  367. of field: FieldLayout,
  368. operation: TrampolineFieldOperation,
  369. type: [T].Type,
  370. perform: (inout Int32) throws -> Bool,
  371. onInvalidValue: (Int32) -> Void
  372. ) rethrows {
  373. switch operation {
  374. case .read:
  375. for value in assumedPresentValue(at: field.offset, as: [T].self) {
  376. var rawValue = Int32(value.rawValue)
  377. guard try perform(&rawValue) else { break }
  378. }
  379. case .mutate:
  380. preconditionFailure("Internal error: repeated performOnRawEnumValues should not be called to mutate")
  381. case .append:
  382. let pointer = (buffer.baseAddress! + field.offset).bindMemory(to: [T].self, capacity: 1)
  383. var rawValue: Int32 = 0
  384. var isFieldPresent = isPresent(field)
  385. while try perform(&rawValue) {
  386. if let newValue = T(rawValue: Int(rawValue)) {
  387. if !isFieldPresent {
  388. pointer.initialize(to: [])
  389. switch field.presence {
  390. case .hasBit(let hasByteOffset, let hasMask):
  391. _ = updatePresence(hasBit: (hasByteOffset, hasMask), willBeSet: true)
  392. case .oneOfMember(let oneofOffset):
  393. _ = updatePopulatedOneofMember((oneofOffset, field.fieldNumber))
  394. }
  395. isFieldPresent = true
  396. }
  397. pointer.pointee.append(newValue)
  398. } else {
  399. onInvalidValue(rawValue)
  400. }
  401. }
  402. }
  403. }
  404. }
  405. // MARK: - Presence helpers
  406. extension _MessageStorage {
  407. /// The byte offset and bitmask of a field's has-bit in in-memory storage.
  408. public typealias HasBit = (offset: Int, mask: UInt8)
  409. /// Returns a value indicating whether the field with the given presence has been explicitly
  410. /// set.
  411. @_alwaysEmitIntoClient @inline(__always)
  412. public func isPresent(hasBit: HasBit) -> Bool {
  413. buffer.load(fromByteOffset: hasBit.offset, as: UInt8.self) & hasBit.mask != 0
  414. }
  415. /// Updates the presence of a field, returning the old presence value before it was changed.
  416. @_alwaysEmitIntoClient @inline(__always)
  417. func updatePresence(hasBit: HasBit, willBeSet: Bool) -> Bool {
  418. let oldValue = buffer.load(fromByteOffset: hasBit.offset, as: UInt8.self) & ~hasBit.mask
  419. buffer.storeBytes(of: oldValue | (willBeSet ? hasBit.mask : 0), toByteOffset: hasBit.offset, as: UInt8.self)
  420. return oldValue != 0
  421. }
  422. }
  423. // MARK: - Field readers used during encoding
  424. extension _MessageStorage {
  425. /// Returns the value at the given offset in the storage.
  426. ///
  427. /// - Precondition: The value must already be known to be present.
  428. @_alwaysEmitIntoClient @inline(__always)
  429. func assumedPresentValue<Value>(at offset: Int, as type: Value.Type = Value.self) -> Value {
  430. (buffer.baseAddress! + offset).bindMemory(to: Value.self, capacity: 1).pointee
  431. }
  432. /// Returns the value at the given offset in the storage.
  433. ///
  434. /// - Precondition: The value must already be known to be present.
  435. @_alwaysEmitIntoClient @inline(__always)
  436. func assumedPresentValue<Value: Enum>(at offset: Int, as type: Value.Type = Value.self) -> Value {
  437. // It is always safe to force-unwrap this. For open enums, the raw value initializer never
  438. // fails. For closed enums, it fails if the raw value is not a valid case, but such a value
  439. // should never cause presence to be set. For example, during decoding such a value would be
  440. // placed in unknown fields.
  441. //
  442. // TODO: Change this to `Int32` when we're using that as the raw value type.
  443. Value(rawValue: Int((buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee))!
  444. }
  445. }
  446. // MARK: - Field readers used by generated accessors
  447. // The field reader functions have some explicit specializations (both concrete and more-constrained
  448. // generic) for cases where we want to encode a "default default value". This reduces the amount of
  449. // code generation that we need to do for the common case (fields without presence, where the
  450. // default value is the zero/empty value for the field's type).
  451. //
  452. // Here and throughout, these functions use `@_alwaysEmitIntoClient` and `@inline(__always)` in a
  453. // best effort to force the compiler to specialize and optimize the generated property accessors
  454. // that call these functions into direct memory accesses. The first attribute also ensures that
  455. // these functions do not emit symbols into the runtime itself, as they would never be used.
  456. //
  457. // We expect an upcoming version of Swift to formalize these two attributes with new names, at
  458. // which point we can conditionally switch to those names to guarantee the behavior.
  459. extension _MessageStorage {
  460. /// Returns the `Bool` value at the given offset in the storage, or the default value if the
  461. /// value is not present.
  462. @_alwaysEmitIntoClient @inline(__always)
  463. public func value(at offset: Int, default defaultValue: Bool = false, hasBit: HasBit) -> Bool {
  464. guard isPresent(hasBit: hasBit) else { return defaultValue }
  465. return (buffer.baseAddress! + offset).bindMemory(to: Bool.self, capacity: 1).pointee
  466. }
  467. /// Returns the `Int32` value at the given offset in the storage, or the default value if the
  468. /// value is not present.
  469. @_alwaysEmitIntoClient @inline(__always)
  470. public func value(at offset: Int, default defaultValue: Int32 = 0, hasBit: HasBit) -> Int32 {
  471. guard isPresent(hasBit: hasBit) else { return defaultValue }
  472. return (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee
  473. }
  474. /// Returns the `UInt32` value at the given offset in the storage, or the default value if the
  475. /// value is not present.
  476. @_alwaysEmitIntoClient @inline(__always)
  477. public func value(at offset: Int, default defaultValue: UInt32 = 0, hasBit: HasBit) -> UInt32 {
  478. guard isPresent(hasBit: hasBit) else { return defaultValue }
  479. return (buffer.baseAddress! + offset).bindMemory(to: UInt32.self, capacity: 1).pointee
  480. }
  481. /// Returns the `Int64` value at the given offset in the storage, or the default value if the
  482. /// value is not present.
  483. @_alwaysEmitIntoClient @inline(__always)
  484. public func value(at offset: Int, default defaultValue: Int64 = 0, hasBit: HasBit) -> Int64 {
  485. guard isPresent(hasBit: hasBit) else { return defaultValue }
  486. return (buffer.baseAddress! + offset).bindMemory(to: Int64.self, capacity: 1).pointee
  487. }
  488. /// Returns the `UInt64` value at the given offset in the storage, or the default value if the
  489. /// value is not present.
  490. @_alwaysEmitIntoClient @inline(__always)
  491. public func value(at offset: Int, default defaultValue: UInt64 = 0, hasBit: HasBit) -> UInt64 {
  492. guard isPresent(hasBit: hasBit) else { return defaultValue }
  493. return (buffer.baseAddress! + offset).bindMemory(to: UInt64.self, capacity: 1).pointee
  494. }
  495. /// Returns the `Float` value at the given offset in the storage, or the default value if the
  496. /// value is not present.
  497. @_alwaysEmitIntoClient @inline(__always)
  498. public func value(at offset: Int, default defaultValue: Float = 0, hasBit: HasBit) -> Float {
  499. guard isPresent(hasBit: hasBit) else { return defaultValue }
  500. return (buffer.baseAddress! + offset).bindMemory(to: Float.self, capacity: 1).pointee
  501. }
  502. /// Returns the `Double` value at the given offset in the storage, or the default value if the
  503. /// value is not present.
  504. @_alwaysEmitIntoClient @inline(__always)
  505. public func value(at offset: Int, default defaultValue: Double = 0, hasBit: HasBit) -> Double {
  506. guard isPresent(hasBit: hasBit) else { return defaultValue }
  507. return (buffer.baseAddress! + offset).bindMemory(to: Double.self, capacity: 1).pointee
  508. }
  509. /// Returns the string value at the given offset in the storage, or the default value if the
  510. /// value is not present.
  511. @_alwaysEmitIntoClient @inline(__always)
  512. public func value(at offset: Int, default defaultValue: String = "", hasBit: HasBit) -> String {
  513. guard isPresent(hasBit: hasBit) else { return defaultValue }
  514. return (buffer.baseAddress! + offset).bindMemory(to: String.self, capacity: 1).pointee
  515. }
  516. /// Returns the `Data` value at the given offset in the storage, or the default value if the
  517. /// value is not present.
  518. @_alwaysEmitIntoClient @inline(__always)
  519. public func value(at offset: Int, default defaultValue: Data = Data(), hasBit: HasBit) -> Data {
  520. guard isPresent(hasBit: hasBit) else { return defaultValue }
  521. return (buffer.baseAddress! + offset).bindMemory(to: Data.self, capacity: 1).pointee
  522. }
  523. /// Returns the `Array` value at the given offset in the storage, or the empty array if the
  524. /// value is not present.
  525. @_alwaysEmitIntoClient @inline(__always)
  526. public func value<Element>(at offset: Int, hasBit: HasBit) -> [Element] {
  527. guard isPresent(hasBit: hasBit) else { return [] }
  528. return (buffer.baseAddress! + offset).bindMemory(to: [Element].self, capacity: 1).pointee
  529. }
  530. /// Returns the `Dictionary` value at the given offset in the storage, or the empty array if
  531. /// the value is not present.
  532. @_alwaysEmitIntoClient @inline(__always)
  533. public func value<Key, Value>(at offset: Int, hasBit: HasBit) -> [Key: Value] {
  534. guard isPresent(hasBit: hasBit) else { return [:] }
  535. return (buffer.baseAddress! + offset).bindMemory(to: [Key: Value].self, capacity: 1).pointee
  536. }
  537. /// Returns the protobuf enum value at the given offset in the storage, or the default value if
  538. /// the value is not present.
  539. @_alwaysEmitIntoClient @inline(__always)
  540. public func value<T: Enum>(at offset: Int, default defaultValue: T, hasBit: HasBit) -> T {
  541. guard isPresent(hasBit: hasBit) else { return defaultValue }
  542. // It is always safe to force-unwrap this. For open enums, the raw value initializer never
  543. // fails. For closed enums, it fails if the raw value is not a valid case, but such a value
  544. // should never cause presence to be set. For example, during decoding such a value would be
  545. // placed in unknown fields.
  546. //
  547. // TODO: Change this to `Int32` when we're using that as the raw value type.
  548. return T(rawValue: Int((buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee))!
  549. }
  550. /// Returns the value at the given offset in the storage, or the default value if the value is
  551. /// not present.
  552. @_alwaysEmitIntoClient @inline(__always)
  553. public func value<T>(at offset: Int, default defaultValue: T, hasBit: HasBit) -> T {
  554. guard isPresent(hasBit: hasBit) else { return defaultValue }
  555. return (buffer.baseAddress! + offset).bindMemory(to: T.self, capacity: 1).pointee
  556. }
  557. }
  558. // MARK: - Field mutators used by generated accessors
  559. // As with the readers above, we have some concrete specializations of `updateValue` for trivial
  560. // types, since they can just store the new value (whether it's zero or some other non-zero default)
  561. // without managing any lifetimes.
  562. //
  563. // The generic implementation handles non-trivial cases, where we need to deinitialize an old value
  564. // that's present and then decide what to do with the incoming state. If the field will be
  565. // set/present, we store the new value; otherwise, we leave it uninitialized and zero it out.
  566. //
  567. // These APIs take the offset and has-bit directly because generating that produces more efficient
  568. // code for accessors than one that would have to extract the same information from a `FieldLayout`.
  569. extension _MessageStorage {
  570. /// Updates the `Bool` value at the given offset in the storage, along with its presence.
  571. @_alwaysEmitIntoClient @inline(__always)
  572. public func updateValue(at offset: Int, to newValue: Bool, willBeSet: Bool, hasBit: HasBit) {
  573. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Bool.self, capacity: 1)
  574. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  575. pointer.pointee = newValue
  576. }
  577. /// Updates the `Int32` value at the given offset in the storage, along with its presence.
  578. @_alwaysEmitIntoClient @inline(__always)
  579. public func updateValue(at offset: Int, to newValue: Int32, willBeSet: Bool, hasBit: HasBit) {
  580. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1)
  581. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  582. pointer.pointee = newValue
  583. }
  584. /// Updates the `UInt32` value at the given offset in the storage, along with its presence.
  585. @_alwaysEmitIntoClient @inline(__always)
  586. public func updateValue(at offset: Int, to newValue: UInt32, willBeSet: Bool, hasBit: HasBit) {
  587. let pointer = (buffer.baseAddress! + offset).bindMemory(to: UInt32.self, capacity: 1)
  588. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  589. pointer.pointee = newValue
  590. }
  591. /// Updates the `Int64` value at the given offset in the storage, along with its presence.
  592. @_alwaysEmitIntoClient @inline(__always)
  593. public func updateValue(at offset: Int, to newValue: Int64, willBeSet: Bool, hasBit: HasBit) {
  594. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Int64.self, capacity: 1)
  595. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  596. pointer.pointee = newValue
  597. }
  598. /// Updates the `UInt64` value at the given offset in the storage, along with its presence.
  599. @_alwaysEmitIntoClient @inline(__always)
  600. public func updateValue(at offset: Int, to newValue: UInt64, willBeSet: Bool, hasBit: HasBit) {
  601. let pointer = (buffer.baseAddress! + offset).bindMemory(to: UInt64.self, capacity: 1)
  602. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  603. pointer.pointee = newValue
  604. }
  605. /// Updates the `Float` value at the given offset in the storage, along with its presence.
  606. @_alwaysEmitIntoClient @inline(__always)
  607. public func updateValue(at offset: Int, to newValue: Float, willBeSet: Bool, hasBit: HasBit) {
  608. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Float.self, capacity: 1)
  609. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  610. pointer.pointee = newValue
  611. }
  612. /// Updates the `Double` value at the given offset in the storage, along with its presence.
  613. @_alwaysEmitIntoClient @inline(__always)
  614. public func updateValue(at offset: Int, to newValue: Double, willBeSet: Bool, hasBit: HasBit) {
  615. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Double.self, capacity: 1)
  616. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  617. pointer.pointee = newValue
  618. }
  619. /// Updates the protobuf enum value at the given offset in the storage, along with its presence.
  620. @_alwaysEmitIntoClient @inline(__always)
  621. public func updateValue<T: Enum>(at offset: Int, to newValue: T, willBeSet: Bool, hasBit: HasBit) {
  622. let pointer = (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1)
  623. _ = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  624. pointer.pointee = Int32(newValue.rawValue)
  625. }
  626. /// Updates the value at the given offset in the storage, along with its presence.
  627. @_alwaysEmitIntoClient @inline(__always)
  628. public func updateValue<T>(at offset: Int, to newValue: T, willBeSet: Bool, hasBit: HasBit) {
  629. let rawPointer = buffer.baseAddress! + offset
  630. let pointer = rawPointer.bindMemory(to: T.self, capacity: 1)
  631. let wasSet = updatePresence(hasBit: hasBit, willBeSet: willBeSet)
  632. if wasSet {
  633. pointer.deinitialize(count: 1)
  634. }
  635. if willBeSet {
  636. pointer.initialize(to: newValue)
  637. } else {
  638. rawPointer.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.stride) { bytes in
  639. bytes.initialize(repeating: 0, count: MemoryLayout<T>.stride)
  640. }
  641. }
  642. }
  643. /// Clears the value at the given offset in the storage, along with its presence.
  644. @_alwaysEmitIntoClient @inline(__always)
  645. public func clearValue<T>(at offset: Int, type: T.Type, hasBit: HasBit) {
  646. let rawPointer = buffer.baseAddress! + offset
  647. let pointer = rawPointer.bindMemory(to: T.self, capacity: 1)
  648. let wasSet = updatePresence(hasBit: hasBit, willBeSet: false)
  649. if wasSet {
  650. pointer.deinitialize(count: 1)
  651. }
  652. rawPointer.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.stride) { bytes in
  653. bytes.initialize(repeating: 0, count: MemoryLayout<T>.stride)
  654. }
  655. }
  656. }
  657. // MARK: - Field mutators used for parsing and reflection APIs
  658. // Unlike the above APIs, these only take a `FieldLayout` as an argument. These are used when
  659. // parsing messages and in reflection APIs, where we don't know the nature of an arbitrary field's
  660. // explicit presence (or lack of it) as we do when we generate accessors directly.
  661. extension _MessageStorage {
  662. /// Updates the `Bool` value of the given field, tracking its presence accordingly.
  663. func updateValue(of field: FieldLayout, to newValue: Bool) {
  664. let offset = field.offset
  665. switch field.presence {
  666. case .hasBit(let hasByteOffset, let hasMask):
  667. updateValue(
  668. at: offset,
  669. to: newValue,
  670. willBeSet: layout.fieldHasPresence(field) ? true : newValue,
  671. hasBit: (hasByteOffset, hasMask)
  672. )
  673. case .oneOfMember(let oneofOffset):
  674. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  675. }
  676. }
  677. /// Updates the `Int32` value of the given field, tracking its presence accordingly.
  678. func updateValue(of field: FieldLayout, to newValue: Int32) {
  679. let offset = field.offset
  680. switch field.presence {
  681. case .hasBit(let hasByteOffset, let hasMask):
  682. updateValue(
  683. at: offset,
  684. to: newValue,
  685. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  686. hasBit: (hasByteOffset, hasMask)
  687. )
  688. case .oneOfMember(let oneofOffset):
  689. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  690. }
  691. }
  692. /// Updates the `UInt32` value of the given field, tracking its presence accordingly.
  693. func updateValue(of field: FieldLayout, to newValue: UInt32) {
  694. let offset = field.offset
  695. switch field.presence {
  696. case .hasBit(let hasByteOffset, let hasMask):
  697. updateValue(
  698. at: offset,
  699. to: newValue,
  700. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  701. hasBit: (hasByteOffset, hasMask)
  702. )
  703. case .oneOfMember(let oneofOffset):
  704. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  705. }
  706. }
  707. /// Updates the `Int64` value of the given field, tracking its presence accordingly.
  708. func updateValue(of field: FieldLayout, to newValue: Int64) {
  709. let offset = field.offset
  710. switch field.presence {
  711. case .hasBit(let hasByteOffset, let hasMask):
  712. updateValue(
  713. at: offset,
  714. to: newValue,
  715. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  716. hasBit: (hasByteOffset, hasMask)
  717. )
  718. case .oneOfMember(let oneofOffset):
  719. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  720. }
  721. }
  722. /// Updates the `UInt64` value of the given field, tracking its presence accordingly.
  723. func updateValue(of field: FieldLayout, to newValue: UInt64) {
  724. let offset = field.offset
  725. switch field.presence {
  726. case .hasBit(let hasByteOffset, let hasMask):
  727. updateValue(
  728. at: offset,
  729. to: newValue,
  730. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  731. hasBit: (hasByteOffset, hasMask)
  732. )
  733. case .oneOfMember(let oneofOffset):
  734. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  735. }
  736. }
  737. /// Updates the `Float` value of the given field, tracking its presence accordingly.
  738. func updateValue(of field: FieldLayout, to newValue: Float) {
  739. let offset = field.offset
  740. switch field.presence {
  741. case .hasBit(let hasByteOffset, let hasMask):
  742. updateValue(
  743. at: offset,
  744. to: newValue,
  745. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  746. hasBit: (hasByteOffset, hasMask)
  747. )
  748. case .oneOfMember(let oneofOffset):
  749. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  750. }
  751. }
  752. /// Updates the `Double` value of the given field, tracking its presence accordingly.
  753. func updateValue(of field: FieldLayout, to newValue: Double) {
  754. let offset = field.offset
  755. switch field.presence {
  756. case .hasBit(let hasByteOffset, let hasMask):
  757. updateValue(
  758. at: offset,
  759. to: newValue,
  760. willBeSet: layout.fieldHasPresence(field) ? true : (newValue != 0),
  761. hasBit: (hasByteOffset, hasMask)
  762. )
  763. case .oneOfMember(let oneofOffset):
  764. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  765. }
  766. }
  767. /// Updates the `String` value of the given field, tracking its presence accordingly.
  768. func updateValue(of field: FieldLayout, to newValue: String) {
  769. let offset = field.offset
  770. switch field.presence {
  771. case .hasBit(let hasByteOffset, let hasMask):
  772. updateValue(
  773. at: offset,
  774. to: newValue,
  775. willBeSet: layout.fieldHasPresence(field) ? true : !newValue.isEmpty,
  776. hasBit: (hasByteOffset, hasMask)
  777. )
  778. case .oneOfMember(let oneofOffset):
  779. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  780. }
  781. }
  782. /// Updates the `Data` value of the given field, tracking its presence accordingly.
  783. func updateValue(of field: FieldLayout, to newValue: Data) {
  784. let offset = field.offset
  785. switch field.presence {
  786. case .hasBit(let hasByteOffset, let hasMask):
  787. updateValue(
  788. at: offset,
  789. to: newValue,
  790. willBeSet: layout.fieldHasPresence(field) ? true : !newValue.isEmpty,
  791. hasBit: (hasByteOffset, hasMask)
  792. )
  793. case .oneOfMember(let oneofOffset):
  794. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  795. }
  796. }
  797. /// Updates the protobuf enum value of the given field, tracking its presence accordingly.
  798. func updateValue<T: Enum>(of field: FieldLayout, to newValue: T) {
  799. let offset = field.offset
  800. switch field.presence {
  801. case .hasBit(let hasByteOffset, let hasMask):
  802. updateValue(
  803. at: offset,
  804. to: newValue,
  805. willBeSet: layout.fieldHasPresence(field) ? true : newValue != T(),
  806. hasBit: (hasByteOffset, hasMask)
  807. )
  808. case .oneOfMember(let oneofOffset):
  809. updateValue(at: offset, to: newValue, oneofPresence: (oneofOffset, field.fieldNumber))
  810. }
  811. }
  812. /// Appends the given value to the values already present in the field, initializing the field
  813. /// if necessary.
  814. func appendValue<T>(_ value: T, to field: FieldLayout) {
  815. // If the field isn't already present, we need to initialize a new array first.
  816. let pointer = (buffer.baseAddress! + field.offset).bindMemory(to: [T].self, capacity: 1)
  817. if !isPresent(field) {
  818. pointer.initialize(to: [value])
  819. switch field.presence {
  820. case .hasBit(let hasByteOffset, let hasMask):
  821. _ = updatePresence(hasBit: (hasByteOffset, hasMask), willBeSet: true)
  822. case .oneOfMember(let oneofOffset):
  823. _ = updatePopulatedOneofMember((oneofOffset, field.fieldNumber))
  824. }
  825. } else {
  826. pointer.pointee.append(value)
  827. }
  828. }
  829. }
  830. // MARK: - Oneof support
  831. extension _MessageStorage {
  832. /// Describes presence information that is used when getting or setting oneof members.
  833. public typealias OneofPresence = (offset: Int, fieldNumber: UInt32)
  834. /// Returns the field number of the oneof member that is populated, given the oneof offset into
  835. /// the storage buffer.
  836. @_alwaysEmitIntoClient @inline(__always)
  837. public func populatedOneofMember(at oneofOffset: Int) -> UInt32 {
  838. (buffer.baseAddress! + oneofOffset).bindMemory(to: UInt32.self, capacity: 1).pointee
  839. }
  840. /// Updates the field number of the oneof member that is populated, given the oneof offset into
  841. /// the storage buffer, and returns the field number of the previously set member (or zero if
  842. /// none was set).
  843. @_alwaysEmitIntoClient @inline(__always)
  844. public func updatePopulatedOneofMember(_ presence: OneofPresence) -> UInt32 {
  845. let offsetPointer = (buffer.baseAddress! + presence.offset).bindMemory(to: UInt32.self, capacity: 1)
  846. let oldFieldNumber = offsetPointer.pointee
  847. offsetPointer.pointee = presence.fieldNumber
  848. return oldFieldNumber
  849. }
  850. /// Returns the `Bool` value at the given offset in the storage if it is the currently
  851. /// populated member of its containing oneof, or the default value otherwise.
  852. @_alwaysEmitIntoClient @inline(__always)
  853. public func value(at offset: Int, default defaultValue: Bool = false, oneofPresence: OneofPresence) -> Bool {
  854. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  855. return defaultValue
  856. }
  857. return (buffer.baseAddress! + offset).bindMemory(to: Bool.self, capacity: 1).pointee
  858. }
  859. /// Returns the `Int32` value at the given offset in the storage if it is the currently
  860. /// populated member of its containing oneof, or the default value otherwise.
  861. @_alwaysEmitIntoClient @inline(__always)
  862. public func value(at offset: Int, default defaultValue: Int32 = 0, oneofPresence: OneofPresence) -> Int32 {
  863. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  864. return defaultValue
  865. }
  866. return (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee
  867. }
  868. /// Returns the `UInt32` value at the given offset in the storage if it is the currently
  869. /// populated member of its containing oneof, or the default value otherwise.
  870. @_alwaysEmitIntoClient @inline(__always)
  871. public func value(at offset: Int, default defaultValue: UInt32 = 0, oneofPresence: OneofPresence) -> UInt32 {
  872. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  873. return defaultValue
  874. }
  875. return (buffer.baseAddress! + offset).bindMemory(to: UInt32.self, capacity: 1).pointee
  876. }
  877. /// Returns the `Int64` value at the given offset in the storage if it is the currently
  878. /// populated member of its containing oneof, or the default value otherwise.
  879. @_alwaysEmitIntoClient @inline(__always)
  880. public func value(at offset: Int, default defaultValue: Int64 = 0, oneofPresence: OneofPresence) -> Int64 {
  881. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  882. return defaultValue
  883. }
  884. return (buffer.baseAddress! + offset).bindMemory(to: Int64.self, capacity: 1).pointee
  885. }
  886. /// Returns the `UInt64` value at the given offset in the storage if it is the currently
  887. /// populated member of its containing oneof, or the default value otherwise.
  888. @_alwaysEmitIntoClient @inline(__always)
  889. public func value(at offset: Int, default defaultValue: UInt64 = 0, oneofPresence: OneofPresence) -> UInt64 {
  890. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  891. return defaultValue
  892. }
  893. return (buffer.baseAddress! + offset).bindMemory(to: UInt64.self, capacity: 1).pointee
  894. }
  895. /// Returns the `Float` value at the given offset in the storage if it is the currently
  896. /// populated member of its containing oneof, or the default value otherwise.
  897. @_alwaysEmitIntoClient @inline(__always)
  898. public func value(at offset: Int, default defaultValue: Float = 0, oneofPresence: OneofPresence) -> Float {
  899. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  900. return defaultValue
  901. }
  902. return (buffer.baseAddress! + offset).bindMemory(to: Float.self, capacity: 1).pointee
  903. }
  904. /// Returns the `Double` value at the given offset in the storage if it is the currently
  905. /// populated member of its containing oneof, or the default value otherwise.
  906. @_alwaysEmitIntoClient @inline(__always)
  907. public func value(at offset: Int, default defaultValue: Double = 0, oneofPresence: OneofPresence) -> Double {
  908. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  909. return defaultValue
  910. }
  911. return (buffer.baseAddress! + offset).bindMemory(to: Double.self, capacity: 1).pointee
  912. }
  913. /// Returns the `String` value at the given offset in the storage if it is the currently
  914. /// populated member of its containing oneof, or the default value otherwise.
  915. @_alwaysEmitIntoClient @inline(__always)
  916. public func value(at offset: Int, default defaultValue: String = "", oneofPresence: OneofPresence) -> String {
  917. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  918. return defaultValue
  919. }
  920. return (buffer.baseAddress! + offset).bindMemory(to: String.self, capacity: 1).pointee
  921. }
  922. /// Returns the `Data` value at the given offset in the storage if it is the currently
  923. /// populated member of its containing oneof, or the default value otherwise.
  924. @_alwaysEmitIntoClient @inline(__always)
  925. public func value(at offset: Int, default defaultValue: Data = Data(), oneofPresence: OneofPresence) -> Data {
  926. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  927. return defaultValue
  928. }
  929. return (buffer.baseAddress! + offset).bindMemory(to: Data.self, capacity: 1).pointee
  930. }
  931. /// Returns the protobuf enum value at the given offset in the storage if it is the currently
  932. /// populated member of its containing oneof, or the default value otherwise.
  933. @_alwaysEmitIntoClient @inline(__always)
  934. public func value<T: Enum>(at offset: Int, default defaultValue: T, oneofPresence: OneofPresence) -> T {
  935. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  936. return defaultValue
  937. }
  938. // It is always safe to force-unwrap this. For open enums, the raw value initializer never
  939. // fails. For closed enums, it fails if the raw value is not a valid case, but such a value
  940. // should never cause presence to be set. For example, during decoding such a value would be
  941. // placed in unknown fields.
  942. //
  943. // TODO: Change this to `Int32` when we're using that as the raw value type.
  944. return T(rawValue: Int((buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee))!
  945. }
  946. /// Returns the value at the given offset in the storage if it is the currently populated
  947. /// member of its containing oneof, or the default value otherwise.
  948. @_alwaysEmitIntoClient @inline(__always)
  949. public func value<T>(at offset: Int, default defaultValue: T, oneofPresence: OneofPresence) -> T {
  950. guard populatedOneofMember(at: oneofPresence.offset) == oneofPresence.fieldNumber else {
  951. return defaultValue
  952. }
  953. return (buffer.baseAddress! + offset).bindMemory(to: T.self, capacity: 1).pointee
  954. }
  955. /// Updates the `Bool` value at the given offset in the storage, along with its presence.
  956. @_alwaysEmitIntoClient @inline(__always)
  957. public func updateValue(at offset: Int, to newValue: Bool, oneofPresence: OneofPresence) {
  958. let rawPointer = buffer.baseAddress! + offset
  959. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  960. if oldFieldNumber != 0 {
  961. // We can force-unwrap this because the field must exist or it would be a generator bug.
  962. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  963. }
  964. rawPointer.bindMemory(to: Bool.self, capacity: 1).pointee = newValue
  965. }
  966. /// Updates the `Int32` value at the given offset in the storage, along with its presence.
  967. @_alwaysEmitIntoClient @inline(__always)
  968. public func updateValue(at offset: Int, to newValue: Int32, oneofPresence: OneofPresence) {
  969. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  970. if oldFieldNumber != 0 {
  971. // We can force-unwrap this because the field must exist or it would be a generator bug.
  972. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  973. }
  974. (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).pointee = newValue
  975. }
  976. /// Updates the `UInt32` value at the given offset in the storage, along with its presence.
  977. @_alwaysEmitIntoClient @inline(__always)
  978. public func updateValue(at offset: Int, to newValue: UInt32, oneofPresence: OneofPresence) {
  979. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  980. if oldFieldNumber != 0 {
  981. // We can force-unwrap this because the field must exist or it would be a generator bug.
  982. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  983. }
  984. (buffer.baseAddress! + offset).bindMemory(to: UInt32.self, capacity: 1).pointee = newValue
  985. }
  986. /// Updates the `Int64` value at the given offset in the storage, along with its presence.
  987. @_alwaysEmitIntoClient @inline(__always)
  988. public func updateValue(at offset: Int, to newValue: Int64, oneofPresence: OneofPresence) {
  989. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  990. if oldFieldNumber != 0 {
  991. // We can force-unwrap this because the field must exist or it would be a generator bug.
  992. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  993. }
  994. (buffer.baseAddress! + offset).bindMemory(to: Int64.self, capacity: 1).pointee = newValue
  995. }
  996. /// Updates the `UInt64` value at the given offset in the storage, along with its presence.
  997. @_alwaysEmitIntoClient @inline(__always)
  998. public func updateValue(at offset: Int, to newValue: UInt64, oneofPresence: OneofPresence) {
  999. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  1000. if oldFieldNumber != 0 {
  1001. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1002. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1003. }
  1004. (buffer.baseAddress! + offset).bindMemory(to: UInt64.self, capacity: 1).pointee = newValue
  1005. }
  1006. /// Updates the `Float` value at the given offset in the storage, along with its presence.
  1007. @_alwaysEmitIntoClient @inline(__always)
  1008. public func updateValue(at offset: Int, to newValue: Float, oneofPresence: OneofPresence) {
  1009. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  1010. if oldFieldNumber != 0 {
  1011. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1012. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1013. }
  1014. (buffer.baseAddress! + offset).bindMemory(to: Float.self, capacity: 1).pointee = newValue
  1015. }
  1016. /// Updates the `Double` value at the given offset in the storage, along with its presence.
  1017. @_alwaysEmitIntoClient @inline(__always)
  1018. public func updateValue(at offset: Int, to newValue: Double, oneofPresence: OneofPresence) {
  1019. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  1020. if oldFieldNumber != 0 {
  1021. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1022. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1023. }
  1024. (buffer.baseAddress! + offset).bindMemory(to: Double.self, capacity: 1).pointee = newValue
  1025. }
  1026. /// Updates the protobuf enum value at the given offset in the storage, along with its presence.
  1027. @_alwaysEmitIntoClient @inline(__always)
  1028. public func updateValue<T: Enum>(at offset: Int, to newValue: T, oneofPresence: OneofPresence) {
  1029. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  1030. if oldFieldNumber != 0 {
  1031. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1032. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1033. }
  1034. (buffer.baseAddress! + offset).bindMemory(to: Int32.self, capacity: 1).initialize(to: Int32(newValue.rawValue))
  1035. }
  1036. /// Updates the value at the given offset in the storage, along with its presence.
  1037. @_alwaysEmitIntoClient @inline(__always)
  1038. public func updateValue<T>(at offset: Int, to newValue: T, oneofPresence: OneofPresence) {
  1039. let oldFieldNumber = updatePopulatedOneofMember(oneofPresence)
  1040. if oldFieldNumber != 0 {
  1041. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1042. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1043. }
  1044. (buffer.baseAddress! + offset).bindMemory(to: T.self, capacity: 1).initialize(to: newValue)
  1045. }
  1046. /// Clears the populated oneof member give the oneof offset into the storage buffer,
  1047. /// deinitializing any existing value if necessary.
  1048. @_alwaysEmitIntoClient @inline(__always)
  1049. public func clearPopulatedOneofMember(at oneofOffset: Int) {
  1050. let oldFieldNumber = updatePopulatedOneofMember((offset: oneofOffset, fieldNumber: 0))
  1051. guard oldFieldNumber != 0 else { return }
  1052. // We can force-unwrap this because the field must exist or it would be a generator bug.
  1053. deinitializeOneofMember(layout[fieldNumber: oldFieldNumber]!)
  1054. }
  1055. /// Deinitializes the value for the given field that is a oneof member and zeros out the
  1056. /// storage slot.
  1057. ///
  1058. /// - Precondition: The value associated with this field must be initialized.
  1059. @_alwaysEmitIntoClient @inline(__always)
  1060. private func deinitializeOneofMember(_ field: FieldLayout) {
  1061. // TODO: We could skip zeroing out the backing storage if this is part of a mutation that
  1062. // is setting the same member that's being deinitialized. Determine if that's a worthwhile
  1063. // optimization.
  1064. deinitializeField(field)
  1065. let stride = field.scalarStride
  1066. (buffer.baseAddress! + field.offset).withMemoryRebound(to: UInt8.self, capacity: stride) { bytes in
  1067. bytes.initialize(repeating: 0, count: stride)
  1068. }
  1069. }
  1070. }
  1071. // MARK: - Message equality
  1072. extension _MessageStorage {
  1073. /// Tests this message storage for equality with the other storage.
  1074. ///
  1075. /// Precondition: Both instances of storage are assumed to be represented by the same message
  1076. /// type.
  1077. ///
  1078. /// Message equality in SwiftProtobuf includes presence. That is, a message with an integer
  1079. /// field set to 100 is not considered equal to one where that field is not present but has a
  1080. /// default defined to be 100.
  1081. @inline(never)
  1082. public func isEqual(to other: _MessageStorage) -> Bool {
  1083. if self === other {
  1084. /// Identical message storage means they must be equal.
  1085. return true
  1086. }
  1087. // TODO: If we store the offset of the first non-trivial field in the layout, we can make
  1088. // this extremely fast by doing the memcmp up front and failing fast. Likewise, we can also
  1089. // avoid the loop entirely if the message contains only trivial fields. We could see similar
  1090. // performance wins for copy and deinit.
  1091. // Loops through the fields, checking equality of any that are non-trivial types. We ignore
  1092. // the trivial ones here, instead tracking the byte offset of the first non-trivial field
  1093. // so that we can bitwise-compare those as a block afterward.
  1094. var firstNontrivialStorageOffset = layout.size
  1095. var equalSoFar = true
  1096. for field in layout.fields {
  1097. switch field.fieldMode.cardinality {
  1098. case .map:
  1099. if field.offset < firstNontrivialStorageOffset {
  1100. firstNontrivialStorageOffset = field.offset
  1101. }
  1102. // TODO: Support map fields.
  1103. break
  1104. case .array:
  1105. if field.offset < firstNontrivialStorageOffset {
  1106. firstNontrivialStorageOffset = field.offset
  1107. }
  1108. switch field.rawFieldType {
  1109. case .bool:
  1110. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Bool].self)
  1111. case .bytes:
  1112. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Data].self)
  1113. case .double:
  1114. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Double].self)
  1115. case .enum, .group, .message:
  1116. equalSoFar = layout.areFieldsEqual(
  1117. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  1118. field,
  1119. self,
  1120. other
  1121. )
  1122. case .fixed32, .uint32:
  1123. equalSoFar = isField(field, equalToSameFieldIn: other, type: [UInt32].self)
  1124. case .fixed64, .uint64:
  1125. equalSoFar = isField(field, equalToSameFieldIn: other, type: [UInt64].self)
  1126. case .float:
  1127. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Float].self)
  1128. case .int32, .sfixed32, .sint32:
  1129. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Int32].self)
  1130. case .int64, .sfixed64, .sint64:
  1131. equalSoFar = isField(field, equalToSameFieldIn: other, type: [Int64].self)
  1132. case .string:
  1133. equalSoFar = isField(field, equalToSameFieldIn: other, type: [String].self)
  1134. default:
  1135. preconditionFailure("Unreachable")
  1136. }
  1137. case .scalar:
  1138. switch field.rawFieldType {
  1139. case .bytes:
  1140. if field.offset < firstNontrivialStorageOffset {
  1141. firstNontrivialStorageOffset = field.offset
  1142. }
  1143. equalSoFar = isField(field, equalToSameFieldIn: other, type: Data.self)
  1144. case .group, .message:
  1145. if field.offset < firstNontrivialStorageOffset {
  1146. firstNontrivialStorageOffset = field.offset
  1147. }
  1148. equalSoFar = layout.areFieldsEqual(
  1149. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  1150. field,
  1151. self,
  1152. other
  1153. )
  1154. case .string:
  1155. if field.offset < firstNontrivialStorageOffset {
  1156. firstNontrivialStorageOffset = field.offset
  1157. }
  1158. equalSoFar = isField(field, equalToSameFieldIn: other, type: String.self)
  1159. default:
  1160. // Do nothing. Trivial fields will be bitwise-compared as a block below.
  1161. break
  1162. }
  1163. default:
  1164. preconditionFailure("Unreachable")
  1165. }
  1166. guard equalSoFar else {
  1167. return false
  1168. }
  1169. }
  1170. // Compare all of the trivial values (including has-bits) in bitwise fashion.
  1171. if firstNontrivialStorageOffset != 0
  1172. && memcmp(buffer.baseAddress!, other.buffer.baseAddress!, firstNontrivialStorageOffset) != 0
  1173. {
  1174. return false
  1175. }
  1176. if unknownFields.data != other.unknownFields.data {
  1177. return false
  1178. }
  1179. return true
  1180. }
  1181. /// Returns whether the given field in the receiver is equal to the same field in the other
  1182. /// storage, given the expected type of that field.
  1183. public func isField<T: Equatable>(
  1184. _ field: FieldLayout,
  1185. equalToSameFieldIn other: _MessageStorage,
  1186. type: T.Type
  1187. ) -> Bool {
  1188. let isSelfPresent = isPresent(field)
  1189. let isOtherPresent = other.isPresent(field)
  1190. guard isSelfPresent && isOtherPresent else {
  1191. // If the field isn't present in both messages, then it must be absent in both to be
  1192. // considered equal.
  1193. return isSelfPresent == isOtherPresent
  1194. }
  1195. // The field is present in both messages, so compare their values.
  1196. let selfPointer = (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1)
  1197. let otherPointer = (other.buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1)
  1198. return selfPointer.pointee == otherPointer.pointee
  1199. }
  1200. }
  1201. // MARK: - Message initialized (i.e., required fields) check
  1202. extension _MessageStorage {
  1203. /// Indicates whether all required fields are present in this message.
  1204. ///
  1205. /// This is a shallow check; it does not recurse into submessages to check their initialized
  1206. /// state.
  1207. @inline(never)
  1208. private var isMessageInitializedShallow: Bool {
  1209. // A message with no required fields is trivially considered initialized.
  1210. guard layout.requiredCount > 0 else { return true }
  1211. // The has-bits for the required fields have been ordered first in storage, so we can
  1212. // quickly determine whether a message is initialzed using a simple `memcmp` (with at most
  1213. // one additional masked byte comparison for overflow bits).
  1214. let requiredByteCount = layout.requiredCount / 8
  1215. if requiredByteCount > 0 {
  1216. let requiredBytesAllSet = withUnsafeTemporaryAllocation(of: UInt8.self, capacity: requiredByteCount) {
  1217. allSetBuffer in
  1218. allSetBuffer.initialize(repeating: 0xff)
  1219. return memcmp(buffer.baseAddress!, allSetBuffer.baseAddress!, requiredByteCount) == 0
  1220. }
  1221. guard requiredBytesAllSet else { return false }
  1222. }
  1223. // If the number of required has-bits is not a multiple of 8, check the remaining bits.
  1224. // These may be followed immediately by has-bits for non-required fields so we need to mask
  1225. // off just the required ones.
  1226. let remainingBits = UInt8(layout.requiredCount & 7)
  1227. guard remainingBits != 0 else { return true }
  1228. let remainingMask: UInt8 = (1 << remainingBits) - 1
  1229. return buffer[requiredByteCount] & remainingMask == remainingMask
  1230. }
  1231. /// Indicates whether all required fields are present in this message, recursively checking
  1232. /// submessages.
  1233. public var isInitialized: Bool {
  1234. guard isMessageInitializedShallow else { return false }
  1235. for field in layout.fields {
  1236. switch field.rawFieldType {
  1237. case .message, .group:
  1238. guard isPresent(field) else {
  1239. // If the submessage is not present, check if it's required. If it is, then
  1240. // we're not initialized; otherwise, we can skip to the next field.
  1241. if layout.isFieldRequired(field) {
  1242. return false
  1243. }
  1244. continue
  1245. }
  1246. // This never actually throws because the closure cannot throw, but closures cannot
  1247. // be declared rethrows.
  1248. let isSubmessageInitialized = try! layout.performOnSubmessageStorage(
  1249. _MessageLayout.TrampolineToken(index: field.submessageIndex),
  1250. field,
  1251. self,
  1252. .read
  1253. ) { $0.isInitialized }
  1254. guard isSubmessageInitialized else { return false }
  1255. default:
  1256. // Nothing to do for other types of fields; they've already been considered by the
  1257. // shallow check.
  1258. break
  1259. }
  1260. }
  1261. // TODO: Check extension fields.
  1262. return true
  1263. }
  1264. /// Returns whether the given field in the receiver, which must be another message type, is
  1265. /// initialized (recursively).
  1266. public func isFieldInitialized<T: Message>(_ field: FieldLayout, type: T.Type) -> Bool {
  1267. (buffer.baseAddress! + field.offset).bindMemory(to: T.self, capacity: 1).pointee.isInitialized
  1268. }
  1269. /// Returns whether the given field in the receiver, which must be an array of a message type,
  1270. /// is initialized (recursively).
  1271. public func isFieldInitialized<T: Message>(_ field: FieldLayout, type: [T].Type) -> Bool {
  1272. (buffer.baseAddress! + field.offset).bindMemory(to: [T].self, capacity: 1).pointee.allSatisfy {
  1273. $0.isInitialized
  1274. }
  1275. }
  1276. }
  1277. /// A token that allows the runtime to access the underlying storage of a message.
  1278. ///
  1279. /// This type is public because the runtime must be able to generically access the underlying
  1280. /// storage of a message, so a protocol requirement on `_MessageImplementationBase` is provided that
  1281. /// takes a value of this type as an argument. However, only the runtime may create instances of it.
  1282. public struct _MessageStorageToken {
  1283. init() {}
  1284. }
  1285. /// A macro-like helper function used in generated code to simplify writing platform-specific
  1286. /// offsets in field accessors.
  1287. ///
  1288. /// By virtue of being declared transparent, the compiler will always be able to reduce this down
  1289. /// to a single integer load depending on the target platform, so this function has no real
  1290. /// overhead and we are able to keep the generated code more compact than if we had to express the
  1291. /// `#if` blocks directly inside each accessor.
  1292. @_transparent
  1293. public func _fieldOffset(_ pointerWidth64: Int, _ pointerWidth32: Int) -> Int {
  1294. #if _pointerBitWidth(_64)
  1295. pointerWidth64
  1296. #elseif _pointerBitWidth(_32)
  1297. pointerWidth32
  1298. #else
  1299. #error("Unsupported platform")
  1300. #endif
  1301. }