From 21a0ca42df595bd58878ed19ef1feb5a9d3bf210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Tue, 24 Nov 2026 15:49:44 +0000 Subject: [PATCH] Keep Swift unknown fields behind one pointer --- .../src/main/swift/UnknownFields.swift | 59 +++++--- .../src/test/swift/UnknownFieldsTests.swift | 135 ++++++++++++++++++ 2 files changed, 175 insertions(+), 19 deletions(-) diff --git a/wire-runtime-swift/src/main/swift/UnknownFields.swift b/wire-runtime-swift/src/main/swift/UnknownFields.swift index a278a27c4c..97036b07ef 100644 --- a/wire-runtime-swift/src/main/swift/UnknownFields.swift +++ b/wire-runtime-swift/src/main/swift/UnknownFields.swift @@ -25,16 +25,21 @@ import Foundation /// A dictionary value must hold only complete wire fields that carry its key as their tag. /// The dictionary style accessors (`subscript`, `keys`, `values`, `count`, `removeValue` and `updateValue`) /// read the bytes each time, so their cost is linear in the size of the data. +/// +/// This type is one pointer in size, because every generated message holds one and messages are stored inline in each other. +/// The bytes live in a reference to a box that is nil when there are no fields, so an empty value does not allocate. +/// Copies share the box, and a mutation copies the bytes first when the box is shared. public struct UnknownFields: Sendable { public typealias Key = UInt32 public typealias Value = Data + /// Holds the bytes of the fields. It is nil if, and only if, there are no fields. + private var storage: Storage? + /// The wire bytes of every field, ordered by tag. - public private(set) var rawData: Data + public var rawData: Data { storage?.data ?? Data() } - public init() { - rawData = Data() - } + public init() {} /// Creates unknown fields from wire bytes. /// @@ -42,13 +47,13 @@ public struct UnknownFields: Sendable { /// Bytes that are not valid fields are kept at the end, as they are. public init(rawData: Data) { // This also moves a `Data` slice to indices that start at zero. - self.rawData = Data(rawData) - self.canonicalize() + let data = Data(rawData) + self.init(orderedRawData: data.withUnsafeBytes { Self.orderedCopy(of: $0) } ?? data) } /// Creates unknown fields from bytes that are already ordered by tag. internal init(orderedRawData: Data) { - self.rawData = orderedRawData + self.storage = orderedRawData.isEmpty ? nil : Storage(orderedRawData) } /// Creates unknown fields from a dictionary of tag to wire bytes. @@ -68,7 +73,7 @@ public struct UnknownFields: Sendable { for tag in fieldsByTag.keys.sorted() { data.append(fieldsByTag[tag]!) } - self.rawData = data + self.init(orderedRawData: data) } /// Creates empty unknown fields. The capacity is ignored. @@ -76,7 +81,7 @@ public struct UnknownFields: Sendable { self.init() } - public var isEmpty: Bool { rawData.isEmpty } + public var isEmpty: Bool { storage == nil } /// The number of distinct tags. This reads all the data. public var count: Int { @@ -200,7 +205,18 @@ public struct UnknownFields: Sendable { if let newValue { result.append(newValue) } result.append(bytes, removeEnd...) } - rawData = result + replaceRawData(with: result) + } + } + + /// Sets the bytes, and reuses the box when no other copy shares it. + private mutating func replaceRawData(with data: Data) { + if data.isEmpty { + storage = nil + } else if isKnownUniquelyReferenced(&storage) { + storage?.data = data + } else { + storage = Storage(data) } } @@ -291,16 +307,9 @@ public struct UnknownFields: Sendable { return isValid && end == data.count } - /// Orders the fields by tag. Fields with the same tag keep their order. - private mutating func canonicalize() { - if let ordered = rawData.withUnsafeBytes({ Self.orderedCopy(of: $0) }) { - rawData = ordered - } - } - /// Creates unknown fields from bytes that may be out of order, without first copying them to a `Data`. internal init(unorderedBytes bytes: UnsafeRawBufferPointer) { - self.rawData = Self.orderedCopy(of: bytes) ?? Data(bytes) + self.init(orderedRawData: Self.orderedCopy(of: bytes) ?? Data(bytes)) } /// Returns the fields ordered by tag, or nil if they already are. Fields with the same tag keep their order. @@ -391,9 +400,21 @@ private struct TagOffset { var offset: Int } +/// The shared bytes of one or more `UnknownFields` values. +/// +/// The owner of a reference changes `data` only after `isKnownUniquelyReferenced` returned true for it. +/// A box that is shared is never changed, so it is safe to read from many threads. +private final class Storage: @unchecked Sendable { + var data: Data + + init(_ data: Data) { + self.data = data + } +} + extension UnknownFields: Equatable, Hashable { public static func == (lhs: Self, rhs: Self) -> Bool { - lhs.rawData == rhs.rawData + lhs.storage === rhs.storage || lhs.rawData == rhs.rawData } public func hash(into hasher: inout Hasher) { diff --git a/wire-runtime-swift/src/test/swift/UnknownFieldsTests.swift b/wire-runtime-swift/src/test/swift/UnknownFieldsTests.swift index 34222b92c0..b368ec2c1e 100644 --- a/wire-runtime-swift/src/test/swift/UnknownFieldsTests.swift +++ b/wire-runtime-swift/src/test/swift/UnknownFieldsTests.swift @@ -618,6 +618,136 @@ final class UnknownFieldsTests: XCTestCase { XCTAssertTrue(message.unknownFields.isEmpty) } + // MARK: - Tests - Size and Copy on Write + + func testUnknownFieldsIsOnePointerInSize() { + XCTAssertEqual(MemoryLayout.size, 8) + XCTAssertEqual(MemoryLayout.size, MemoryLayout.size) + } + + func testExtensibleUnknownFieldsIsAtMostTwoPointersInSize() { + XCTAssertLessThanOrEqual(MemoryLayout.size, 16) + } + + func testEmptyUnknownFieldsAreEmptyEverywhere() throws { + var fields = UnknownFields() + XCTAssertTrue(fields.isEmpty) + XCTAssertEqual(fields.rawData, Foundation.Data()) + XCTAssertEqual(fields, UnknownFields(rawData: Foundation.Data())) + XCTAssertEqual(fields, UnknownFields(fieldsByTag: [:])) + XCTAssertEqual(fields.hashValue, UnknownFields(rawData: Foundation.Data()).hashValue) + + // Removing the last field makes the value empty again. + fields[1] = Foundation.Data(varintField(1, 1)) + XCTAssertFalse(fields.isEmpty) + fields[1] = nil + XCTAssertTrue(fields.isEmpty) + XCTAssertEqual(fields, UnknownFields()) + } + + func testMutatingACopyOfUnknownFieldsDoesNotChangeTheOriginal() { + var original = UnknownFields() + original[10] = Foundation.Data(varintField(10, 1)) + original[30] = Foundation.Data(varintField(30, 3)) + let originalBytes = original.rawData + + var copy = original + copy[20] = Foundation.Data(varintField(20, 2)) + XCTAssertEqual(original.rawData, originalBytes) + XCTAssertEqual(original.keys, [10, 30]) + XCTAssertEqual(copy.keys, [10, 20, 30]) + + var replaced = original + replaced[10] = Foundation.Data(varintField(10, 99)) + XCTAssertEqual(original[10], Foundation.Data(varintField(10, 1))) + XCTAssertEqual(replaced[10], Foundation.Data(varintField(10, 99))) + + var removed = original + removed[30] = nil + XCTAssertEqual(original.keys, [10, 30]) + XCTAssertEqual(removed.keys, [10]) + + var emptied = original + emptied.fieldsByTag = [:] + XCTAssertTrue(emptied.isEmpty) + XCTAssertEqual(original.rawData, originalBytes) + } + + func testMutatingTheOriginalDoesNotChangeItsCopies() { + var original = UnknownFields() + original[10] = Foundation.Data(varintField(10, 1)) + let copy = original + + original[10] = Foundation.Data(varintField(10, 2)) + original[5] = Foundation.Data(varintField(5, 5)) + + XCTAssertEqual(copy.rawData, Foundation.Data(varintField(10, 1))) + XCTAssertEqual(original.rawData, Foundation.Data(varintField(5, 5) + varintField(10, 2))) + } + + func testMutatingAUniqueValueKeepsGivingTheRightBytes() { + var fields = UnknownFields() + for tag in stride(from: UInt32(50), through: 1, by: -1) { + fields[tag] = Foundation.Data(varintField(tag, UInt64(tag))) + } + XCTAssertEqual(fields.keys, Array(1...50)) + XCTAssertEqual(fields.rawData, Foundation.Data((1...50).flatMap { varintField(UInt32($0), UInt64($0)) })) + } + + func testUnknownFieldsFromDecodingAreNotChangedByMutatingACopyOfTheMessage() throws { + let input = Foundation.Data(varintField(1, 7) + varintField(100, 1) + varintField(200, 2)) + let original = try ProtoDecoder().decode(SimpleOptional2.self, from: input) + + var copy = original + copy.unknownFields[150] = Foundation.Data(varintField(150, 3)) + copy.opt_int32 = 8 + + XCTAssertEqual(original.opt_int32, 7) + XCTAssertEqual(original.unknownFields.keys, [100, 200]) + XCTAssertEqual(try ProtoEncoder().encode(original), input) + XCTAssertEqual(copy.unknownFields.keys, [100, 150, 200]) + XCTAssertNotEqual(original, copy) + } + + func testEqualityDoesNotDependOnSharingTheSameBuffer() throws { + let input = Foundation.Data(varintField(100, 1) + varintField(200, 2)) + let first = try ProtoDecoder().decode(SimpleOptional2.self, from: input) + let second = try ProtoDecoder().decode(SimpleOptional2.self, from: input) + let copy = first + + XCTAssertEqual(first.unknownFields, second.unknownFields) + XCTAssertEqual(first.unknownFields, copy.unknownFields) + XCTAssertEqual(first.unknownFields.hashValue, second.unknownFields.hashValue) + } + + func testExtensibleUnknownFieldsCopyOnWriteWithTheSharedBuffer() throws { + var original = ExtensibleUnknownFields() + original[10] = Foundation.Data(varintField(10, 1)) + var copy = original + + copy[10] = Foundation.Data(varintField(10, 2)) + copy[20] = Foundation.Data(varintField(20, 3)) + + XCTAssertEqual(original.rawData, Foundation.Data(varintField(10, 1))) + XCTAssertEqual(copy.rawData, Foundation.Data(varintField(10, 2) + varintField(20, 3))) + } + + func testUnknownFieldsCanBeSharedAcrossThreads() { + var fields = UnknownFields() + for tag in 1...100 { fields[UInt32(tag)] = Foundation.Data(varintField(UInt32(tag), 1)) } + let expected = fields.rawData + let results = (0..<8).map { _ in Atomic(false) } + + DispatchQueue.concurrentPerform(iterations: 8) { index in + var local = fields + local[1000 + UInt32(index)] = Foundation.Data(varintField(1000 + UInt32(index), 1)) + results[index].value = fields.rawData == expected && local.keys.count == 101 + } + + XCTAssertTrue(results.allSatisfy { $0.value }) + XCTAssertEqual(fields.rawData, expected) + } + // MARK: - Helpers private func varintBytes(_ value: UInt64) -> [UInt8] { @@ -655,3 +785,8 @@ final class UnknownFieldsTests: XCTestCase { key(tag, 5) + (0..<4).map { UInt8((value >> (8 * UInt32($0))) & 0xFF) } } } + +private final class Atomic: @unchecked Sendable { + var value: T + init(_ value: T) { self.value = value } +}