//===----------------------------------------------------------------------===// // // 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 NIOIMAP /// Encoded output written straight into a `ByteBuffer`: the benchmarks' second sink, measured against /// the library's `IMAPOutputBuffer`. /// /// Not shipped. It used to live in `NIOIMAP` as a caller's choice of sink and was removed from the /// library; it is kept here, built only on public API, so the `bytebuffer-sink` cases still measure /// the trade it makes. /// /// 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. /// /// ## Against `IMAPOutputBuffer` /// /// Per-write cost does not decide between them: 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 large regions and copies short ones (see /// `IMAPBufferList.makeDispatchData()`). Both keep large payloads by reference, so neither wins there. /// /// `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. 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: the next write reuses it only if /// nothing is left pending, the bytes handed out are gone and it is at most 64 KiB, and starts a /// fresh one otherwise. /// /// - Parameter byteCount: How many bytes to take. Must not exceed ``byteCount``. /// - Returns: The bytes taken. 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. 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. var pendingRegionCount: Int { closed.count + (buffer.writerIndex > openRegionStart ? 1 : 0) } } extension ByteBufferOutput: CustomDebugStringConvertible { /// A description showing what is pending. var debugDescription: String { let regions = pendingRegionCount return "ByteBufferOutput(\(pending) bytes pending in \(regions) region\(regions == 1 ? "" : "s"))" } }