From 62bbc6e92cbc623f5fd7e7b588ec9fa81fa86f72 Mon Sep 17 00:00:00 2001 From: Daniel Eggert Date: Wed, 18 Nov 2026 15:28:21 +0100 Subject: [PATCH] Tighten Bytes API docs State the donation threshold only on makeDispatchData(), restore IMAPByteStorage's allocation cost to the doc comment, move the copiedBytes() note to the method, and fix four broken links. --- Sources/NIOIMAP/Bytes/ByteBufferOutput.swift | 480 ------------------ Sources/NIOIMAPCore/Bytes/ByteRegion.swift | 2 +- Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift | 7 +- .../NIOIMAPCore/Bytes/IMAPByteStorage.swift | 8 +- .../NIOIMAPCore/Bytes/IMAPInputBuffer.swift | 4 +- 5 files changed, 11 insertions(+), 490 deletions(-) delete mode 100644 Sources/NIOIMAP/Bytes/ByteBufferOutput.swift diff --git a/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift b/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift deleted file mode 100644 index 6d5f15b1..00000000 --- a/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift +++ /dev/null @@ -1,480 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftNIO project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import NIO -import NIOIMAPCore - -/// Encoded output written straight into a `ByteBuffer`. -/// -/// This is the ``EncoderOutputBuffer`` to consider when the bytes are going to a NIO `Channel`. Every -/// byte of a command or response is copied exactly once — into the buffer as it is encoded — and -/// handing a chunk out costs no copy at all: the regions ``takeFirst(_:)`` returns are slices of that -/// same buffer, so `IMAPBufferList.makeByteBuffers()` recovers them without touching a byte. -/// -/// ## Choosing between this and `IMAPOutputBuffer` -/// -/// Pass it as the `sink:` argument of a ``CommandEncodeBuffer`` or ``ResponseEncodeBuffer``: -/// -/// ```swift -/// var encoder = CommandEncodeBuffer(sink: ByteBufferOutput(), options: options, loggingMode: false) -/// ``` -/// -/// It is deliberately *not* the default, and ``IMAPClientHandler`` and ``IMAPServerHandler`` do not use -/// it. Per-write cost does not decide it: the encoder stages small writes, so either sink sees about -/// one append per 256 bytes. The hand-out does. This sink is zero-copy into `ByteBuffer`s — its -/// regions are slices — where ``IMAPOutputBuffer`` copies its regions into fresh `ByteBuffer`s. Into a -/// `DispatchData` they are alike: each donates regions of at least the dispatch donation threshold -/// (512 B) and copies shorter ones. Both keep large payloads by -/// reference, so neither wins there. Measured on a stream of small responses into a `Channel`, this -/// sink allocates fewer bytes but is slower, and while earlier responses are still in flight it is -/// slower still and allocates more bytes (see below). So it ships as a caller's choice. -/// `Examples/PerformanceTester` has the numbers. -/// -/// ``IMAPOutputBuffer`` has one structural advantage: it can keep writing into a segment it has -/// already handed part of out, which this cannot. A `ByteBuffer` grows by reallocating, and writing into -/// storage that a handed-out slice still refers to would copy the whole buffer — so once bytes have been -/// handed out, this starts a fresh buffer instead. When the previous one has already been written to the -/// network, and its slice released, that is free; when it has not, it costs one allocation and still no -/// copy. -/// -/// ## Large payloads -/// -/// A payload appended as an ``IMAPBuffer`` — an `APPEND` message, a forwarded `FETCH` literal — is -/// kept by reference rather than copied once it is big enough to be worth a separate region, exactly -/// as ``IMAPOutputBuffer`` does. The chunk then has more than one region, and a caller that writes one -/// `ByteBuffer` per region lets NIO gather them into a single `writev` rather than coalescing them -/// itself. That is what makes forwarding a multi-megabyte literal free. -public struct ByteBufferOutput: EncoderOutputBuffer, Sendable { - /// One entry in the pending list. - /// - /// Only regions that have been *closed* are held as values; the run of bytes currently being - /// written is described by ``openRegionStart`` and the buffer's writer index instead, so that the - /// common case — a message of nothing but written bytes — needs no list at all. - private enum Region: Sendable { - /// A range of ``buffer``. - case owned(Range) - /// A region belonging to somebody else, kept by reference rather than copied. - case foreign(IMAPBuffer) - - var count: Int { - switch self { - case .owned(let range): return range.count - case .foreign(let buffer): return buffer.count - } - } - - /// Splits into the first `k` bytes and the rest, by range arithmetic alone. - func split(at k: Int) -> (Region, Region) { - switch self { - case .owned(let range): - let middle = range.lowerBound + k - return (.owned(range.lowerBound..= IMAPBuffer.copyThreshold else { - region.withUnsafeBytes { self.append($0) } - return - } - closeOpenRegion() - closed.append(.foreign(region)) - pending += region.count - } - - /// Removes the first `byteCount` pending bytes and returns them, in order. - /// - /// The returned regions are slices of the buffer they were written into, so this copies nothing. It - /// is also the point at which that buffer stops being written into — see ``startFreshBuffer()``. - /// - /// - Parameter byteCount: How many bytes to take. Must not exceed ``byteCount``. - /// - Returns: The bytes taken. - public mutating func takeFirst(_ byteCount: Int) -> IMAPBufferList { - precondition( - byteCount >= 0 && byteCount <= pending, - "cannot take \(byteCount) bytes from a ByteBufferOutput holding \(pending)" - ) - guard byteCount > 0 else { return IMAPBufferList() } - - let list: IMAPBufferList - if closed.isEmpty { - // The common case: everything pending is the one run of bytes being written, so the - // hand-out is a single region and needs neither the region list nor an intermediate array. - list = IMAPBufferList( - IMAPBuffer(IMAPByteStorage(buffer), range: openRegionStart..<(openRegionStart + byteCount)) - ) - openRegionStart += byteCount - } else if closed[0].count >= byteCount { - // The oldest region covers the request on its own, which is what a streamed literal looks - // like: one payload appended by reference, handed straight back out. Worth keeping off the - // general path, which allocates an array to gather regions into. - let head: Region - if closed[0].count == byteCount { - head = closed.removeFirst() - } else { - let (first, rest) = closed[0].split(at: byteCount) - closed[0] = rest - head = first - } - list = IMAPBufferList(makeBuffer(head)) - } else { - list = takeAcrossRegions(byteCount) - } - pending -= byteCount - handedOut = true - learn(usedCapacity: buffer.writerIndex) - if pending == 0, buffer.capacity > Self.maximumRetainedCapacity { - // Nothing is left to carry over, so a buffer that grew for one large message can go now - // rather than pinning megabytes until the next write. Costs nothing: the bytes just handed - // out keep the memory alive for exactly as long as they need it. - releaseBuffer() - } - return list - } - - /// Calls the given closure with the pending regions, in order. - /// - /// - Note: Cold path — equality, hashing and debug descriptions. This materialises an array, and - /// it briefly shares the buffer's storage with the regions it yields, so a write immediately - /// afterwards may copy the buffer once. Nothing on the encode path reads bytes back. - /// - /// - Parameter body: A closure that receives the pending regions. - /// - Returns: Whatever `body` returns. - public func withPendingRegions(_ body: (Span) -> R) -> R { - // `ContiguousArray`, not `Array`: `Array.span` checks for a bridged `NSArray` and copies the - // elements out if it finds one, which `ContiguousArray.span` never has to do. The macOS 26 floor - // makes either spelling legal now; this one is the cheaper. - var regions: ContiguousArray = [] - regions.reserveCapacity(closed.count + 1) - var storage: IMAPByteStorage? - for region in closed { - switch region { - case .owned(let range): - let owner = storage ?? IMAPByteStorage(buffer) - storage = owner - regions.append(IMAPBuffer(owner, range: range)) - case .foreign(let buffer): - regions.append(buffer) - } - } - // The run still being written is pending too, even though it is not in `closed`. - if buffer.writerIndex > openRegionStart { - let owner = storage ?? IMAPByteStorage(buffer) - regions.append(IMAPBuffer(owner, range: openRegionStart.. openRegionStart else { return } - closed.append(.owned(openRegionStart.. 0 else { - resetBuffer() - return - } - - var fresh = allocator.buffer(capacity: Swift.max(nextCapacity, ownedPending)) - let previous = buffer - previous.withUnsafeReadableBytes { bytes in - for index in closed.indices { - guard case .owned(let range) = closed[index] else { continue } - let start = fresh.writerIndex - fresh.writeBytes(UnsafeRawBufferPointer(rebasing: bytes[range])) - closed[index] = .owned(start.. Self.maximumRetainedCapacity { - releaseBuffer() - } else { - buffer.clear(minimumCapacity: nextCapacity) - } - } - - /// Lets go of the buffer's memory, so that the next write allocates a fresh one. - /// - /// Only for a buffer that grew far past what messages need. Whatever has been handed out of it keeps - /// it alive for as long as it needs it, so this frees nothing that is still in use. - private mutating func releaseBuffer() { - // Zero capacity is NIO's shared empty buffer, so this allocates nothing of its own. - buffer = allocator.buffer(capacity: 0) - openRegionStart = 0 - handedOut = false - } - - // MARK: - Handing out - - /// Turns one pending region into an ``IMAPBuffer``. - /// - /// An owned region gets a box holding the buffer it lives in: that is what keeps the bytes alive - /// after this sink has moved on to a fresh buffer, and the range is what pins the extent, so the - /// region can never see bytes written later. - private func makeBuffer(_ region: Region) -> IMAPBuffer { - switch region { - case .owned(let range): return IMAPBuffer(IMAPByteStorage(buffer), range: range) - case .foreign(let region): return region - } - } - - /// Takes `byteCount` bytes from the front of the pending regions. - /// - /// The path for a chunk that spans more than one region, which means a payload was appended by - /// reference or a previous hand-out left bytes behind. - private mutating func takeAcrossRegions(_ byteCount: Int) -> IMAPBufferList { - closeOpenRegion() - - var taken: [IMAPBuffer] = [] - var storage: IMAPByteStorage? - var remaining = byteCount - var consumed = 0 - while remaining > 0 { - let region = closed[consumed] - let head: Region - if region.count <= remaining { - head = region - remaining -= region.count - consumed += 1 - } else { - let (first, rest) = region.split(at: remaining) - head = first - closed[consumed] = rest - remaining = 0 - } - switch head { - case .owned(let range): - // One owner for every region taken out of the buffer, however many there are: the box - // is what the bytes are kept alive by, and they are all kept alive by the same buffer. - let owner = storage ?? IMAPByteStorage(buffer) - storage = owner - taken.append(IMAPBuffer(owner, range: range)) - case .foreign(let region): - taken.append(region) - } - } - closed.removeFirst(consumed) - return IMAPBufferList(taken) - } - - /// Records how big the last message was, so the next buffer starts big enough for it. - /// - /// Deliberately the *last* message rather than the largest one seen. A high-water mark is the right - /// answer for a buffer that is reused, because it is free to keep capacity it already has — but this - /// number is also what a buffer allocates with when it *cannot* be reused, which is what happens - /// whenever the last message is still on its way to the network. Sizing those allocations by the - /// high-water mark means one large response makes every small response after it allocate as if it - /// were large too. - private mutating func learn(usedCapacity: Int) { - nextCapacity = Swift.min( - Swift.max(usedCapacity, Self.defaultCapacity), - Self.maximumRetainedCapacity - ) - } -} - -// MARK: - Debugging - -extension ByteBufferOutput { - /// How many regions are pending, including the run still being written. - /// - /// This exposes what the public API deliberately hides — how the pending bytes are split up — which - /// is the only way to check that consecutive writes stay one region, that a payload appended by - /// reference becomes its own, and that a hand-out leaves the remainder where the next write can - /// extend it. Tests use these three; nothing else should. - internal var pendingRegionCount: Int { - closed.count + (buffer.writerIndex > openRegionStart ? 1 : 0) - } - - /// Whether the pending region at `index` is one appended by reference rather than written. - internal func pendingRegionIsForeign(_ index: Int) -> Bool { - guard index < closed.count else { return false } - if case .foreign = closed[index] { return true } - return false - } - - /// The address of the buffer being written into, and its capacity. - /// - /// Address identity is how "the buffer was reused rather than reallocated" is observable at all. - /// Deliberately a non-mutating read: asking for a mutable pointer would copy the storage when it is - /// shared, which is the very thing being observed. - internal var writeBufferIdentity: (address: UInt, capacity: Int) { - (buffer.withUnsafeReadableBytes { UInt(bitPattern: $0.baseAddress) }, buffer.capacity) - } -} - -extension ByteBufferOutput: CustomDebugStringConvertible { - /// A description showing what is pending. - public var debugDescription: String { - let regions = pendingRegionCount - return "ByteBufferOutput(\(pending) bytes pending in \(regions) region\(regions == 1 ? "" : "s"))" - } -} diff --git a/Sources/NIOIMAPCore/Bytes/ByteRegion.swift b/Sources/NIOIMAPCore/Bytes/ByteRegion.swift index afcde6a9..0bfb464b 100644 --- a/Sources/NIOIMAPCore/Bytes/ByteRegion.swift +++ b/Sources/NIOIMAPCore/Bytes/ByteRegion.swift @@ -58,7 +58,7 @@ extension ContiguousArray: ByteRegion where Element == UInt8 {} /// address, and those bytes stay valid and unchanged for as long as any copy of the value is alive. /// In return, the library keeps a copy of the value where it would otherwise copy the bytes: /// ``IMAPInputBuffer`` keeps a large region by reference, and ``IMAPBufferList/makeDispatchData()`` -/// donates a region of at least the dispatch donation threshold (512 B) to the `DispatchData`. +/// donates a large enough region to the `DispatchData`. /// /// This is the extension point for a byte-buffer type of your own; `NIOIMAP` conforms `ByteBuffer` /// with nothing more. A region that does not conform is copied instead, which is always correct. diff --git a/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift b/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift index 2a38361d..d060c002 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift @@ -35,7 +35,7 @@ import Android /// - **Retained.** The bytes belong to an ``IMAPByteStorage`` — a network read, an encoder output /// segment, a memory-mapped file — and this value holds a strong reference to it plus a range. /// -/// The two are indistinguishable through the API: ``==`` and ``hash(into:)`` compare bytes, so a +/// The two are indistinguishable through the API: ``==(_:_:)`` and ``hash(into:)`` compare bytes, so a /// copied buffer and a retained buffer over the same bytes are equal and hash equally. /// /// - Note: `IMAPBuffer` stores an *object and a range*, never a pointer. Nothing here can dangle, @@ -55,9 +55,6 @@ import Android /// /// ``copiedBytes()`` is the convenient path, and it allocates and copies on **every** call. public struct IMAPBuffer: Sendable { - // `copiedBytes()` is a method rather than a property to say that it copies: on a value that may hold - // a multi-megabyte literal, a property that copies reads as free. - // // `IMAPBuffer` is deliberately not a `Collection`. Subscripting a byte at a time through a scoped // accessor is a performance trap that looks free. @@ -174,6 +171,8 @@ public struct IMAPBuffer: Sendable { /// ``withUnsafeBytes(_:)`` where the bytes do not need to outlive the call. /// - Returns: The bytes. public func copiedBytes() -> [UInt8] { + // A method rather than a property to say that it copies: on a value that may hold a + // multi-megabyte literal, a property that copies reads as free. switch storage { case .copied(let bytes, let range) where range == bytes.indices: return bytes diff --git a/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift b/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift index 82417249..46b7ec0a 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift @@ -18,6 +18,10 @@ /// multi-megabyte message payload can be handed to a caller — or written back out again — as a /// reference to somebody else's memory rather than as a copy. /// +/// - Complexity: Wrapping a value of three words or fewer — a `ByteBuffer` is 24 bytes of stride, +/// `Data` is 16 — costs **one** allocation in total, because the value fits in the existential's +/// inline storage. +/// /// ## Immutability requirement /// /// - Important: The wrapped region's bytes, and their count, must never change for as long as this @@ -36,9 +40,7 @@ /// its word, so a false conformance does leave one dangling. public final class IMAPByteStorage: Sendable { // A `final class` on purpose: it gives the wrapped region exactly one heap box with a reference - // count, which is the whole mechanism. Wrapping a value of three words or fewer — a `ByteBuffer` - // is 24 bytes of stride, `Data` is 16 — costs **one** allocation in total, because the value fits - // in the existential's inline storage. + // count, which is the whole mechanism. private let region: any ByteRegion & Sendable diff --git a/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift b/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift index 85bbde1e..dd1ef162 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift @@ -120,8 +120,8 @@ public struct IMAPInputBuffer: Sendable { /// ``StableAddressByteRegion``, or an ``IMAPBuffer`` over one — is not copied: it is retained as-is /// and parsed where it lies, for one small object per call. Any other region that large — a `Data`, /// say — is copied once into an exact-size array, which is retained instead. A smaller one is copied - /// into the tail, or into a fresh ``minimumTailCapacity`` tail if it does not fit, and is not - /// retained. + /// into the tail, or into a fresh tail of ``IMAPBuffer/copyThreshold`` bytes if it does not fit, + /// and is not retained. /// /// Appending an empty region does nothing. ///