diff --git a/Examples/CLI/Sources/CLILib/Handlers/Outbound/CommandRoundtripHandler.swift b/Examples/CLI/Sources/CLILib/Handlers/Outbound/CommandRoundtripHandler.swift index 81373a98..da23a5ed 100644 --- a/Examples/CLI/Sources/CLILib/Handlers/Outbound/CommandRoundtripHandler.swift +++ b/Examples/CLI/Sources/CLILib/Handlers/Outbound/CommandRoundtripHandler.swift @@ -15,7 +15,7 @@ import Logging import NIO import NIOIMAP -@_spi(NIOIMAPInternal) import NIOIMAPCore +import NIOIMAPCore import NIOSSL enum CommandRoundtripError: Error { @@ -46,12 +46,17 @@ public class CommandRoundtripHandler: ChannelOutboundHandler { } var encodeBuffer = CommandEncodeBuffer( - buffer: context.channel.allocator.buffer(capacity: originalBuffer.readableBytes), capabilities: self.capabilities, loggingMode: false ) encodeBuffer.writeCommandStream(command) - var roundtripBuffer = encodeBuffer.buffer.nextChunk().bytes + // Compare all chunks: a synchronizing literal ends a chunk mid-command. Ignores + // `nextStep`, since only the original bytes are sent. + var roundtripBytes: [UInt8] = [] + while let chunk = encodeBuffer.nextChunk() { + roundtripBytes.append(contentsOf: chunk.bytes.copiedBytes()) + } + var roundtripBuffer = ByteBuffer(bytes: roundtripBytes) if originalBuffer != roundtripBuffer { self.logger.warning("Input command vs roundtrip output is different") diff --git a/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift b/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift index 8bc8227c..3596a1a8 100644 --- a/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift +++ b/Sources/NIOIMAP/Bytes/ByteBufferOutput.swift @@ -17,11 +17,10 @@ import NIOIMAPCore /// Encoded output written straight into a `ByteBuffer`. /// -/// This is the ``EncoderOutputBuffer`` to consider when the bytes are going to a NIO `Channel` and the -/// traffic is dominated by large payloads. 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. +/// 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` /// @@ -32,13 +31,17 @@ import NIOIMAPCore /// ``` /// /// It is deliberately *not* the default, and ``IMAPClientHandler`` and ``IMAPServerHandler`` do not use -/// it: ``IMAPOutputBuffer`` is faster wherever bytes are written rather than referred -/// to, because every `ByteBuffer` write pays a uniqueness check and a non-inlined capacity call where a -/// segment write goes through cached trivial fields — and a `BODYSTRUCTURE` response is hundreds of -/// small writes. This sink allocates fewer bytes and wins on payload-heavy traffic, so it ships as -/// a caller's choice. `Examples/PerformanceTester` has the numbers. +/// 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 +/// `IMAPBuffer.dispatchDonationThreshold` bytes 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`` also has one structural advantage: it can keep writing into a segment it has +/// ``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 diff --git a/Sources/NIOIMAP/Coders/ClientStateMachine.swift b/Sources/NIOIMAP/Coders/ClientStateMachine.swift index f0917355..bd76bd36 100644 --- a/Sources/NIOIMAP/Coders/ClientStateMachine.swift +++ b/Sources/NIOIMAP/Coders/ClientStateMachine.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIO -@_spi(NIOIMAPInternal) import NIOIMAPCore +import NIOIMAPCore public struct InvalidClientState: Error { public init() {} @@ -110,7 +110,7 @@ extension InvalidCommandForState: CustomStringConvertible, CustomDebugStringConv } struct OutgoingChunk: Equatable { - var bytes: ByteBuffer + var bytes: IMAPBufferList var promise: EventLoopPromise? var shouldSucceedPromise: Bool @@ -157,30 +157,52 @@ struct ClientStateMachine { private var buffer: CommandEncodeBuffer private var promise: EventLoopPromise? + /// The chunk after the one handed out last, taken from `buffer` one early to tell whether that + /// one was the command's last; see ``isDrained``. + private var upcoming: CommandEncodeBuffer.Chunk? + init(buffer: CommandEncodeBuffer, promise: EventLoopPromise?) { self.buffer = buffer self.promise = promise + self.upcoming = self.buffer.nextChunk() } mutating func drop() -> EventLoopPromise? { defer { self.promise = nil - self.buffer = .init(buffer: ByteBuffer(), capabilities: .init(), loggingMode: false) + self.buffer = .init(capabilities: .init(), loggingMode: false) + self.upcoming = nil } return self.promise } - mutating func nextChunk() -> OutgoingChunk { - let chunk = self.buffer.buffer.nextChunk() - let promise = self.promise - return .init(bytes: chunk.bytes, promise: promise, shouldSucceedPromise: !chunk.waitForContinuation) + /// Whether every chunk has been handed out. A chunk that awaits `+` may still be the last, + /// e.g. APPEND's `{5}\r\n` before the message bytes. + var isDrained: Bool { self.upcoming == nil } + + /// The command's next chunk, and what the client does after sending it. Writing a chunk that + /// proceeds completes the promise. + /// + /// A command without bytes, e.g. APPEND's `.endMessage`, gives one empty chunk, so that its + /// promise completes too. + mutating func nextChunk() -> (chunk: OutgoingChunk, nextStep: CommandEncodeBuffer.NextStep) { + let current = self.upcoming + self.upcoming = self.buffer.nextChunk() + let nextStep = current?.nextStep ?? .proceed + let chunk = OutgoingChunk( + bytes: current?.bytes ?? IMAPBufferList(), + promise: self.promise, + shouldSucceedPromise: nextStep == .proceed + ) + return (chunk, nextStep) } static func == ( lhs: ClientStateMachine.ActiveEncodeContext, rhs: ClientStateMachine.ActiveEncodeContext ) -> Bool { - lhs.buffer == rhs.buffer && lhs.promise?.futureResult == rhs.promise?.futureResult + lhs.buffer == rhs.buffer && lhs.upcoming == rhs.upcoming + && lhs.promise?.futureResult == rhs.promise?.futureResult } } @@ -211,7 +233,8 @@ struct ClientStateMachine { case appending(ClientStateMachine.Append) /// An append part holds a synchronizing literal before its end, e.g. the mailbox in - /// `A1 APPEND {2}\r\nå`. Waiting for `+` before sending the rest of the part. + /// `A1 APPEND {2}\r\nå`. Waiting for `+` before sending the rest of the part. Also a + /// zero-length literal that ends the part, e.g. an empty mailbox as `{0}\r\n`. case appendingLiteral(ClientStateMachine.Append, ActiveEncodeContext) /// We've sent a command that requires a continuation request @@ -229,7 +252,12 @@ struct ClientStateMachine { var state: State = .expectingNormalResponse private var activeCommandTags: Set = [] - private var allocator: ByteBufferAllocator! + /// The channel's allocator. + /// + /// Nothing reads it while commands are encoded into an `IMAPOutputBuffer`, which allocates its own + /// segments. It is kept because the other shipped sink — `ByteBufferOutput` — needs one, and which + /// of the two belongs here is a question the benchmarks answer differently for different traffic. + private var allocator = ByteBufferAllocator() // We mark where we should write up to at the next opportunity // using the `flush` method called from the channel handler. @@ -478,13 +506,12 @@ extension ClientStateMachine { guard case .appendingLiteral(let appendingStateMachine, var context) = self.state else { preconditionFailure("Invalid state: \(self.state)") } - let chunk = context.nextChunk() - guard chunk.shouldSucceedPromise else { + let (next, nextStep) = context.nextChunk() + let chunk = self.handOutAppendChunk(next, nextStep, context: context, append: appendingStateMachine) + guard case .appending = self.state else { // Another literal in the same part. - self.state = .appendingLiteral(appendingStateMachine, context) return .sendChunks([chunk]) } - self.state = .appending(appendingStateMachine) // Promises dequeued before a throw are never completed; see #858. return try .sendChunks([chunk] + self.extractSendableChunks().chunks) } @@ -580,20 +607,20 @@ extension ClientStateMachine { // instead of failing the connection; see #858. self.guardAgainstMultipleRunningCommands() self.state = .idle(Idle(tag: command.tag)) - return .init(chunks: [context.nextChunk()], nextContext: nil) + return .init(chunks: [context.nextChunk().chunk], nextContext: nil) case .authenticate: self.guardAgainstMultipleRunningCommands() self.state = .authenticating(Authentication()) - return .init(chunks: [context.nextChunk()], nextContext: nil) + return .init(chunks: [context.nextChunk().chunk], nextContext: nil) default: - let chunk = context.nextChunk() + let chunk = context.nextChunk().chunk // if we're meant to succeed the promise then there can't be any next context guard chunk.shouldSucceedPromise else { self.state = .expectingLiteralContinuationRequest(context) return .init(chunks: [chunk], nextContext: context) } - precondition(context.nextChunk().bytes.readableBytes == 0) + assert(context.isDrained) self.state = .expectingNormalResponse return .init(chunks: [chunk], nextContext: nil) } @@ -611,13 +638,43 @@ extension ClientStateMachine { } // no other commands can be running when we start appending - let append = Append(tag: tag) let buffer = self.makeEncodeBuffer(.append(command)) var context = ActiveEncodeContext(buffer: buffer, promise: promise) - let chunk = context.nextChunk() - // A mailbox sent as a synchronizing literal: the rest of the part follows `+`. - self.state = chunk.shouldSucceedPromise ? .appending(append) : .appendingLiteral(append, context) - return .init(chunks: [chunk], nextContext: nil) + let (chunk, nextStep) = context.nextChunk() + return .init( + chunks: [self.handOutAppendChunk(chunk, nextStep, context: context, append: Append(tag: tag))], + nextContext: nil + ) + } + + /// Moves to the state that follows `chunk`, just taken from an APPEND part's `context`, and + /// returns the chunk to write. + private mutating func handOutAppendChunk( + _ chunk: OutgoingChunk, + _ nextStep: CommandEncodeBuffer.NextStep, + context: ActiveEncodeContext, + append: Append + ) -> OutgoingChunk { + switch nextStep { + case .proceed: + self.state = .appending(append) + return chunk + case .awaitContinuationRequest: + guard context.isDrained, append.isWaitingForContinuationRequest else { + // A literal before the part's end, e.g. the mailbox in `A1 APPEND {2}\r\nå`: the rest + // of the part follows `+`. Or one ending the part that `append` doesn't expect, e.g. an + // empty mailbox as `{0}\r\n`: the next part still waits for `+`, and the empty chunk + // after it completes the promise. + self.state = .appendingLiteral(append, context) + return chunk + } + // The part ends in the message's or CATENATE data's literal header (`beginMessage`, + // `catenateData(.begin)`): it is fully sent, and `append` waits for that `+`. + self.state = .appending(append) + var sent = chunk + sent.shouldSucceedPromise = true + return sent + } } /// Iterate through the current command queue until we reached the marked position @@ -631,7 +688,7 @@ extension ClientStateMachine { private mutating func extractSendableChunks(currentContext: ActiveEncodeContext? = nil) throws -> SendableChunks { var results: [OutgoingChunk] = [] if var currentContext = currentContext { - let chunk = currentContext.nextChunk() + let chunk = currentContext.nextChunk().chunk guard chunk.shouldSucceedPromise else { self.state = .expectingLiteralContinuationRequest(currentContext) return .init(chunks: [chunk], nextContext: currentContext) @@ -655,10 +712,10 @@ extension ClientStateMachine { precondition(self.activeCommandTags.count == 1) } + // Default sink, `IMAPOutputBuffer`, on purpose: a sink handing the channel slices of one + // `ByteBuffer` rather than copies measured no faster on commands. private func makeEncodeBuffer(_ command: CommandStreamPart? = nil) -> CommandEncodeBuffer { - let byteBuffer = self.allocator.buffer(capacity: 128) var encodeBuffer = CommandEncodeBuffer( - buffer: byteBuffer, options: self.encodingOptions.encodingOptions, loggingMode: false ) @@ -754,13 +811,10 @@ extension ClientStateMachine { idleStateMachine.sendCommand(command) self.state = .expectingNormalResponse - var encodeBuffer = self.makeEncodeBuffer(command) - let chunk = encodeBuffer.buffer.nextChunk() - precondition(!chunk.waitForContinuation) - return .init( - chunks: [.init(bytes: chunk.bytes, promise: promise, shouldSucceedPromise: true)], - nextContext: nil - ) + var context = ActiveEncodeContext(buffer: self.makeEncodeBuffer(command), promise: promise) + let (chunk, nextStep) = context.nextChunk() + precondition(chunk.shouldSucceedPromise && nextStep == .proceed) + return .init(chunks: [chunk], nextContext: nil) } /// When authenticating we need to first defer to the authentication state machine to make sure @@ -779,13 +833,10 @@ extension ClientStateMachine { authenticatingStateMachine.sendCommand(command) self.state = .authenticating(authenticatingStateMachine) - var encodeBuffer = self.makeEncodeBuffer(.continuationResponse(data)) - let chunk = encodeBuffer.buffer.nextChunk() - precondition(!chunk.waitForContinuation) - return .init( - chunks: [.init(bytes: chunk.bytes, promise: promise, shouldSucceedPromise: true)], - nextContext: nil - ) + var context = ActiveEncodeContext(buffer: self.makeEncodeBuffer(.continuationResponse(data)), promise: promise) + let (chunk, nextStep) = context.nextChunk() + precondition(chunk.shouldSucceedPromise && nextStep == .proceed) + return .init(chunks: [chunk], nextContext: nil) } /// When appending we need to first defer to the appending state machine to see if we can actually @@ -817,7 +868,6 @@ extension ClientStateMachine { encodingOptions.useNonSynchronizingLiteralMinus = false var encodeBuffer = CommandEncodeBuffer( - buffer: ByteBuffer(), options: encodingOptions, encodedAtLeastOneCatenateElement: appendingStateMachine.hasCatenatedAtLeastOneObject, loggingMode: false @@ -826,16 +876,10 @@ extension ClientStateMachine { appendingStateMachine.sendCommand(.append(command)) var context = ActiveEncodeContext(buffer: encodeBuffer, promise: promise) - let chunk = context.nextChunk() - - // A literal before the part's end, e.g. `URL {90}\r\n` and then the URL: send the rest - // after `+`. A part that ends in its own literal header (`beginMessage`, - // `catenateData(.begin)`) is fully sent; `appendingStateMachine` waits for that `+`. - guard chunk.shouldSucceedPromise else { - self.state = .appendingLiteral(appendingStateMachine, context) - return .init(chunks: [chunk], nextContext: nil) - } - self.state = .appending(appendingStateMachine) - return .init(chunks: [chunk], nextContext: nil) + let (chunk, nextStep) = context.nextChunk() + return .init( + chunks: [self.handOutAppendChunk(chunk, nextStep, context: context, append: appendingStateMachine)], + nextContext: nil + ) } } diff --git a/Sources/NIOIMAP/Coders/CommandEncoder.swift b/Sources/NIOIMAP/Coders/CommandEncoder.swift deleted file mode 100644 index e9fb9897..00000000 --- a/Sources/NIOIMAP/Coders/CommandEncoder.swift +++ /dev/null @@ -1,47 +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 -@_spi(NIOIMAPInternal) import NIOIMAPCore - -enum CommandEncodingError: Error, Equatable { - case missingBytes -} - -class CommandEncoder: MessageToByteEncoder { - typealias OutboundIn = CommandStreamPart - - enum Mode: Hashable { - case normal - case bytes(remaining: Int) - } - - var loggingMode: Bool - var capabilities: [Capability] = [] - private var mode = Mode.normal - - init(loggingMode: Bool) { - self.loggingMode = loggingMode - } - - func encode(data: CommandStreamPart, out: inout ByteBuffer) { - var encodeBuffer = CommandEncodeBuffer( - buffer: out, - capabilities: self.capabilities, - loggingMode: self.loggingMode - ) - encodeBuffer.writeCommandStream(data) - out = encodeBuffer.buffer.nextChunk().bytes - } -} diff --git a/Sources/NIOIMAP/Coders/IMAPClientHandler.swift b/Sources/NIOIMAP/Coders/IMAPClientHandler.swift index e34db7c7..4367abc9 100644 --- a/Sources/NIOIMAP/Coders/IMAPClientHandler.swift +++ b/Sources/NIOIMAP/Coders/IMAPClientHandler.swift @@ -159,10 +159,47 @@ public final class IMAPClientHandler: ChannelDuplexHandler { } private func writeChunk(_ chunk: OutgoingChunk, context: ChannelHandlerContext) { - let outbound = self.wrapOutboundOut(chunk.bytes) - if chunk.shouldSucceedPromise { + // A chunk usually becomes one write. It becomes several when it carries a payload the encoder + // kept by reference — an `APPEND` message — because writing that payload on its own is what + // keeps it from being copied, and NIO gathers the writes into one `writev` anyway. See + // `IMAPBufferList.makeOutboundBuffers()` for why this is not simply one write per region. + // + // A chunk with no bytes still has to reach the channel: an empty write is how the end of an + // `APPEND` message is signalled, and the promise has to be resolved either way. + switch chunk.bytes.regionCount { + case 0: + self.write(ByteBuffer(), of: chunk, position: .last, context: context) + case 1: + self.write(chunk.bytes.regions[0].byteBuffer, of: chunk, position: .last, context: context) + default: + let buffers = chunk.bytes.makeOutboundBuffers() + for (index, buffer) in buffers.enumerated() { + let position: BufferPosition = index == buffers.count - 1 ? .last : .notLast + self.write(buffer, of: chunk, position: position, context: context) + } + } + } + + /// Where a buffer sits among the writes of one chunk. + private enum BufferPosition { + case notLast + /// The chunk's final write; it may resolve the chunk's promise. + case last + } + + /// Writes one of a chunk's buffers, resolving the chunk's promise on the last of them. + private func write( + _ bytes: ByteBuffer, + of chunk: OutgoingChunk, + position: BufferPosition, + context: ChannelHandlerContext + ) { + let outbound = self.wrapOutboundOut(bytes) + if position == .last, chunk.shouldSucceedPromise { context.write(outbound, promise: chunk.promise) } else { + // Not the last buffer, or a chunk that will only be finished by a later one: the promise + // must not succeed yet, but a failure anywhere has to reach it. context.write(outbound).cascadeFailure(to: chunk.promise) } } diff --git a/Sources/NIOIMAP/Coders/IMAPServerHandler.swift b/Sources/NIOIMAP/Coders/IMAPServerHandler.swift index e216d76a..edf0d521 100644 --- a/Sources/NIOIMAP/Coders/IMAPServerHandler.swift +++ b/Sources/NIOIMAP/Coders/IMAPServerHandler.swift @@ -44,19 +44,25 @@ public final class IMAPServerHandler: ChannelDuplexHandler { } set { self._continuationRequest = newValue - let buffer = ByteBufferAllocator().buffer(capacity: 16) - var encodeBuffer = ResponseEncodeBuffer(buffer: buffer, capabilities: self.capabilities, loggingMode: false) - encodeBuffer.writeContinuationRequest(newValue) - self.continuationRequestBytes = encodeBuffer.readBytes() + self.continuationRequestBytes = Self.encode(newValue, capabilities: self.capabilities) } } private let decoder: NIOSingleStepByteToMessageProcessor private var numberOfOutstandingContinuationRequests = 0 + + /// The encoded continuation request, written once per outstanding request. + /// + /// Coalesced into one `ByteBuffer` rather than kept as regions, because it is a handful of bytes + /// that gets written many times over the life of the connection. private var continuationRequestBytes: ByteBuffer + /// The buffer every response is encoded into, kept for the lifetime of the connection. + /// + /// Default sink, `IMAPOutputBuffer`, on purpose: a sink handing the channel slices of one + /// `ByteBuffer` rather than copies allocates a fresh `ByteBuffer` per chunk while earlier ones are + /// still in flight, and is slower on a stream of small responses. private var responseEncodeBuffer = ResponseEncodeBuffer( - buffer: ByteBuffer(string: ""), options: .init(), loggingMode: false ) @@ -72,10 +78,14 @@ public final class IMAPServerHandler: ChannelDuplexHandler { maximumBufferSize: IMAPDefaults.lineLengthLimit ) self._continuationRequest = continuationRequest - let buffer = ByteBufferAllocator().buffer(capacity: 16) - var encodeBuffer = ResponseEncodeBuffer(buffer: buffer, capabilities: self.capabilities, loggingMode: false) - encodeBuffer.writeContinuationRequest(continuationRequest) - self.continuationRequestBytes = encodeBuffer.readBytes() + self.continuationRequestBytes = Self.encode(continuationRequest, capabilities: self.capabilities) + } + + /// Encodes one continuation request into a single `ByteBuffer`. + private static func encode(_ request: ContinuationRequest, capabilities: [Capability]) -> ByteBuffer { + var encodeBuffer = ResponseEncodeBuffer(capabilities: capabilities, loggingMode: false) + encodeBuffer.writeContinuationRequest(request) + return encodeBuffer.readBytes().makeByteBuffer() } public func read(context: ChannelHandlerContext) { @@ -116,7 +126,26 @@ public final class IMAPServerHandler: ChannelDuplexHandler { public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { let response = self.unwrapOutboundIn(data) self.responseEncodeBuffer.writeResponse(response) - context.write(self.wrapOutboundOut(self.responseEncodeBuffer.readBytes()), promise: promise) + let bytes = self.responseEncodeBuffer.readBytes() + // Usually one write. Several when the response carries a payload the encoder kept by reference — + // a streamed literal — so that the payload reaches the network without being copied. See + // `IMAPBufferList.makeOutboundBuffers()`. + switch bytes.regionCount { + case 0: + context.write(self.wrapOutboundOut(ByteBuffer()), promise: promise) + case 1: + context.write(self.wrapOutboundOut(bytes.regions[0].byteBuffer), promise: promise) + default: + let buffers = bytes.makeOutboundBuffers() + for (index, buffer) in buffers.enumerated() { + let outbound = self.wrapOutboundOut(buffer) + if index == buffers.count - 1 { + context.write(outbound, promise: promise) + } else { + context.write(outbound).cascadeFailure(to: promise) + } + } + } } } diff --git a/Sources/NIOIMAPCore/Bytes/EncoderOutputBuffer.swift b/Sources/NIOIMAPCore/Bytes/EncoderOutputBuffer.swift index f33941f1..8d4cd8da 100644 --- a/Sources/NIOIMAPCore/Bytes/EncoderOutputBuffer.swift +++ b/Sources/NIOIMAPCore/Bytes/EncoderOutputBuffer.swift @@ -30,18 +30,13 @@ /// ```swift /// // the default: segments the library allocates /// var encoder = CommandEncodeBuffer(options: options, loggingMode: false) -/// // or, for payload-heavy traffic headed to a NIO Channel -/// var encoder = CommandEncodeBuffer(sink: ByteBufferOutput(), options: options, loggingMode: false) +/// // or a sink of your own +/// var encoder = CommandEncodeBuffer(sink: MyOutput(), options: options, loggingMode: false) /// ``` /// /// - ``IMAPOutputBuffer`` is the shipped conformer, the default argument, and what `NIOIMAP`'s /// handlers use. Reach for it unless you have measured a reason not to: it never moves a byte it has /// already written, which is what makes handing out a chunk while encoding continues free. -/// - `ByteBufferOutput`, in `NIOIMAP`, writes straight into a `ByteBuffer` and hands out slices of it, -/// so nothing is copied between the encoder and a `Channel`. It allocates less and wins on traffic -/// dominated by large payloads; it loses on traffic made of many small writes, because a -/// `ByteBuffer` write costs more per call than a segment write. It is a caller's choice, not the -/// default. /// - Conform yourself when the bytes have to land in storage this package cannot know about — a file, /// shared memory, a ring buffer. The six members below are the whole obligation, plus value /// semantics: copying an encoder copies its sink, so a class-backed sink would leave both copies @@ -50,6 +45,12 @@ /// This mirrors the read side, where ``ParserInputBuffer`` is the seam and ``IMAPInputBuffer`` is the /// conformer to reach for. /// +/// ## Batched appends +/// +/// The encoder stages small writes and appends them together, so a conformer sees fewer, larger +/// appends than there were writes, and ``byteCount`` and ``withPendingRegions(_:)`` may lag what has +/// been encoded. Bytes always arrive in order; staged ones arrive before the next ``takeFirst(_:)``. +/// /// ## What is deliberately not here /// /// - **Stop points and chunking.** They belong to the encoder, which expresses them as offsets diff --git a/Sources/NIOIMAPCore/Bytes/IMAPBufferList.swift b/Sources/NIOIMAPCore/Bytes/IMAPBufferList.swift index 4889ea46..72eea749 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPBufferList.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPBufferList.swift @@ -173,6 +173,49 @@ extension IMAPBufferList { } } +// MARK: - The region cap + +extension IMAPBufferList { + /// The most regions any one chunk is handed out as. + /// + /// Realistic chunks have one to three regions, and nothing in the library can produce more than a + /// handful: a chunk of copied bytes is a protocol line, bounded well below one output segment, and + /// at most one payload is appended by reference per command or response. + /// + /// The cap is insurance against a direct user of the public encode API, which accumulates until + /// drained — a caller that writes a thousand payloads before asking for a chunk would otherwise + /// get a thousand-region chunk, and 1024 is the most vectors a single `writev` can take. + /// + /// The encoder applies it to every chunk, whatever the sink handed it, so no + /// ``EncoderOutputBuffer`` has to. + internal static let maximumRegionsPerChunk = 64 + + /// Creates a list of at most ``maximumRegionsPerChunk`` regions, coalescing the tail if there are + /// more. + /// + /// The leading regions are kept as they are — those are the ones most likely to be large payloads + /// worth not copying — and everything past the cap is copied into one region. Nothing is ever + /// dropped, so this only ever trades zero-copy for a bounded region count. + /// + /// - Parameter regions: The regions, in order. + internal init(cappingRegionCount regions: some Collection) { + guard regions.count > Self.maximumRegionsPerChunk else { + self.init(regions) + return + } + + let keeping = Self.maximumRegionsPerChunk - 1 + self.init(regions.prefix(keeping)) + let tail = regions.dropFirst(keeping) + var coalesced: [UInt8] = [] + coalesced.reserveCapacity(tail.reduce(0) { $0 + $1.count }) + for region in tail { + region.withUnsafeBytes { coalesced.append(contentsOf: $0) } + } + self.append(IMAPBuffer(coalesced)) + } +} + // MARK: - Equatable & Hashable extension IMAPBufferList: Hashable { diff --git a/Sources/NIOIMAPCore/Bytes/IMAPOutputBuffer.swift b/Sources/NIOIMAPCore/Bytes/IMAPOutputBuffer.swift index 9afbac19..95999f02 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPOutputBuffer.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPOutputBuffer.swift @@ -36,9 +36,7 @@ import DequeModule /// var encoder = CommandEncodeBuffer(options: options, loggingMode: false) // sink: IMAPOutputBuffer() /// ``` /// -/// The alternative is `NIOIMAP`'s `ByteBufferOutput`, which wins on traffic dominated by large -/// payloads and loses on traffic made of many small writes; see that type. -/// Callers whose bytes have to land in storage neither type describes — a file, shared +/// Callers whose bytes have to land in storage this type does not describe — a file, shared /// memory — conform to the protocol themselves rather than reaching for this. /// /// ## Getting the bytes out diff --git a/Sources/NIOIMAPCore/CommandEncodeBuffer.swift b/Sources/NIOIMAPCore/CommandEncodeBuffer.swift index 42d38732..0bde37a9 100644 --- a/Sources/NIOIMAPCore/CommandEncodeBuffer.swift +++ b/Sources/NIOIMAPCore/CommandEncodeBuffer.swift @@ -12,8 +12,6 @@ // //===----------------------------------------------------------------------===// -import struct NIO.ByteBuffer - /// Encodes IMAP client commands into wire format ready for transmission to an IMAP server. /// /// `CommandEncodeBuffer` is the primary interface for encoding commands from the client side. @@ -24,16 +22,29 @@ import struct NIO.ByteBuffer /// /// ```swift /// var buffer = CommandEncodeBuffer( -/// buffer: ByteBuffer(), /// options: CommandEncodingOptions(capabilities: [.literalPlus]), /// loggingMode: false /// ) -/// // Encode command data into buffer -/// // Retrieve chunks via buffer.buffer.nextChunk() +/// buffer.writeCommand(TaggedCommand(tag: "A1", command: .login(username: "user", password: "pass"))) +/// while let chunk = buffer.nextChunk() { +/// send(chunk.bytes) +/// if chunk.nextStep == .awaitContinuationRequest { +/// // Wait for the server's `+` before sending the next chunk. +/// } +/// } /// ``` /// +/// ## Where the bytes go +/// +/// This is the type a client creates; it owns an ``EncoderOutputBuffer``, the sink the encoded bytes +/// are appended to, chosen once with the `sink:` argument and never named again. Leaving it out gives +/// an ``IMAPOutputBuffer``, which is the right answer unless the bytes have to land somewhere +/// specific — see ``EncoderOutputBuffer`` for the choice. The bytes come back out as an +/// ``IMAPBufferList`` from ``nextChunk()``, which converts to a `DispatchData`, to `ByteBuffer`s, or to +/// one contiguous copy. +/// /// - SeeAlso: ``ResponseEncodeBuffer``, ``CommandEncodingOptions`` -public struct CommandEncodeBuffer: Hashable, Sendable { +public struct CommandEncodeBuffer: Hashable { /// The underlying buffer containing data to be written. /// /// Provides access to the raw ``EncodeBuffer`` for advanced operations, @@ -46,8 +57,8 @@ public struct CommandEncodeBuffer: Hashable, Sendable { /// Creates a new command encoding buffer with explicit options. /// /// - Parameters: - /// - buffer: The initial `ByteBuffer` to build upon. This buffer is copied, - /// not taken as inout. + /// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``, which + /// is the right choice unless the bytes have to land somewhere specific. /// - options: The ``CommandEncodingOptions`` controlling how literals, strings, /// and other protocol elements are encoded. /// - encodedAtLeastOneCatenateElement: Internal tracking for CATENATE operations. @@ -55,16 +66,23 @@ public struct CommandEncodeBuffer: Hashable, Sendable { /// - loggingMode: When `true`, binary data is replaced with placeholders like /// `[N bytes]` for safe logging. Defaults to `false`. public init( - buffer: ByteBuffer, + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), options: CommandEncodingOptions, encodedAtLeastOneCatenateElement: Bool = false, loggingMode: Bool ) { - self.buffer = .clientEncodeBuffer(buffer: buffer, options: options, loggingMode: loggingMode) + self.buffer = .clientEncodeBuffer(sink: sink, options: options, loggingMode: loggingMode) self.encodedAtLeastOneCatenateElement = encodedAtLeastOneCatenateElement } } +// MARK: - Sendability + +/// `CommandEncodeBuffer` is deliberately **not** `Sendable`, because the ``EncoderOutputBuffer`` it +/// writes into is not: see ``EncodeBuffer``. A chunk that has been handed out *is* `Sendable`. +@available(*, unavailable) +extension CommandEncodeBuffer: Sendable {} + extension CommandEncodeBuffer { /// The encoding options currently in use. /// @@ -93,8 +111,7 @@ extension CommandEncodeBuffer { /// server advertises the corresponding capabilities. /// /// - Parameters: - /// - buffer: The initial `ByteBuffer` to build upon. This buffer is copied, - /// not taken as inout. + /// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``. /// - capabilities: Server capabilities from a `CAPABILITY` response. These are /// used to configure encoding options automatically. /// - encodedAtLeastOneCatenateElement: Internal tracking for CATENATE operations. @@ -102,12 +119,12 @@ extension CommandEncodeBuffer { /// - loggingMode: When `true`, binary data is replaced with placeholders like /// `[N bytes]` for safe logging. Defaults to `false`. public init( - buffer: ByteBuffer, + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), capabilities: [Capability], encodedAtLeastOneCatenateElement: Bool = false, loggingMode: Bool ) { - self.buffer = .clientEncodeBuffer(buffer: buffer, capabilities: capabilities, loggingMode: loggingMode) + self.buffer = .clientEncodeBuffer(sink: sink, capabilities: capabilities, loggingMode: loggingMode) self.encodedAtLeastOneCatenateElement = encodedAtLeastOneCatenateElement } } @@ -117,14 +134,52 @@ extension CommandEncodeBuffer { /// /// Used for implementing ``CustomDebugStringConvertible`` conformance. static func makeDescription(loggingMode: Bool = false, _ closure: (inout CommandEncodeBuffer) -> Void) -> String { - var buffer = CommandEncodeBuffer(buffer: ByteBuffer(), options: .rfc3501, loggingMode: loggingMode) + var buffer = CommandEncodeBuffer(options: .rfc3501, loggingMode: loggingMode) closure(&buffer) - var chunk = buffer.buffer.nextChunk() - var result = String(bestEffortDecodingUTF8Bytes: chunk.bytes.readableBytesView) - while chunk.waitForContinuation { - chunk = buffer.buffer.nextChunk() - result += String(bestEffortDecodingUTF8Bytes: chunk.bytes.readableBytesView) + var bytes: [UInt8] = [] + while let chunk = buffer.nextChunk() { + bytes.append(contentsOf: chunk.bytes.copiedBytes()) + } + return String(bestEffortDecodingUTF8Bytes: bytes) + } +} + +// MARK: - Chunks + +extension CommandEncodeBuffer { + /// Encoded bytes to send as one write, and what the client must do before sending more. + public struct Chunk: Hashable, Sendable { + /// The bytes to send, in order. Large payloads are referenced, not copied. + public var bytes: IMAPBufferList + + /// What the client must do after sending `bytes` and before sending the next chunk. + public var nextStep: NextStep + } + + /// What a client does after sending a chunk. + public enum NextStep: Hashable, Sendable { + /// Send the next chunk right away. + case proceed + + /// The chunk ends with a synchronizing literal header (`{n}`). Wait for the server's + /// continuation request (`+`) before sending the next chunk. + case awaitContinuationRequest + } + + /// Removes and returns the next chunk of encoded bytes, ending at the first pending + /// synchronizing literal header; returns `nil` if nothing is pending. + /// + /// A chunk may end with the last byte written so far, e.g. after `.append(.beginMessage(…))`: + /// its `nextStep` is still ``NextStep/awaitContinuationRequest``, and the next chunk, once more + /// is written, follows the `+`. + public mutating func nextChunk() -> Chunk? { + guard self.buffer.hasChunks || self.buffer.pendingByteCount > 0 else { return nil } + let (chunk, end) = self.buffer.takeChunk(allowEmptyChunk: true) + switch end { + case .stopPoint: + return Chunk(bytes: chunk.bytes, nextStep: .awaitContinuationRequest) + case .pendingBytes: + return Chunk(bytes: chunk.bytes, nextStep: .proceed) } - return result } } diff --git a/Sources/NIOIMAPCore/EncodeBuffer+ByteBufferShim.swift b/Sources/NIOIMAPCore/EncodeBuffer+ByteBufferShim.swift new file mode 100644 index 00000000..e60d6a82 --- /dev/null +++ b/Sources/NIOIMAPCore/EncodeBuffer+ByteBufferShim.swift @@ -0,0 +1,24 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 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 struct NIO.ByteBuffer + +// Temporary: lets model types that still hold a `ByteBuffer` write through the sink. Removed in +// "Make payload cases IMAPBuffer". +extension EncodeBuffer { + @discardableResult + mutating func writeBuffer(_ buffer: inout ByteBuffer) -> Int { + self.writeBytes(buffer.readableBytesView) + } +} diff --git a/Sources/NIOIMAPCore/ByteBuffer+WriteLiteral.swift b/Sources/NIOIMAPCore/EncodeBuffer+WriteLiteral.swift similarity index 98% rename from Sources/NIOIMAPCore/ByteBuffer+WriteLiteral.swift rename to Sources/NIOIMAPCore/EncodeBuffer+WriteLiteral.swift index 5da791b8..1bfb7fb6 100644 --- a/Sources/NIOIMAPCore/ByteBuffer+WriteLiteral.swift +++ b/Sources/NIOIMAPCore/EncodeBuffer+WriteLiteral.swift @@ -39,9 +39,9 @@ extension EncodeBuffer { /// Writes an IMAP `string` type as defined by the grammar in RFC 3501. /// The function will decide to use either `quoted` or `literal` syntax based - /// upon what bytes `buffer` contains, and what encoding types are supported. + /// upon what `bytes` contains, and what encoding types are supported. /// - parameters: - /// - buffer: The buffer to write. + /// - bytes: The bytes to write. /// - returns: The number of bytes written. @discardableResult mutating func writeIMAPString(_ bytes: T) -> Int where T.Element == UInt8 { guard !self.loggingMode else { @@ -313,13 +313,15 @@ extension EncodeBuffer { self.writeString(suffix) } } + } // MARK: - Conditional writes // Free functions, not `EncodeBuffer` methods: a method call `self.write(if: …) { self.write… }` // borrows `self` while the closure mutates it, so the compiler copies the buffer and the first write -// inside the closure pays for copy-on-write. +// inside the closure pays for copy-on-write. On a segmented sink, that is a new segment per +// conditional write. /// Writes using a closure if the given `value` is non-`nil`. This allows for chaining together writes /// when attempting to perform composite writes and return the total number of bytes written. diff --git a/Sources/NIOIMAPCore/EncodeBuffer.swift b/Sources/NIOIMAPCore/EncodeBuffer.swift index bbfa7fc3..a6e70e1f 100644 --- a/Sources/NIOIMAPCore/EncodeBuffer.swift +++ b/Sources/NIOIMAPCore/EncodeBuffer.swift @@ -12,15 +12,13 @@ // //===----------------------------------------------------------------------===// -import struct NIO.ByteBuffer -import struct NIO.ByteBufferView -import struct NIO.CircularBuffer +import DequeModule /// A buffer for encoding IMAP protocol messages into wire format. /// /// `EncodeBuffer` is the core infrastructure for converting Swift types into bytes -/// that can be transmitted over the network. It wraps a `ByteBuffer` and tracks -/// encoding state, supporting both client commands and server responses. +/// that can be transmitted over the network. It appends those bytes to an +/// ``EncoderOutputBuffer`` — a sink chosen by whoever created the buffer — and tracks encoding state. /// /// Part of the internal SPI and is primarily used by: /// - ``CommandEncodeBuffer`` for encoding client commands @@ -40,7 +38,7 @@ import struct NIO.CircularBuffer /// continuation response is expected. /// /// - SeeAlso: ``CommandEncodeBuffer``, ``ResponseEncodeBuffer`` -@_spi(NIOIMAPInternal) public struct EncodeBuffer: Hashable, Sendable { +@_spi(NIOIMAPInternal) public struct EncodeBuffer { /// Determines whether the buffer encodes for a client or server. /// /// Affects how the buffer formats protocol elements like literals, strings, @@ -65,68 +63,118 @@ import struct NIO.CircularBuffer /// Enables logging mode, which obscures binary data for display purposes. /// - /// When `true`, methods like ``writeBytes(_:)`` and ``writeBuffer(_:)`` will - /// write placeholder text like `[N bytes]` instead of the actual binary content. - /// Useful for logging and debugging without exposing sensitive data. + /// When `true`, methods like ``writeBytes(_:)-1nrmp`` will write placeholder text like + /// `[N bytes]` instead of the actual binary content. Useful for logging and debugging without + /// exposing sensitive data. public var loggingMode: Bool internal var mode: Mode - @usableFromInline internal var buffer: ByteBuffer - @usableFromInline internal var stopPoints: CircularBuffer = [] - init(_ buffer: ByteBuffer, mode: Mode, loggingMode: Bool) { - self.buffer = buffer + /// Where the encoded bytes go. + @usableFromInline internal var sink: any EncoderOutputBuffer + + /// Offsets, counted in ``totalWritten``, at which chunks must be broken. + /// + /// These are **absolute** — bytes ever appended to this buffer — rather than positions within + /// what the sink is currently holding, because the sink's contents shrink every time a chunk is + /// handed out. See ``markStopPoint()``. + @usableFromInline internal var stopPoints: Deque = [] + + /// How many bytes have ever been appended, since the buffer was created or last cleared. + @usableFromInline internal var totalWritten: Int = 0 + + /// How many bytes have ever been handed out by ``nextChunk()``. + /// + /// `handedOut + sink.byteCount + stagedCount == totalWritten` at all times, which is the invariant + /// that makes the absolute stop points above meaningful. + @usableFromInline internal var handedOut: Int = 0 + + /// Small writes collect here and reach the sink as one `append`: one existential call per + /// ``stagingCapacity`` bytes instead of one per write. Flushed before any direct sink append and + /// before the sink hands bytes out. + @usableFromInline internal var staging = Staging(repeating: 0) + + /// How many bytes at the start of ``staging`` are waiting for the sink. + @usableFromInline internal var stagedCount: Int = 0 + + // 256: a typical command or response line, while keeping copies of `EncodeBuffer` cheap. + @usableFromInline typealias Staging = InlineArray<256, UInt8> + + /// The most bytes ``staging`` holds. A write at least this big skips it. + @inlinable static var stagingCapacity: Int { Staging.count } + + init(_ sink: some EncoderOutputBuffer, mode: Mode, loggingMode: Bool) { + self.sink = sink self.mode = mode self.loggingMode = loggingMode } } +// MARK: - Sendability + +/// `EncodeBuffer` is deliberately **not** `Sendable`. +/// +/// It writes into an ``EncoderOutputBuffer``, which is not `Sendable` either: a sink belongs to one +/// encoder, which belongs to one connection handler, and it may own memory it is actively writing +/// into. What does cross a thread is a chunk that has been handed out — ``Chunk`` holds an +/// ``IMAPBufferList``, whose bytes are frozen at hand-out and so are `Sendable`. +@available(*, unavailable) +extension EncodeBuffer: Sendable {} + extension EncodeBuffer { /// Creates a new `EncodeBuffer` suitable for a client to write commands. - /// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`. + /// - parameter sink: Where the encoded bytes are appended. /// - parameter options: Configuration to use when writing. /// - returns: A new `EncodeBuffer` configured for client use. static func clientEncodeBuffer( - buffer: ByteBuffer, + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), options: CommandEncodingOptions, loggingMode: Bool ) -> EncodeBuffer { - EncodeBuffer(buffer, mode: .client(options: options), loggingMode: loggingMode) + EncodeBuffer(sink, mode: .client(options: options), loggingMode: loggingMode) } /// Creates a new `EncodeBuffer` suitable for a client to write commands. - /// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`. + /// - parameter sink: Where the encoded bytes are appended. /// - parameter capabilities: The capabilities the server advertised, which decide the encoding /// options. /// - returns: A new `EncodeBuffer` configured for client use. - static func clientEncodeBuffer(buffer: ByteBuffer, capabilities: [Capability], loggingMode: Bool) -> EncodeBuffer { + static func clientEncodeBuffer( + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), + capabilities: [Capability], + loggingMode: Bool + ) -> EncodeBuffer { clientEncodeBuffer( - buffer: buffer, + sink: sink, options: CommandEncodingOptions(capabilities: capabilities), loggingMode: loggingMode ) } /// Creates a new `EncodeBuffer` suitable for a server to write responses. - /// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`. + /// - parameter sink: Where the encoded bytes are appended. /// - parameter options: Configuration to use when writing. /// - returns: A new `EncodeBuffer` configured for server use. static func serverEncodeBuffer( - buffer: ByteBuffer, + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), options: ResponseEncodingOptions, loggingMode: Bool ) -> EncodeBuffer { - EncodeBuffer(buffer, mode: .server(streamingAttributes: false, options: options), loggingMode: loggingMode) + EncodeBuffer(sink, mode: .server(streamingAttributes: false, options: options), loggingMode: loggingMode) } /// Creates a new `EncodeBuffer` suitable for a server to write responses. - /// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`. + /// - parameter sink: Where the encoded bytes are appended. /// - parameter capabilities: The capabilities the server advertises, which decide the encoding /// options. /// - returns: A new `EncodeBuffer` configured for server use. - static func serverEncodeBuffer(buffer: ByteBuffer, capabilities: [Capability], loggingMode: Bool) -> EncodeBuffer { + static func serverEncodeBuffer( + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), + capabilities: [Capability], + loggingMode: Bool + ) -> EncodeBuffer { serverEncodeBuffer( - buffer: buffer, + sink: sink, options: ResponseEncodingOptions(capabilities: capabilities), loggingMode: loggingMode ) @@ -142,9 +190,27 @@ extension EncodeBuffer { options.useQuotedString = true options.useSynchronizingLiteral = false options.useNonSynchronizingLiteralPlus = true - var buffer = EncodeBuffer.clientEncodeBuffer(buffer: ByteBuffer(), options: options, loggingMode: false) + var buffer = EncodeBuffer.clientEncodeBuffer(options: options, loggingMode: false) closure(&buffer) - return String(bestEffortDecodingUTF8Bytes: buffer.buffer.readableBytesView) + return String(bestEffortDecodingUTF8Bytes: buffer.makePendingBufferList().copiedBytes()) + } + + /// The bytes appended but not yet handed out, as one list. + /// + /// Cold path only — equality, hashing and debug descriptions. This allocates per pending region, + /// which is why it is a method rather than a property. + internal func makePendingBufferList() -> IMAPBufferList { + var list = sink.withPendingRegions { regions in + var list = IMAPBufferList() + for index in 0.. 0 { + list.append(withUnsafeBytes(of: self.staging) { IMAPBuffer(Array($0.prefix(self.stagedCount))) }) + } + return list } } @@ -161,8 +227,10 @@ extension EncodeBuffer { public struct Chunk: Hashable, Sendable { /// The encoded bytes ready to write to the network. /// - /// Contains the next portion of IMAP protocol data to transmit. - public var bytes: ByteBuffer + /// Contains the next portion of IMAP protocol data to transmit, as one or more regions — + /// usually one. A networking caller writes them in order and lets the transport gather + /// them; ``IMAPBufferList/copiedBytes()`` coalesces them where they have to be contiguous. + public var bytes: IMAPBufferList /// Whether a continuation request (`+`) should be expected before sending the next chunk. /// @@ -170,6 +238,9 @@ extension EncodeBuffer { /// response before calling ``nextChunk()`` again. This synchronization is required /// by RFC 3501 for commands containing literals. /// + /// `false` for a chunk that ends at a stop point with nothing written after it yet, e.g. + /// APPEND's `{5}\r\n`; ``CommandEncodeBuffer/nextChunk()`` reports that one as awaiting `+`. + /// /// - SeeAlso: ``ContinuationRequest`` public var waitForContinuation: Bool } @@ -178,6 +249,11 @@ extension EncodeBuffer { self.stopPoints.count > 0 } + /// How many bytes have been written but not yet handed out by ``nextChunk()``. + internal var pendingByteCount: Int { + self.sink.byteCount + self.stagedCount + } + /// Retrieves the next chunk of encoded data ready to transmit. /// /// In client mode with synchronizing literals, this may return multiple chunks with @@ -196,24 +272,60 @@ extension EncodeBuffer { /// *NOTE*: Use This function with caution. You probably shouldn't be using it, using nextChunk() instead. /// - returns: The next chunk that is ready to be written. @_spi(NIOIMAPInternal) public mutating func nextChunk(allowEmptyChunk: Bool) -> Chunk { + self.takeChunk(allowEmptyChunk: allowEmptyChunk).chunk + } + + /// Where a chunk handed out by ``takeChunk(allowEmptyChunk:)`` ends. + enum ChunkEnd { + /// At a stop point: a synchronizing literal header, whose `+` the client awaits. Possibly the + /// last byte written, e.g. APPEND's `{5}\r\n` before the message bytes are written. + case stopPoint + /// With everything pending; no stop point remains. + case pendingBytes + } + + /// ``nextChunk(allowEmptyChunk:)``, and whether the chunk ended at a stop point. + /// + /// ``Chunk/waitForContinuation`` can't tell: it is `false` for a stop point that is the last byte + /// written so far. + mutating func takeChunk(allowEmptyChunk: Bool) -> (chunk: Chunk, end: ChunkEnd) { switch self.mode { case .client: guard let stopPoint = self.stopPoints.popFirst() else { - precondition(allowEmptyChunk || self.buffer.readableBytes > 0, "No next chunk to send.") - return .init( - bytes: self.buffer.readSlice(length: self.buffer.readableBytes)!, - waitForContinuation: false - ) + // A zero-*bytes* check, deliberately not `regionCount == 0`: a chunk carrying one + // zero-length region holds no bytes at all. + precondition(allowEmptyChunk || self.pendingByteCount > 0, "No next chunk to send.") + return (.init(bytes: self.takeEverythingPending(), waitForContinuation: false), .pendingBytes) } - return .init( - bytes: self.buffer.readSlice(length: stopPoint - self.buffer.readerIndex)!, - waitForContinuation: stopPoint != self.buffer.writerIndex - ) + // Both are absolute offsets, so the difference is what is pending below the stop point. + // Comparing a stop point against the sink's own (resetting) byte count instead is the + // mistake that deadlocks the protocol. + let bytes = self.takeFromSink(stopPoint - self.handedOut) + self.handedOut = stopPoint + return (.init(bytes: bytes, waitForContinuation: stopPoint != self.totalWritten), .stopPoint) case .server: - return .init(bytes: self.buffer.readSlice(length: self.buffer.readableBytes)!, waitForContinuation: false) + return (.init(bytes: self.takeEverythingPending(), waitForContinuation: false), .pendingBytes) } } + private mutating func takeEverythingPending() -> IMAPBufferList { + let bytes = self.takeFromSink(self.pendingByteCount) + self.handedOut = self.totalWritten + return bytes + } + + /// Takes pending bytes, staged ones included, capped at ``IMAPBufferList/maximumRegionsPerChunk`` + /// regions whatever the sink returned. + /// + /// The cap is here rather than in each sink so that a sink of the caller's own gets it too. Checking + /// is O(1); only a list over the cap is rebuilt. + private mutating func takeFromSink(_ byteCount: Int) -> IMAPBufferList { + self.flushStaging() + let bytes = self.sink.takeFirst(byteCount) + guard bytes.regionCount > IMAPBufferList.maximumRegionsPerChunk else { return bytes } + return IMAPBufferList(cappingRegionCount: bytes.regions) + } + /// Marks the end of a command, potentially creating a stop point for chunking. /// /// In client mode, this sets a stop point that ``nextChunk()`` uses to determine @@ -226,7 +338,7 @@ extension EncodeBuffer { @discardableResult public mutating func markStopPoint() -> Int { if case .client = mode { - stopPoints.append(buffer.writerIndex) + stopPoints.append(totalWritten) } return 0 } @@ -240,7 +352,11 @@ extension EncodeBuffer { @discardableResult @inlinable public mutating func writeString(_ string: String) -> Int { - self.buffer.writeString(string) + // Contiguous for every native string. A foreign one, e.g. a bridged non-ASCII `NSString`, + // has to be transcoded, which allocates. + let written = string.utf8.withContiguousStorageIfAvailable { self.appendBytes(UnsafeRawBufferPointer($0)) } + if let written { return written } + return Array(string.utf8).withUnsafeBytes { self.appendBytes($0) } } /// Writes a single byte to the buffer. @@ -274,7 +390,7 @@ extension EncodeBuffer { /// interpolation machinery and heap-allocates as soon as the result exceeds 15 UTF-8 bytes, /// whereas this formats the digits into a stack buffer and copies them once. /// - /// Unlike ``writeBytes(_:)``, this is never redacted in ``loggingMode`` — the numbers + /// Unlike ``writeBytes(_:)-1nrmp``, this is never redacted in ``loggingMode`` — the numbers /// written here are lengths, offsets and identifiers, not payload. /// /// - Parameters: @@ -322,30 +438,52 @@ extension EncodeBuffer { /// - Returns: The number of bytes written (in logging mode, this is the length of the placeholder). @discardableResult @inlinable - public mutating func writeBytes(_ bytes: Bytes) -> Int where Bytes.Element == UInt8 { - guard loggingMode else { - return self.buffer.writeBytes(bytes) + public mutating func writeBytes(_ bytes: some Collection) -> Int { + guard !loggingMode else { + return self.writeRedactedByteCount(bytes.count) } - return self.writeRedactedByteCount(bytes.reduce(into: 0) { count, _ in count += 1 }) + // Every caller in the encoder passes an array, an `ArraySlice`, or a `String.UTF8View`, all + // of which take the contiguous path. + if let written = bytes.withContiguousStorageIfAvailable({ buffer -> Int in + guard let base = buffer.baseAddress else { return 0 } + return self.appendBytes(UnsafeRawBufferPointer(start: base, count: buffer.count)) + }) { + return written + } + let contiguous = ContiguousArray(bytes) + return contiguous.withUnsafeBytes { self.appendBytes($0) } } - /// Writes a `ByteBuffer` to the buffer. + /// Writes raw message bytes to the buffer. /// - /// When ``loggingMode`` is enabled, this writes a placeholder like `[N bytes]` - /// instead of the actual binary data. + /// This is the overload the four raw-payload model cases use — `messageBytes`, `catenateData`, + /// `continuationResponse` and `streamingBytes`. It exists so that a multi-megabyte literal can be + /// handed to the encoder without being copied, which is what an ``IMAPBuffer`` gives a caller + /// that received it from the parser or wrapped its own memory in it. /// - /// - Parameter buffer: The buffer to write. + /// Whether the bytes are actually copied is the sink's decision: ``IMAPOutputBuffer`` keeps a + /// large region by reference and copies a small one, so forwarding a `FETCH` literal into an + /// `APPEND` costs nothing. + /// + /// When ``loggingMode`` is enabled, this writes a placeholder like `[N bytes]` instead of the + /// payload, matching the other byte-writing primitives. + /// + /// - Parameter region: The bytes to write. /// - Returns: The number of bytes written (in logging mode, this is the length of the placeholder). @discardableResult @inlinable - public mutating func writeBuffer(_ buffer: inout ByteBuffer) -> Int { - guard loggingMode else { - return self.buffer.writeBuffer(&buffer) + public mutating func writeBytes(_ region: IMAPBuffer) -> Int { + guard !loggingMode else { + return self.writeRedactedByteCount(region.count) } - return self.writeRedactedByteCount(buffer.readableBytes) + // Flush first: the sink must see the bytes in order, and gets the region itself, uncopied. + self.flushStaging() + self.sink.append(region) + self.totalWritten += region.count + return region.count } - /// Appends bytes to the buffer with no redaction. + /// Appends bytes with no redaction: into ``staging`` if they fit, else to the sink. /// /// The primitive the redaction-exempt writers (``writeByte(_:)``, /// ``writeDecimal(_:minimumDigits:)``) and the already-redacted ones build on. A caller that @@ -356,7 +494,32 @@ extension EncodeBuffer { @discardableResult @inlinable mutating func appendBytes(_ bytes: UnsafeRawBufferPointer) -> Int { - self.buffer.writeBytes(bytes) + let count = bytes.count + self.totalWritten += count + guard count < Self.stagingCapacity else { + self.flushStaging() + self.sink.append(bytes) + return count + } + guard let source = bytes.baseAddress else { return count } + if count > Self.stagingCapacity - self.stagedCount { + self.flushStaging() + } + let offset = self.stagedCount + withUnsafeMutableBytes(of: &self.staging) { staging in + staging.baseAddress!.advanced(by: offset).copyMemory(from: source, byteCount: count) + } + self.stagedCount += count + return count + } + + /// Hands the staged bytes to the sink. + @inlinable + mutating func flushStaging() { + guard self.stagedCount > 0 else { return } + let count = self.stagedCount + self.stagedCount = 0 + withUnsafeBytes(of: &self.staging) { self.sink.append(UnsafeRawBufferPointer(rebasing: $0.prefix(count))) } } /// Writes the `[123 bytes]` placeholder that ``loggingMode`` substitutes for payload bytes. @@ -375,7 +538,39 @@ extension EncodeBuffer { @inlinable public mutating func clear() { self.stopPoints.removeAll() - self.buffer.clear() + self.sink.removeAll() + self.stagedCount = 0 + self.totalWritten = 0 + self.handedOut = 0 + } +} + +// MARK: - Equatable & Hashable + +extension EncodeBuffer: Hashable { + /// Compares two buffers by their state and by the bytes they are holding. + /// + /// The bytes are compared byte by byte rather than region by region, so two buffers holding the + /// same bytes are equal however their sinks happened to split them up. That matters because the + /// split depends on segment sizes and on whether a payload was retained or copied. + /// + /// - Complexity: O(``pendingByteCount``). + public static func == (lhs: EncodeBuffer, rhs: EncodeBuffer) -> Bool { + lhs.mode == rhs.mode && lhs.loggingMode == rhs.loggingMode && lhs.stopPoints == rhs.stopPoints + && lhs.totalWritten == rhs.totalWritten && lhs.handedOut == rhs.handedOut + && lhs.makePendingBufferList() == rhs.makePendingBufferList() + } + + /// Hashes the buffer's state and the bytes it is holding. + /// + /// - Complexity: O(``pendingByteCount``). + public func hash(into hasher: inout Hasher) { + hasher.combine(mode) + hasher.combine(loggingMode) + hasher.combine(stopPoints) + hasher.combine(totalWritten) + hasher.combine(handedOut) + hasher.combine(makePendingBufferList()) } } diff --git a/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md b/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md index c34e06ef..c02ca46c 100644 --- a/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md +++ b/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md @@ -6,6 +6,8 @@ Parse IMAP server responses and encode client commands using these streaming par NIOIMAPCore provides comprehensive parsing and encoding capabilities. These types handle the conversion between the IMAP wire format and strongly-typed Swift structures, including error handling and advanced features like pipelining. +On the way out, ``CommandEncodeBuffer`` and ``ResponseEncodeBuffer`` write into an ``EncoderOutputBuffer`` — ``IMAPOutputBuffer`` unless you pass another — and hand bytes out as an ``IMAPBufferList`` — ordered ``IMAPBuffer`` regions, usually one — from ``CommandEncodeBuffer/nextChunk()`` and ``ResponseEncodeBuffer/readBytes()``. A command chunk ends at each synchronizing literal header; its ``CommandEncodeBuffer/Chunk/nextStep`` says whether to wait for the server's `+` before sending the next. A large payload you supply as an ``IMAPBuffer`` is kept by reference, so forwarding a message costs no copy. Handed-out bytes never move or change, so a chunk is `Sendable` and can be written while encoding continues. Convert it with ``IMAPBufferList/makeDispatchData()``, `makeByteBuffers()` in NIOIMAP, or ``IMAPBufferList/copiedBytes()``. + ## Topics ### Parsers diff --git a/Sources/NIOIMAPCore/Parser/ParseInput.swift b/Sources/NIOIMAPCore/Parser/ParseInput.swift index 16d1ebc9..44eca2bb 100644 --- a/Sources/NIOIMAPCore/Parser/ParseInput.swift +++ b/Sources/NIOIMAPCore/Parser/ParseInput.swift @@ -34,7 +34,7 @@ import Android // // Unsafe seams. In the byte, encoder and parser code — `NIOIMAPCore`'s `Bytes/`, `Parser/` and // `EncodeBuffer*.swift`, and `NIOIMAP`'s `Bytes/` — memory safety and `Sendable` are compiler-checked -// except at these thirteen. Not counted: reading through a pointer, or binding it to `UInt8`, inside the +// except at these fourteen. Not counted: reading through a pointer, or binding it to `UInt8`, inside the // `withUnsafe…` closure that produced it. Outside that scope, `Base64/Chromium.swift` and // `MailboxName.swift` use pointers too; both predate this list. // @@ -65,18 +65,21 @@ import Android // (EncodeBuffer.swift). `maximumDecimalLength` holds every digit of a number up to // `maximumDecimalBitWidth` bits plus a sign; padding stops at the start; only the written suffix is read. // 9. Write: `EncodeBuffer.writeQuotedIMAPString(_:)` escapes into a `withUnsafeTemporaryAllocation` -// (ByteBuffer+WriteLiteral.swift). Its `2 * count + 2` bytes fit every byte escaped, plus both quotes. -// 10. Public: `IMAPBuffer.withUnsafeBytesAndOwner(_:)` (IMAPBuffer.swift) lets its pointer escape the +// (EncodeBuffer+WriteLiteral.swift). Its `2 * count + 2` bytes fit every byte escaped, plus both quotes. +// 10. Write: `EncodeBuffer.appendBytes(_:)` copies into the `staging` `InlineArray` with `copyMemory` +// (EncodeBuffer.swift). It copies only when `stagedCount + count` fits `stagingCapacity`, flushing +// first if needed; `flushStaging()` reads only the `stagedCount` bytes written. +// 11. Public: `IMAPBuffer.withUnsafeBytesAndOwner(_:)` (IMAPBuffer.swift) lets its pointer escape the // closure. It hands out only bytes with a fixed address, and they stay valid while the caller holds // `owner`; correct use outside the closure is the caller's job. -// 11. Public: `StableAddressByteRegion` (ByteRegion.swift) is a promise nothing checks; seams 2, 6 and 10 +// 12. Public: `StableAddressByteRegion` (ByteRegion.swift) is a promise nothing checks; seams 2, 6 and 11 // rest on it, through `IMAPByteStorage.hasStableAddress`. The library conforms the stdlib byte arrays // and `DispatchDataRegion`, not `DispatchData.Region`, which does not keep its bytes alive; `NIOIMAP` // conforms `ByteBuffer`. -// 12. Sendable: `DispatchDataRegion: @unchecked Sendable` (ParserInputBuffer+Foundation.swift), what +// 13. Sendable: `DispatchDataRegion: @unchecked Sendable` (ParserInputBuffer+Foundation.swift), what // `IMAPInputBuffer.append(contentsOf:)` keeps. Its pointer is into the `DispatchData` it holds, which // is immutable and keeps its regions alive. -// 13. Sendable: `GrammarParser: @unchecked Sendable` (GrammarParser.swift), older than this list. Its +// 14. Sendable: `GrammarParser: @unchecked Sendable` (GrammarParser.swift), older than this list. Its // `parsedStringCache` closure is not `@Sendable`. /// One contiguous run of input bytes, plus whoever can keep those bytes alive. diff --git a/Sources/NIOIMAPCore/ResponseEncodeBuffer.swift b/Sources/NIOIMAPCore/ResponseEncodeBuffer.swift index f7ac3aaf..32c35009 100644 --- a/Sources/NIOIMAPCore/ResponseEncodeBuffer.swift +++ b/Sources/NIOIMAPCore/ResponseEncodeBuffer.swift @@ -25,7 +25,6 @@ import struct NIO.ByteBuffer /// /// ```swift /// var buffer = ResponseEncodeBuffer( -/// buffer: ByteBuffer(), /// options: ResponseEncodingOptions(), /// loggingMode: false /// ) @@ -33,8 +32,16 @@ import struct NIO.ByteBuffer /// let encoded = buffer.readBytes() // Get all encoded data /// ``` /// +/// ## Where the bytes go +/// +/// This is the type a server creates; it owns an ``EncoderOutputBuffer``, the sink the encoded bytes +/// are appended to, chosen once with the `sink:` argument and never named again. Leaving it out gives +/// an ``IMAPOutputBuffer``, which is the right answer unless the bytes have to land somewhere +/// specific — see ``EncoderOutputBuffer`` for the choice. ``readBytes()`` hands back an +/// ``IMAPBufferList``, which converts to a `DispatchData`, to `ByteBuffer`s, or to one contiguous copy. +/// /// - SeeAlso: ``CommandEncodeBuffer``, ``ResponseEncodingOptions`` -public struct ResponseEncodeBuffer: Sendable { +public struct ResponseEncodeBuffer { var buffer: EncodeBuffer /// Retrieves all encoded data from the buffer for transmission. @@ -43,28 +50,50 @@ public struct ResponseEncodeBuffer: Sendable { /// next response. This is typically called after encoding a complete response /// to retrieve the wire-format bytes for sending to the client. /// - /// - Returns: A `ByteBuffer` containing all encoded response data. - public mutating func readBytes() -> ByteBuffer { - let buffer = self.buffer.nextChunk().bytes - precondition(self.buffer.buffer.readableBytes == 0) - self.buffer.buffer.clear() - return buffer + /// - Returns: All encoded response data, as one or more regions — usually one. + public mutating func readBytes() -> IMAPBufferList { + let bytes = self.buffer.nextChunk().bytes + // A zero-*bytes* check: a server-mode chunk takes everything, so nothing may be left behind. + precondition(self.buffer.pendingByteCount == 0) + // Clearing also releases the sink's storage, which matters because a server handler keeps one + // of these for the lifetime of a connection. + self.buffer.clear() + return bytes } /// Creates a new response encoding buffer with explicit options. /// /// - Parameters: - /// - buffer: The initial `ByteBuffer` to build upon. This buffer is copied, - /// not taken as inout. + /// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``, which + /// is the right choice unless the bytes have to land somewhere specific. /// - options: The ``ResponseEncodingOptions`` controlling how strings and other /// protocol elements are encoded. /// - loggingMode: When `true`, binary data is replaced with placeholders like /// `[N bytes]` for safe logging. Defaults to `false`. - public init(buffer: ByteBuffer, options: ResponseEncodingOptions, loggingMode: Bool) { - self.buffer = .serverEncodeBuffer(buffer: buffer, options: options, loggingMode: loggingMode) + public init( + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), + options: ResponseEncodingOptions, + loggingMode: Bool + ) { + self.buffer = .serverEncodeBuffer(sink: sink, options: options, loggingMode: loggingMode) + } + + /// Wraps an existing ``EncodeBuffer``, so response writers can be driven over a buffer somebody + /// else created. + /// + /// - Parameter buffer: The buffer to write to. Must be in server mode. + internal init(_ buffer: EncodeBuffer) { + self.buffer = buffer } } +// MARK: - Sendability + +/// `ResponseEncodeBuffer` is deliberately **not** `Sendable`, because the ``EncoderOutputBuffer`` it +/// writes into is not: see ``EncodeBuffer``. The bytes ``readBytes()`` hands out *are* `Sendable`. +@available(*, unavailable) +extension ResponseEncodeBuffer: Sendable {} + extension ResponseEncodeBuffer { /// Creates a new response encoding buffer from server capabilities. /// @@ -72,14 +101,17 @@ extension ResponseEncodeBuffer { /// which enables capability-dependent encoding options if the server advertises them. /// /// - Parameters: - /// - buffer: The initial `ByteBuffer` to build upon. This buffer is copied, - /// not taken as inout. + /// - sink: Where the encoded bytes are appended. Defaults to an ``IMAPOutputBuffer``. /// - capabilities: Server capabilities for context. These may be used to configure /// encoding options if needed. /// - loggingMode: When `true`, binary data is replaced with placeholders like /// `[N bytes]` for safe logging. Defaults to `false`. - public init(buffer: ByteBuffer, capabilities: [Capability], loggingMode: Bool) { - self.buffer = .serverEncodeBuffer(buffer: buffer, capabilities: capabilities, loggingMode: loggingMode) + public init( + sink: some EncoderOutputBuffer = IMAPOutputBuffer(), + capabilities: [Capability], + loggingMode: Bool + ) { + self.buffer = .serverEncodeBuffer(sink: sink, capabilities: capabilities, loggingMode: loggingMode) } } @@ -90,9 +122,9 @@ extension ResponseEncodeBuffer { static func makeDescription(loggingMode: Bool, _ closure: (inout ResponseEncodeBuffer) -> Void) -> String { var options = ResponseEncodingOptions() options.useQuotedString = true - var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(), options: options, loggingMode: loggingMode) + var buffer = ResponseEncodeBuffer(options: options, loggingMode: loggingMode) closure(&buffer) - return String(bestEffortDecodingUTF8Bytes: buffer.buffer.buffer.readableBytesView) + return String(bestEffortDecodingUTF8Bytes: buffer.buffer.makePendingBufferList().copiedBytes()) } } diff --git a/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift b/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift index c500edc6..5816fb2d 100644 --- a/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift +++ b/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift @@ -50,6 +50,36 @@ private struct UnstableBuffer: ByteRegion, Sendable { } } +/// A third-party sink that hands every byte out as a region of its own: the most regions a sink can. +private struct OneRegionPerByteSink: EncoderOutputBuffer { + private var bytes: [UInt8] = [] + + var byteCount: Int { bytes.count } + + mutating func append(_ bytes: UnsafeRawBufferPointer) { + self.bytes.append(contentsOf: bytes) + } + + mutating func append(_ region: IMAPBuffer) { + region.withUnsafeBytes { bytes.append(contentsOf: $0) } + } + + mutating func takeFirst(_ byteCount: Int) -> IMAPBufferList { + let taken = bytes.prefix(byteCount).map { IMAPBuffer([$0]) } + bytes.removeFirst(byteCount) + return IMAPBufferList(taken) + } + + func withPendingRegions(_ body: (Span) -> R) -> R { + let regions = ContiguousArray(bytes.map { IMAPBuffer([$0]) }) + return body(regions.span) + } + + mutating func removeAll() { + bytes = [] + } +} + /// Where `buffer`'s bytes are. private func address(of buffer: IMAPBuffer) -> UnsafeRawPointer? { buffer.withUnsafeBytes { UnsafeRawPointer($0.baseAddress) } @@ -205,4 +235,21 @@ struct StableAddressByteRegionTests { let unstable = UnstableBuffer(bytes: Array(repeating: 0, count: Self.byteCount)) #expect(donatedAddress(of: wrapGenerically(unstable)) == nil) } + + /// The most regions the encoder hands out in one chunk. Internal to the library, so spelled here. + static let encoderRegionCap = 64 + + @Test("the encoder caps the regions a sink of your own hands it") + func encoderCapsForeignSink() { + var encoder = ResponseEncodeBuffer( + sink: OneRegionPerByteSink(), + options: ResponseEncodingOptions(), + loggingMode: false + ) + let text = String(repeating: "x", count: 1_000) + encoder.writeContinuationRequest(.responseText(ResponseText(text: text))) + let bytes = encoder.readBytes() + #expect(bytes.regionCount == Self.encoderRegionCap) + #expect(bytes.copiedBytes() == Array("+ \(text)\r\n".utf8)) + } } diff --git a/Tests/NIOIMAPCoreTests/CommandEncodeFixture.swift b/Tests/NIOIMAPCoreTests/CommandEncodeFixture.swift index ccceb47f..b8497e55 100644 --- a/Tests/NIOIMAPCoreTests/CommandEncodeFixture.swift +++ b/Tests/NIOIMAPCoreTests/CommandEncodeFixture.swift @@ -48,7 +48,6 @@ extension CommandEncodeFixture { sourceLocation: SourceLocation = #_sourceLocation ) { var encodeBuffer = CommandEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: options, loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/EncodeBufferPrimitivesTests.swift b/Tests/NIOIMAPCoreTests/EncodeBufferPrimitivesTests.swift index 41307c56..b0e1fd0a 100644 --- a/Tests/NIOIMAPCoreTests/EncodeBufferPrimitivesTests.swift +++ b/Tests/NIOIMAPCoreTests/EncodeBufferPrimitivesTests.swift @@ -21,7 +21,6 @@ import Testing struct EncodeBufferPrimitivesTests { private func encoded(_ write: (inout EncodeBuffer) -> Int) -> (string: String, byteCount: Int) { var buffer = EncodeBuffer.clientEncodeBuffer( - buffer: ByteBuffer(), options: .rfc3501, loggingMode: false ) @@ -152,12 +151,12 @@ struct LoggingModeRedactionTests { /// Encodes in logging mode, draining every chunk — redacted literals still mark stop points, so /// reading one chunk would silently truncate. private func redacted(_ write: (inout EncodeBuffer) -> Void) -> String { - var buffer = EncodeBuffer.clientEncodeBuffer(buffer: ByteBuffer(), options: .rfc3501, loggingMode: true) + var buffer = EncodeBuffer.clientEncodeBuffer(options: .rfc3501, loggingMode: true) write(&buffer) var bytes: [UInt8] = [] while true { let chunk = buffer.nextChunk() - bytes.append(contentsOf: chunk.bytes.readableBytesView) + bytes.append(contentsOf: chunk.bytes.copiedBytes()) guard chunk.waitForContinuation else { break } } return String(decoding: bytes, as: UTF8.self) @@ -167,8 +166,8 @@ struct LoggingModeRedactionTests { func rawBytes() { #expect(redacted { $0.writeBytes([1, 2, 3]) } == "[3 bytes]") #expect(redacted { $0.writeBytes([]) } == "[0 bytes]") - var payload = ByteBuffer(repeating: 0, count: 4096) - #expect(redacted { $0.writeBuffer(&payload) } == "[4096 bytes]") + let payload = IMAPBuffer(Array(repeating: UInt8(0), count: 4096)) + #expect(redacted { $0.writeBytes(payload) } == "[4096 bytes]") } @Test("numbers and single bytes are not redacted, because they are not payload") diff --git a/Tests/NIOIMAPCoreTests/EncodeBufferSinkTests.swift b/Tests/NIOIMAPCoreTests/EncodeBufferSinkTests.swift new file mode 100644 index 00000000..6050fa57 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/EncodeBufferSinkTests.swift @@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +#if canImport(ObjectiveC) +import Foundation // for a bridged `NSString` +#endif + +/// The encoder writing into an ``EncoderOutputBuffer`` instead of into one contiguous buffer. +/// +/// The cases here are the ones the change could get wrong without any existing test noticing: stop +/// points now being offsets into "bytes ever written" rather than positions in a buffer whose contents +/// are handed away, and the sink being reachable through an existential that copies. +@Suite("EncodeBuffer over a sink") +struct EncodeBufferSinkTests { + private func clientBuffer(_ options: CommandEncodingOptions = .rfc3501) -> EncodeBuffer { + EncodeBuffer.clientEncodeBuffer(options: options, loggingMode: false) + } + + private func drain(_ buffer: inout EncodeBuffer) -> [String] { + var chunks: [String] = [] + while true { + let chunk = buffer.nextChunk() + chunks.append(String(buffer: chunk.bytes)) + guard chunk.waitForContinuation else { return chunks } + } + } + + // MARK: - Stop points + + /// The case that deadlocks the protocol if stop points are measured against the sink's own byte + /// count: after the first chunk is handed out, the sink is holding fewer bytes than were written, + /// so a stop point recorded before the hand-out is meaningless as a position within it. + @Test("a stop point is an offset into everything written, not into what is pending") + func stopPointsAreAbsolute() { + var buffer = clientBuffer() + buffer.writeString("A1 LOGIN {1}\r\n") + buffer.markStopPoint() + buffer.writeString("x {1}\r\n") + buffer.markStopPoint() + buffer.writeString("y\r\n") + + #expect(drain(&buffer) == ["A1 LOGIN {1}\r\n", "x {1}\r\n", "y\r\n"]) + } + + /// A stop point at the very end means "everything has been written", so the last chunk must not + /// ask for a continuation. One byte out either way is the deadlock. + @Test("a trailing stop point does not ask for a continuation") + func trailingStopPointDoesNotWait() { + var buffer = clientBuffer() + buffer.writeString("A1 LOGIN {1}\r\n") + buffer.markStopPoint() + buffer.writeString("x") + buffer.markStopPoint() + + var first = buffer.nextChunk() + #expect(String(buffer: first.bytes) == "A1 LOGIN {1}\r\n") + #expect(first.waitForContinuation) + + first = buffer.nextChunk() + #expect(String(buffer: first.bytes) == "x") + #expect(!first.waitForContinuation) + } + + @Test("hasChunks tracks the outstanding stop points") + func hasChunks() { + var buffer = clientBuffer() + #expect(!buffer.hasChunks) + buffer.writeString("A1 LOGIN {1}\r\n") + buffer.markStopPoint() + #expect(buffer.hasChunks) + buffer.writeString("x\r\n") + _ = buffer.nextChunk() + #expect(!buffer.hasChunks) + } + + @Test("a server-mode buffer ignores stop points and hands out everything at once") + func serverModeTakesEverything() { + var buffer = EncodeBuffer.serverEncodeBuffer(options: ResponseEncodingOptions(), loggingMode: false) + buffer.writeString("* OK ") + buffer.markStopPoint() + buffer.writeString("hello\r\n") + #expect(drain(&buffer) == ["* OK hello\r\n"]) + } + + @Test("clear resets the counters as well as the bytes") + func clearResetsCounters() { + var buffer = clientBuffer() + buffer.writeString("A1 LOGIN {1}\r\n") + buffer.markStopPoint() + buffer.writeString("x\r\n") + buffer.clear() + + #expect(buffer.pendingByteCount == 0) + #expect(!buffer.hasChunks) + + // Writing again must start from zero: a stop point recorded now is at offset 2, and comparing + // it against a counter that still remembers the cleared bytes would split in the wrong place. + buffer.writeString("A2") + buffer.markStopPoint() + buffer.writeString(" NOOP\r\n") + #expect(drain(&buffer) == ["A2", " NOOP\r\n"]) + } + + /// Chunking is where a `ByteBuffer`-backed encoder used to copy: handing out a slice left the + /// storage shared, so every later write copied what remained. Segments have no such coupling, and + /// what a caller can observe is that bytes handed out earlier are unaffected by writes afterwards. + @Test("bytes already handed out are unchanged by later writes") + func handedOutBytesAreStable() { + var buffer = clientBuffer() + buffer.writeString("A1 LOGIN {1}\r\n") + buffer.markStopPoint() + buffer.writeString("x") + + let first = buffer.nextChunk() + #expect(first.waitForContinuation) + + // Enough to overflow the first segment and force new ones. + for _ in 0..<4096 { + buffer.writeString("0123456789abcdef") + } + #expect(String(buffer: first.bytes) == "A1 LOGIN {1}\r\n") + } + + // MARK: - Chunk contents + + @Test("a chunk reports bytes and regions separately") + func chunkCounts() { + var buffer = clientBuffer() + // Above `copyThreshold`, so the sink keeps this region by reference rather than copying it + // into a segment — which is what makes the chunk multi-region. + let payload = IMAPBuffer([UInt8](repeating: UInt8(ascii: "z"), count: 4096)) + buffer.writeString("A1 ") + buffer.writeBytes(payload) + buffer.writeString("\r\n") + + let chunk = buffer.nextChunk() + #expect(chunk.bytes.byteCount == 3 + 4096 + 2) + #expect(chunk.bytes.regionCount == 3) + #expect(chunk.bytes.copiedBytes().count == 3 + 4096 + 2) + } + + @Test("an empty buffer hands out an empty chunk rather than nothing") + func emptyChunk() { + var buffer = clientBuffer() + let chunk = buffer.nextChunk() + #expect(chunk.bytes.byteCount == 0) + #expect(!chunk.waitForContinuation) + } + + // MARK: - Equality + + @Test("two buffers holding the same bytes are equal however their sinks split them") + func equalityIgnoresSegmentation() { + // 64 bytes at a time into a sink with tiny segments, against one write into a default one: + // the same bytes, but many regions versus one. + var fragmented = EncodeBuffer.clientEncodeBuffer( + sink: IMAPOutputBuffer(initialSegmentSize: 8, maximumSegmentSize: 8), + options: .rfc3501, + loggingMode: false + ) + var contiguous = clientBuffer() + let text = String(repeating: "abcdefgh", count: 8) + for character in text { + fragmented.writeString(String(character)) + } + contiguous.writeString(text) + + #expect(fragmented.pendingByteCount == contiguous.pendingByteCount) + #expect(fragmented == contiguous) + #expect(fragmented.hashValue == contiguous.hashValue) + } + + @Test("buffers holding different bytes are not equal") + func inequality() { + var a = clientBuffer() + var b = clientBuffer() + a.writeString("A1 NOOP\r\n") + b.writeString("A2 NOOP\r\n") + #expect(a != b) + } + + @Test("buffers differing only in their stop points are not equal") + func stopPointsParticipateInEquality() { + var a = clientBuffer() + var b = clientBuffer() + a.writeString("A1 LOGIN {1}\r\n") + a.markStopPoint() + b.writeString("A1 LOGIN {1}\r\n") + #expect(a != b) + } + + // MARK: - Copying + + /// `ClientStateMachine` stores an encode buffer in its state *and* returns it, and the encode + /// fixtures advance a copy while the original is live. Both copies have to keep working, and + /// neither may see the other's bytes. + @Test("a copy and the original write independently") + func copiesAreIndependent() { + var original = clientBuffer() + original.writeString("A1 ") + + var copy = original + copy.writeString("NOOP\r\n") + original.writeString("EXPUNGE\r\n") + + #expect(drain(©) == ["A1 NOOP\r\n"]) + #expect(drain(&original) == ["A1 EXPUNGE\r\n"]) + } + + /// The failure this guards against is not wrong bytes but wrong *shape*: a spurious copy of the + /// buffer makes the sink's state look shared, and a shared sink seals its open segment and starts + /// a new one. That used to happen once per conditional write, so an array of *n* elements became + /// *n* segments and *n* output regions with the segment size doubling each time. + @Test("writing an array does not fragment the output") + func writingAnArrayStaysInOneRegion() { + var buffer = EncodeBuffer.serverEncodeBuffer(options: ResponseEncodingOptions(), loggingMode: false) + buffer.writeMessageAttribute(.flags([.answered, .draft, .flagged, .seen])) + let chunk = buffer.nextChunk() + #expect(String(buffer: chunk.bytes) == #"FLAGS (\Answered \Draft \Flagged \Seen)"#) + #expect(chunk.bytes.regionCount == 1) + } + + // MARK: - The region cap + + /// Payloads at the copy threshold: each is kept by reference, so each is a region of its own. + private func payloads(_ count: Int) -> [IMAPBuffer] { + (0.. EncodeBuffer { + EncodeBuffer.clientEncodeBuffer(sink: RecordingOutputBuffer(), options: .rfc3501, loggingMode: false) + } + + /// The size of every `append` the sink has received so far. + private func appendSizes(_ buffer: EncodeBuffer) throws -> [Int] { + try #require(buffer.sink as? RecordingOutputBuffer).appendSizes + } + + @Test("small writes reach the sink as one append, at hand-out") + func smallWritesAreBatched() throws { + var buffer = recordingBuffer() + buffer.writeString("A1 ") + buffer.writeString("NOOP") + buffer.writeByte(UInt8(ascii: "\r")) + buffer.writeByte(UInt8(ascii: "\n")) + #expect(try appendSizes(buffer) == []) + + #expect(String(buffer: buffer.nextChunk().bytes) == "A1 NOOP\r\n") + #expect(try appendSizes(buffer) == [9]) + } + + #if canImport(ObjectiveC) + @Test("a string with no contiguous UTF-8 is written in full") + func writeForeignString() throws { + // A non-ASCII `NSString` bridges lazily, as UTF-16: its UTF-8 view isn't contiguous. + let foreign = try #require(NSString(utf8String: "Ünïcødé Mailbox 📬")) as String + try #require(foreign.utf8.withContiguousStorageIfAvailable { _ in } == nil) + var buffer = recordingBuffer() + #expect(buffer.writeString(foreign) == foreign.utf8.count) + #expect(String(buffer: buffer.nextChunk().bytes) == foreign) + } + #endif + + @Test("staged bytes count as pending, though the sink has not seen them") + func stagedBytesArePending() { + var buffer = recordingBuffer() + buffer.writeString("A1 NOOP\r\n") + #expect(buffer.sink.byteCount == 0) + #expect(buffer.pendingByteCount == 9) + + _ = buffer.nextChunk() + #expect(buffer.pendingByteCount == 0) + } + + @Test("a write of at least the staging size goes to the sink directly, after what is staged") + func stagingBoundary() throws { + let capacity = EncodeBuffer.stagingCapacity + var buffer = recordingBuffer() + buffer.writeByte(UInt8(ascii: "a")) + buffer.writeBytes([UInt8](repeating: UInt8(ascii: "b"), count: capacity)) + #expect(try appendSizes(buffer) == [1, capacity]) + + // Exactly filling the staging area still stages; the next byte flushes it. + buffer.writeBytes([UInt8](repeating: UInt8(ascii: "c"), count: capacity - 1)) + buffer.writeByte(UInt8(ascii: "d")) + #expect(try appendSizes(buffer) == [1, capacity]) + buffer.writeByte(UInt8(ascii: "e")) + #expect(try appendSizes(buffer) == [1, capacity, capacity]) + #expect(buffer.pendingByteCount == 1 + capacity + capacity + 1) + + let expected = + "a" + String(repeating: "b", count: capacity) + String(repeating: "c", count: capacity - 1) + "de" + #expect(String(buffer: buffer.nextChunk().bytes) == expected) + } + + @Test("a synchronizing literal splits chunks at the right byte while the bytes are staged") + func stopPointWithStagedBytes() { + var encoder = CommandEncodeBuffer(sink: RecordingOutputBuffer(), options: .rfc3501, loggingMode: false) + // An 8-bit username can't be quoted, so it is a literal. + encoder.writeCommand(TaggedCommand(tag: "A1", command: .login(username: "å", password: "pass"))) + #expect(encoder.buffer.sink.byteCount == 0, "everything is still staged") + + let first = encoder.nextChunk() + #expect(first.map { String(buffer: $0.bytes) } == "A1 LOGIN {2}\r\n") + #expect(first?.nextStep == .awaitContinuationRequest) + let second = encoder.nextChunk() + #expect(second.map { String(buffer: $0.bytes) } == "å \"pass\"\r\n") + #expect(second?.nextStep == .proceed) + #expect(encoder.nextChunk() == nil) + } + + @Test("a stop point at the last byte written splits there while the bytes are staged") + func trailingStopPointWithStagedBytes() { + var encoder = CommandEncodeBuffer(sink: RecordingOutputBuffer(), options: .rfc3501, loggingMode: false) + encoder.writeCommandStream(.append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 5))))) + #expect(encoder.buffer.sink.byteCount == 0, "everything is still staged") + + let header = encoder.nextChunk() + #expect(header.map { String(buffer: $0.bytes) } == " {5}\r\n") + #expect(header?.nextStep == .awaitContinuationRequest) + #expect(encoder.nextChunk() == nil) + + encoder.buffer.writeString("hello") + let message = encoder.nextChunk() + #expect(message.map { String(buffer: $0.bytes) } == "hello") + #expect(message?.nextStep == .proceed) + } + + @Test("staged bytes take part in equality and hashing") + func equalityWithStagedBytes() { + var staged = clientBuffer() + staged.writeString("A1 NOOP\r\n") + // Writing an `IMAPBuffer` flushes, so these bytes are in the sink rather than staged. + var flushed = clientBuffer() + flushed.writeString("A1 ") + flushed.writeBytes(IMAPBuffer(Array("NOOP\r\n".utf8))) + var different = clientBuffer() + different.writeString("A1 NOOQ\r\n") + + #expect(staged == flushed) + #expect(staged.hashValue == flushed.hashValue) + #expect(staged != different) + } + + /// ``equalityIgnoresSegmentation`` with more than ``EncodeBuffer/stagingCapacity`` bytes, so the + /// one-byte writes reach the tiny segments in several flushes rather than as one staged region. + @Test("equality ignores segmentation past the staging area too") + func equalityIgnoresSegmentationPastStaging() { + var fragmented = EncodeBuffer.clientEncodeBuffer( + sink: IMAPOutputBuffer(initialSegmentSize: 8, maximumSegmentSize: 8), + options: .rfc3501, + loggingMode: false + ) + var contiguous = clientBuffer() + let text = String(repeating: "abcdefgh", count: 100) + for character in text { + fragmented.writeString(String(character)) + } + contiguous.writeString(text) + + #expect(fragmented.makePendingBufferList().regionCount > contiguous.makePendingBufferList().regionCount) + #expect(fragmented == contiguous) + #expect(fragmented.hashValue == contiguous.hashValue) + } + + /// ``writingAnArrayStaysInOneRegion`` with more than ``EncodeBuffer/stagingCapacity`` bytes, so + /// the array reaches the sink in several appends, which a spurious copy would split into segments. + @Test("writing an array longer than the staging area does not fragment the output") + func writingALongArrayStaysInOneRegion() { + // Room for the whole output in one segment. + let segmentSize = 4096 + var buffer = EncodeBuffer.serverEncodeBuffer( + sink: IMAPOutputBuffer(initialSegmentSize: segmentSize, maximumSegmentSize: segmentSize), + options: ResponseEncodingOptions(), + loggingMode: false + ) + let flags = (0..<100).compactMap { Flag("keyword\($0)") } + buffer.writeMessageAttribute(.flags(flags)) + let chunk = buffer.nextChunk() + #expect(chunk.bytes.byteCount > EncodeBuffer.stagingCapacity) + #expect(chunk.bytes.regionCount == 1) + } + + @Test("a large region written after staged bytes follows them, by reference") + func largeRegionAfterStagedBytes() throws { + var buffer = clientBuffer() + let payload = IMAPBuffer([UInt8](repeating: UInt8(ascii: "z"), count: IMAPBuffer.copyThreshold)) + buffer.writeString("A1 ") + buffer.writeBytes(payload) + buffer.writeString("\r\n") + + let chunk = buffer.nextChunk() + #expect(String(buffer: chunk.bytes) == "A1 " + String(repeating: "z", count: IMAPBuffer.copyThreshold) + "\r\n") + let regions = Array(chunk.bytes.regions) + try #require(regions.count == 3) + let address = { (region: IMAPBuffer) in + region.withUnsafeBytesAndOwner { bytes, _ in UnsafeRawPointer(bytes.baseAddress) } + } + #expect(address(regions[1]) == address(payload), "the payload is not copied") + } +} + +/// The simplest possible ``EncoderOutputBuffer``: a byte array. +/// +/// It exists to check that the protocol is usable from outside the package — that a caller who wants +/// the bytes somewhere else does not need any of ``IMAPOutputBuffer``'s machinery, only the six +/// members below. +private struct CollectingOutputBuffer: EncoderOutputBuffer { + private var bytes: [UInt8] = [] + + var byteCount: Int { bytes.count } + + mutating func append(_ bytes: UnsafeRawBufferPointer) { + self.bytes.append(contentsOf: bytes) + } + + mutating func append(_ region: IMAPBuffer) { + region.withUnsafeBytes { self.bytes.append(contentsOf: $0) } + } + + mutating func takeFirst(_ byteCount: Int) -> IMAPBufferList { + let taken = Array(bytes.prefix(byteCount)) + bytes.removeFirst(byteCount) + return IMAPBufferList(IMAPBuffer(taken)) + } + + func withPendingRegions(_ body: (Span) -> R) -> R { + let regions: ContiguousArray = [IMAPBuffer(bytes)] + return body(regions.span) + } + + mutating func removeAll() { + bytes = [] + } +} + +/// A byte-array sink that records the size of every `append`, to observe what the encoder stages. +private struct RecordingOutputBuffer: EncoderOutputBuffer { + private var bytes: [UInt8] = [] + private(set) var appendSizes: [Int] = [] + + var byteCount: Int { bytes.count } + + mutating func append(_ bytes: UnsafeRawBufferPointer) { + appendSizes.append(bytes.count) + self.bytes.append(contentsOf: bytes) + } + + mutating func append(_ region: IMAPBuffer) { + appendSizes.append(region.count) + region.withUnsafeBytes { self.bytes.append(contentsOf: $0) } + } + + mutating func takeFirst(_ byteCount: Int) -> IMAPBufferList { + let taken = Array(bytes.prefix(byteCount)) + bytes.removeFirst(byteCount) + return IMAPBufferList(IMAPBuffer(taken)) + } + + func withPendingRegions(_ body: (Span) -> R) -> R { + let regions: ContiguousArray = [IMAPBuffer(bytes)] + return body(regions.span) + } + + mutating func removeAll() { + bytes = [] + } +} diff --git a/Tests/NIOIMAPCoreTests/EncodeFixture.swift b/Tests/NIOIMAPCoreTests/EncodeFixture.swift index 9166089f..a0f41d9a 100644 --- a/Tests/NIOIMAPCoreTests/EncodeFixture.swift +++ b/Tests/NIOIMAPCoreTests/EncodeFixture.swift @@ -60,13 +60,11 @@ extension EncodeFixture { switch bufferKind { case .client(let options): testBuffer = EncodeBuffer.clientEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: options, loggingMode: false ) case .server(let options): testBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: options, loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift index 7158e768..6896e6a5 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift @@ -51,7 +51,6 @@ struct AppendDataTests { processExitsWith: ExitTest.Condition.failure, performing: { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift index 0a81f802..884c997b 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift @@ -68,7 +68,6 @@ struct BodyFieldEncodingTests { func nilEncodingEncodesAsNIL() { let expected = "NIL" var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 32), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/CharacterSetName+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CharacterSetName+Tests.swift index 98012953..e1bbf290 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CharacterSetName+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CharacterSetName+Tests.swift @@ -156,14 +156,13 @@ private let validNameStrings = [ /// Encodes `command` (client mode), parses the bytes back, and expects the original command. private func expectCommandRoundTrip(_ command: Command, sourceLocation: SourceLocation = #_sourceLocation) { - var encodeBuffer = CommandEncodeBuffer(buffer: ByteBuffer(), options: CommandEncodingOptions(), loggingMode: false) + var encodeBuffer = CommandEncodeBuffer(options: CommandEncodingOptions(), loggingMode: false) _ = encodeBuffer.writeCommand(command) var encoded = ByteBuffer() var remaining = encodeBuffer.buffer while true { let chunk = remaining.nextChunk() - var bytes = chunk.bytes - encoded.writeBuffer(&bytes) + encoded.writeBytes(chunk.bytes.copiedBytes()) if !chunk.waitForContinuation { break } } encoded.writeString("\r") diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift index 45e344f7..17ae7ee4 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift @@ -58,7 +58,7 @@ private struct CommandStreamTests { .finish, ] - var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: false) + var buffer = CommandEncodeBuffer(capabilities: [], loggingMode: false) parts.map { CommandStreamPart.append($0) }.forEach { buffer.writeCommandStream($0) } @@ -85,7 +85,7 @@ private struct CommandStreamTests { var options = CommandEncodingOptions() options.useNonSynchronizingLiteralPlus = true - var buffer = CommandEncodeBuffer(buffer: "", options: options, loggingMode: false) + var buffer = CommandEncodeBuffer(options: options, loggingMode: false) parts.map { CommandStreamPart.append($0) }.forEach { buffer.writeCommandStream($0) } @@ -120,7 +120,7 @@ private struct CommandStreamTests { .finish, ] - var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: false) + var buffer = CommandEncodeBuffer(capabilities: [], loggingMode: false) parts.map { CommandStreamPart.append($0) }.forEach { buffer.writeCommandStream($0) } @@ -187,7 +187,7 @@ private struct CommandStreamTests { var options = CommandEncodingOptions() options.useNonSynchronizingLiteralPlus = true - var buffer = CommandEncodeBuffer(buffer: "", options: options, loggingMode: false) + var buffer = CommandEncodeBuffer(options: options, loggingMode: false) parts.map { CommandStreamPart.append($0) }.forEach { buffer.writeCommandStream($0) } @@ -216,7 +216,7 @@ private struct CommandStreamTests { ] // Apply parts twice. - var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: false) + var buffer = CommandEncodeBuffer(capabilities: [], loggingMode: false) (parts + parts).map { CommandStreamPart.append($0) }.forEach { buffer.writeCommandStream($0) } @@ -329,7 +329,7 @@ private struct CommandStreamTests { @Test("writeAppendCommand in loggingMode for messageBytes") func writeAppendCommandLoggingModeMessageBytes() { - var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: true) + var buffer = CommandEncodeBuffer(capabilities: [], loggingMode: true) let count = buffer.writeCommandStream(.append(.messageBytes("hello"))) #expect(count == 0) #expect(String(buffer: buffer.buffer.nextChunk().bytes) == "") @@ -337,7 +337,7 @@ private struct CommandStreamTests { @Test("writeAppendCommand in loggingMode for endMessage") func writeAppendCommandLoggingModeEndMessage() { - var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: true) + var buffer = CommandEncodeBuffer(capabilities: [], loggingMode: true) let count = buffer.writeCommandStream(.append(.endMessage)) #expect(count > 0) let chunk = buffer.buffer.nextChunk() diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandTag+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandTag+Tests.swift index d732d49e..7e4f3b3a 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandTag+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandTag+Tests.swift @@ -53,9 +53,9 @@ struct CommandTagTests { @Test("valid tags round-trip in a command", arguments: validTagStrings) func commandRoundTrip(_ string: String) throws { let tag = try #require(Command.Tag(string)) - var encodeBuffer = CommandEncodeBuffer(buffer: ByteBuffer(), options: .rfc3501, loggingMode: false) + var encodeBuffer = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) encodeBuffer.writeCommand(TaggedCommand(tag: tag, command: .noop)) - var buffer = ParseBuffer(encodeBuffer.buffer.nextChunk().bytes) + var buffer = ParseBuffer(ByteBuffer(bytes: encodeBuffer.buffer.nextChunk().bytes.copiedBytes())) let parsed = try GrammarParser().parseTaggedCommand(buffer: &buffer, tracker: .testTracker) #expect(parsed == TaggedCommand(tag: tag, command: .noop)) } @@ -63,9 +63,9 @@ struct CommandTagTests { @Test("valid tags round-trip in an APPEND", arguments: validTagStrings) func appendRoundTrip(_ string: String) throws { let tag = try #require(Command.Tag(string)) - var encodeBuffer = CommandEncodeBuffer(buffer: ByteBuffer(), options: .rfc3501, loggingMode: false) + var encodeBuffer = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) encodeBuffer.writeCommandStream(.append(.start(tag: tag, appendingTo: .inbox))) - var bytes = encodeBuffer.buffer.nextChunk().bytes + var bytes = ByteBuffer(bytes: encodeBuffer.buffer.nextChunk().bytes.copiedBytes()) bytes.writeString(" ") var buffer = ParseBuffer(bytes) let parsed = try GrammarParser().parseAppend(buffer: &buffer, tracker: .testTracker) diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift index aff19c1f..cdf014c7 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift @@ -294,7 +294,6 @@ struct CommandTypeTests { @Test("authenticate with initialResponse in loggingMode") func authenticateWithInitialResponseLoggingMode() { var buffer = CommandEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 64), capabilities: [], loggingMode: true ) @@ -305,7 +304,6 @@ struct CommandTypeTests { @Test("login credentials redacted in loggingMode") func loginCredentialsRedactedInLoggingMode() { var buffer = CommandEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 64), capabilities: [], loggingMode: true ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift index 2dd20ed0..719308cd 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift @@ -22,7 +22,6 @@ struct ConditionalStoreTests { func encodesToCondstore() { let expected = "CONDSTORE" var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift b/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift index 5b60ca98..1be7f072 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift @@ -297,7 +297,6 @@ struct EmailAddressFixture: Sendable, CustomTestStringConvertible { func checkEncoding() { let buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/EnvelopeTests.swift b/Tests/NIOIMAPCoreTests/Grammar/EnvelopeTests.swift index df251ab2..afed515c 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/EnvelopeTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/EnvelopeTests.swift @@ -303,7 +303,6 @@ struct EnvelopeTests { private static func encodeAddressList(_ addresses: [EmailAddressListElement]) -> String { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Expire+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Expire+Tests.swift index bcf87e1f..0b7e29f1 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Expire+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Expire+Tests.swift @@ -97,7 +97,6 @@ struct ExpireTests { let parsed = try GrammarParser().parseExpire(buffer: &parseBuffer, tracker: .testTracker) #expect(parseBuffer.readableBytes == terminator.utf8.count) var encodeBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift index 952887ef..29ad04e8 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift @@ -187,7 +187,6 @@ struct FullDateTimeTests { var parseBuffer = ParseBuffer(ByteBuffer(string: input + " ")) let parsed = try GrammarParser().parseFullTime(buffer: &parseBuffer, tracker: .testTracker) var encodeBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) @@ -231,7 +230,6 @@ struct FullDateTimeTests { observing: [\.standardErrorContent], performing: { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift index c9e2aa54..575e5f54 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift @@ -540,7 +540,6 @@ extension MessageAttributeTests { ) func encodeRfc822Helpers(_ fixture: Rfc822Fixture) { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) @@ -564,7 +563,6 @@ extension MessageAttributeTests { ) func encodeBodySectionText(_ fixture: BodySectionTextFixture) { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) @@ -641,7 +639,6 @@ struct BodySectionFixture: Sendable, CustomTestStringConvertible { func checkEncoding() { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift index dbf46842..95ebdac7 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift @@ -57,7 +57,6 @@ struct NamespaceDescriptionTests { @Test("logging mode shows the delimiter") func loggingMode() throws { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: true ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/ContinuationRequestTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/ContinuationRequestTests.swift index 545035a2..eedaadb1 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/ContinuationRequestTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/ContinuationRequestTests.swift @@ -88,11 +88,7 @@ extension EncodeFixture { bufferKind: .server(ResponseEncodingOptions()), expectedString: expectedString, encoder: { - var encoder = ResponseEncodeBuffer( - buffer: $0.buffer, - options: ResponseEncodingOptions(), - loggingMode: false - ) + var encoder = ResponseEncodeBuffer($0) let count = encoder.writeContinuationRequest($1) $0 = encoder.buffer return count diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift index 4bd64151..a2ca0676 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift @@ -252,11 +252,7 @@ extension EncodeFixture { bufferKind: .server(ResponseEncodingOptions()), expectedString: expectedString, encoder: { - var encoder = ResponseEncodeBuffer( - buffer: $0.buffer, - options: ResponseEncodingOptions(), - loggingMode: false - ) + var encoder = ResponseEncodeBuffer($0) let count = encoder.writeResponse($1) $0 = encoder.buffer return count @@ -272,14 +268,10 @@ extension EncodeFixture<[FetchResponse]> { ) -> Self { EncodeFixture( input: input, - bufferKind: .client(.rfc3501), + bufferKind: .server(ResponseEncodingOptions()), expectedString: expectedString, encoder: { - var encoder = ResponseEncodeBuffer( - buffer: $0.buffer, - options: ResponseEncodingOptions(), - loggingMode: false - ) + var encoder = ResponseEncodeBuffer($0) let count = $1.reduce(into: 0) { count, response in count += encoder.writeFetchResponse(response) } diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseText+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseText+Tests.swift index 8e7ecb9d..db87eb80 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseText+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseText+Tests.swift @@ -50,7 +50,6 @@ struct ResponseTextTests { observing: [\.standardErrorContent], performing: { [string = string as String] in var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift index f61438fa..9ecc99a0 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift @@ -146,7 +146,6 @@ struct UIDRangeTests { @Test("range operator prefix") func rangeOperatorPrefix() { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) @@ -161,7 +160,6 @@ struct UIDRangeTests { @Test("range operator postfix") func rangeOperatorPostfix() { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) @@ -176,7 +174,6 @@ struct UIDRangeTests { @Test("range operator postfix complete right larger") func rangeOperatorPostfixCompleteRightLarger() { var buffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift b/Tests/NIOIMAPCoreTests/Grammar/WriteLiteralTests.swift similarity index 96% rename from Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift rename to Tests/NIOIMAPCoreTests/Grammar/WriteLiteralTests.swift index 3d959abb..08af4f4a 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/WriteLiteralTests.swift @@ -16,8 +16,8 @@ import NIO @_spi(NIOIMAPInternal) @testable import NIOIMAPCore import Testing -@Suite("ByteBuffer Literal Writing") -struct ByteBufferWriteLiteralTests { +@Suite("Literal Writing") +struct WriteLiteralTests { @Test( "writeIMAPString with client buffers", arguments: [ @@ -122,7 +122,6 @@ struct ByteBufferWriteLiteralTests { func writeIMAPStringLoggingMode() { // quoted string in logging mode → "∅" (with enclosing quotes) var quotedBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: ResponseEncodingOptions(), loggingMode: true ) @@ -136,7 +135,6 @@ struct ByteBufferWriteLiteralTests { var serverOptions = ResponseEncodingOptions() serverOptions.useQuotedString = false var serverLiteralBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: serverOptions, loggingMode: true ) @@ -148,7 +146,6 @@ struct ByteBufferWriteLiteralTests { // client synchronizing literal in logging mode var clientSyncBuffer = EncodeBuffer.clientEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: CommandEncodingOptions(useQuotedString: false, useSynchronizingLiteral: true), loggingMode: true ) @@ -160,7 +157,6 @@ struct ByteBufferWriteLiteralTests { // client non-synchronizing literal in logging mode var clientNonSyncBuffer = EncodeBuffer.clientEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 128), options: CommandEncodingOptions( useQuotedString: false, useSynchronizingLiteral: false, diff --git a/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Stream+Tests.swift b/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Stream+Tests.swift index 1ff75c0f..17916a89 100644 --- a/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Stream+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Stream+Tests.swift @@ -1400,7 +1400,6 @@ private enum DeepEnvelope { let secondFrom = ResponseParserTests.envelopes(in: second.responses).first?.from ?? [] var encoder = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBufferAllocator().buffer(capacity: 1 << 20), options: ResponseEncodingOptions(), loggingMode: false ) diff --git a/Tests/NIOIMAPCoreTests/Parser/RoundtripTests.swift b/Tests/NIOIMAPCoreTests/Parser/RoundtripTests.swift index ff359299..bb049193 100644 --- a/Tests/NIOIMAPCoreTests/Parser/RoundtripTests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/RoundtripTests.swift @@ -185,24 +185,24 @@ private enum RoundtripTests { ] ) static func commandRoundtrip(_ fixture: RoundtripFixture) throws { - var encodeBuffer = CommandEncodeBuffer(buffer: ByteBuffer(), options: .init(), loggingMode: false) + var encodeBuffer = CommandEncodeBuffer(options: .init(), loggingMode: false) let tag: Command.Tag = "1" let taggedCommand = TaggedCommand(tag: tag, command: fixture.command) encodeBuffer.writeCommand(taggedCommand) // required for commands that might terminate with a literal (e.g. append) encodeBuffer.buffer.writeString("\r\n") - var buffer = ByteBufferAllocator().buffer(capacity: 128) + var bytes: [UInt8] = [] + bytes.reserveCapacity(128) while true { let next = encodeBuffer.buffer.nextChunk() - var toSend = next.bytes - buffer.writeBuffer(&toSend) + bytes.append(contentsOf: next.bytes.copiedBytes()) if !next.waitForContinuation { break } } - var parseBuffer = ParseBuffer(buffer) + var parseBuffer = ParseBuffer(ByteBuffer(bytes: bytes)) let decoded = try GrammarParser().parseTaggedCommand(buffer: &parseBuffer, tracker: .testTracker) #expect(decoded == taggedCommand, "Decoded command should match original") } diff --git a/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift b/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift index 01cb036b..c7b7aefb 100644 --- a/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift +++ b/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift @@ -21,7 +21,7 @@ struct ResponseEncodeBufferTests { @Test("correctly streams many simple attributes with spaces") func correctlyStreamsManySimpleAttributesWithSpaces() { // Previously had a bug where spaces weren't inserted between attributes - var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(string: ""), options: .rfc3501, loggingMode: false) + var buffer = ResponseEncodeBuffer(options: .rfc3501, loggingMode: false) buffer.writeFetchResponse(.start(1)) buffer.writeFetchResponse(.simpleAttribute(.flags([.answered]))) buffer.writeFetchResponse(.simpleAttribute(.uid(999))) @@ -34,7 +34,7 @@ struct ResponseEncodeBufferTests { @Test("correctly handles fetch streaming with literal data") func correctlyHandlesFetchStreamingWithLiteralData() { - var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(string: ""), options: .rfc3501, loggingMode: false) + var buffer = ResponseEncodeBuffer(options: .rfc3501, loggingMode: false) buffer.writeFetchResponse(.start(1)) buffer.writeFetchResponse(.streamingBegin(kind: .body(section: .complete, offset: nil), byteCount: 10)) buffer.writeFetchResponse(.streamingBytes(ByteBuffer(string: "0123456789"))) @@ -47,7 +47,7 @@ struct ResponseEncodeBufferTests { @Test("init with capabilities") func initWithCapabilities() { - var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(), capabilities: [.imap4rev1], loggingMode: false) + var buffer = ResponseEncodeBuffer(capabilities: [.imap4rev1], loggingMode: false) buffer.writeFetchResponse(.start(1)) buffer.writeFetchResponse(.finish) let outputString = String(buffer: buffer.readBytes()) @@ -56,7 +56,7 @@ struct ResponseEncodeBufferTests { @Test("correctly streams binary attribute") func correctlyStreamsBinaryAttribute() { - var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(string: ""), options: .rfc3501, loggingMode: false) + var buffer = ResponseEncodeBuffer(options: .rfc3501, loggingMode: false) buffer.writeFetchResponse(.start(1)) buffer.writeFetchResponse(.streamingBegin(kind: .binary(section: [], offset: nil), byteCount: 5)) buffer.writeFetchResponse(.streamingBytes(ByteBuffer(string: "hello"))) @@ -65,4 +65,41 @@ struct ResponseEncodeBufferTests { let outputString = String(buffer: buffer.readBytes()) #expect(outputString == "* 1 FETCH (BINARY {5}\r\nhello)\r\n") } + + /// A server handler keeps one of these for the whole connection and drains it after every + /// response, so anything `readBytes()` fails to release accumulates for the life of the + /// connection. The bytes it already handed out have to survive that, which they do because a + /// handed-out region keeps its own storage alive. + @Test("readBytes drains the buffer without disturbing what it handed out") + func readBytesDrains() { + var buffer = ResponseEncodeBuffer(options: .rfc3501, loggingMode: false) + buffer.writeResponse(.tagged(.init(tag: "A1", state: .ok(.init(text: "first"))))) + let first = buffer.readBytes() + #expect(buffer.readBytes().byteCount == 0) + + buffer.writeResponse(.tagged(.init(tag: "A2", state: .ok(.init(text: "second"))))) + let second = buffer.readBytes() + + #expect(String(buffer: first) == "A1 OK first\r\n") + #expect(String(buffer: second) == "A2 OK second\r\n") + } + + @Test("the encoder writes into a sink the caller supplies") + func customSink() { + var buffer = ResponseEncodeBuffer( + sink: IMAPOutputBuffer(initialSegmentSize: 4, maximumSegmentSize: 4), + options: .rfc3501, + loggingMode: false + ) + // Longer than the encoder stages before appending (`EncodeBuffer.stagingCapacity`, SPI, so + // spelled here), so the sink gets several appends; four-byte segments leave no room to merge + // them, so the response arrives as several regions rather than one — and reads back the same + // either way. + let longerThanStaging = 512 + let text = String(repeating: "x", count: longerThanStaging) + buffer.writeResponse(.tagged(.init(tag: "A1", state: .ok(.init(text: text))))) + let bytes = buffer.readBytes() + #expect(bytes.regionCount > 1) + #expect(String(buffer: bytes) == "A1 OK \(text)\r\n") + } } diff --git a/Tests/NIOIMAPCoreTests/TestUtilities.swift b/Tests/NIOIMAPCoreTests/TestUtilities.swift index 446c3b2d..9142f17d 100644 --- a/Tests/NIOIMAPCoreTests/TestUtilities.swift +++ b/Tests/NIOIMAPCoreTests/TestUtilities.swift @@ -247,13 +247,9 @@ extension TestUtilities { parser: (inout ParseBuffer, StackTracker) throws -> T, sourceLocation: SourceLocation = #_sourceLocation ) { - var encodeBuffer = EncodeBuffer.serverEncodeBuffer( - buffer: ByteBuffer(), - options: ResponseEncodingOptions(), - loggingMode: false - ) + var encodeBuffer = EncodeBuffer.serverEncodeBuffer(options: ResponseEncodingOptions(), loggingMode: false) _ = encoder(&encodeBuffer, value) - var encoded = encodeBuffer.nextChunk().bytes + var encoded = ByteBuffer(bytes: encodeBuffer.nextChunk().bytes.copiedBytes()) encoded.writeString(terminator) let encodedString = String(buffer: encoded) var parseBuffer = ParseBuffer(encoded) @@ -296,3 +292,21 @@ extension TestUtilities { } } #endif + +// Encoded chunks are `IMAPBufferList`s. This mirrors NIO's `String(buffer:)` so a test can read a +// chunk the same way it used to read a `ByteBuffer`. +extension String { + init(buffer list: IMAPBufferList) { + self = String(decoding: list.copiedBytes(), as: UTF8.self) + } +} + +// Encoded chunks are compared against string literals in a few places. A literal makes a one-region +// list, and `IMAPBufferList` equality is byte-wise, so it matches however the sink split the bytes up. +extension IMAPBufferList: ExpressibleByUnicodeScalarLiteral {} +extension IMAPBufferList: ExpressibleByExtendedGraphemeClusterLiteral {} +extension IMAPBufferList: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self = IMAPBufferList(IMAPBuffer(Array(value.utf8))) + } +} diff --git a/Tests/NIOIMAPCoreTests/ThirdPartyTransportTests.swift b/Tests/NIOIMAPCoreTests/ThirdPartyTransportTests.swift new file mode 100644 index 00000000..4b53608b --- /dev/null +++ b/Tests/NIOIMAPCoreTests/ThirdPartyTransportTests.swift @@ -0,0 +1,123 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 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 +// +//===----------------------------------------------------------------------===// + +// Public API only — no `@testable`, no `@_spi`: this file is what a client with its own transport can +// do, and must keep compiling as such. +import NIOIMAPCore +import Testing + +/// A third-party sink that hands every byte out as a region of its own: the most regions a sink can. +private struct OneRegionPerByteSink: EncoderOutputBuffer { + private var bytes: [UInt8] = [] + + var byteCount: Int { bytes.count } + + mutating func append(_ bytes: UnsafeRawBufferPointer) { + self.bytes.append(contentsOf: bytes) + } + + mutating func append(_ region: IMAPBuffer) { + region.withUnsafeBytes { bytes.append(contentsOf: $0) } + } + + mutating func takeFirst(_ byteCount: Int) -> IMAPBufferList { + let taken = bytes.prefix(byteCount).map { IMAPBuffer([$0]) } + bytes.removeFirst(byteCount) + return IMAPBufferList(taken) + } + + func withPendingRegions(_ body: (Span) -> R) -> R { + let regions = ContiguousArray(bytes.map { IMAPBuffer([$0]) }) + return body(regions.span) + } + + mutating func removeAll() { + bytes = [] + } +} + +/// Drains `encoder` the way a client with its own transport does. +private func drain(_ encoder: inout CommandEncodeBuffer) -> [(wire: String, nextStep: CommandEncodeBuffer.NextStep)] { + var chunks: [(wire: String, nextStep: CommandEncodeBuffer.NextStep)] = [] + while let chunk = encoder.nextChunk() { + chunks.append((String(decoding: chunk.bytes.copiedBytes(), as: UTF8.self), chunk.nextStep)) + } + return chunks +} + +/// Command chunks for a client that writes to the network itself, e.g. over `Network.framework`. +@Suite("CommandEncodeBuffer chunks for a third-party transport") +struct ThirdPartyTransportTests { + /// An 8-bit username can't be quoted, so it is a literal. + static let login = TaggedCommand(tag: "A1", command: .login(username: "å", password: "pass")) + + /// The most regions the encoder hands out in one chunk. Internal to the library, so spelled here. + static let encoderRegionCap = 64 + + @Test("a synchronizing literal ends a chunk that awaits +") + func synchronizingLiteral() { + var encoder = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) + encoder.writeCommand(Self.login) + let chunks = drain(&encoder) + #expect(chunks.map(\.wire) == ["A1 LOGIN {2}\r\n", "å \"pass\"\r\n"]) + #expect(chunks.map(\.nextStep) == [.awaitContinuationRequest, .proceed]) + #expect(encoder.nextChunk() == nil) + } + + @Test("a LITERAL+ literal doesn't end a chunk") + func literalPlus() { + var encoder = CommandEncodeBuffer(capabilities: [.literalPlus], loggingMode: false) + encoder.writeCommand(Self.login) + let chunks = drain(&encoder) + #expect(chunks.map(\.wire) == ["A1 LOGIN {2+}\r\nå \"pass\"\r\n"]) + #expect(chunks.map(\.nextStep) == [.proceed]) + } + + /// The chunk ends at the last byte written, yet the message bytes, once written, follow the `+`. + @Test("APPEND's message literal header awaits +") + func appendBeginMessage() { + var encoder = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) + encoder.writeCommandStream(.append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 5))))) + let chunks = drain(&encoder) + #expect(chunks.map(\.wire) == [" {5}\r\n"]) + #expect(chunks.map(\.nextStep) == [.awaitContinuationRequest]) + } + + @Test("CATENATE's data literal header awaits + without LITERAL+") + func catenateDataBegin() { + var encoder = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) + encoder.writeCommandStream(.append(.catenateData(.begin(size: 5)))) + let chunks = drain(&encoder) + #expect(chunks.map(\.wire) == ["TEXT {5}\r\n"]) + #expect(chunks.map(\.nextStep) == [.awaitContinuationRequest]) + } + + @Test("an empty encoder has no chunk") + func emptyEncoder() { + var encoder = CommandEncodeBuffer(options: .rfc3501, loggingMode: false) + #expect(encoder.nextChunk() == nil) + } + + @Test("the encoder caps the regions a sink of your own hands it") + func encoderCapsForeignSink() throws { + var encoder = CommandEncodeBuffer(sink: OneRegionPerByteSink(), options: .rfc3501, loggingMode: false) + let mailbox = String(repeating: "x", count: Self.encoderRegionCap) + encoder.writeCommand(TaggedCommand(tag: "A1", command: .create(MailboxName(Array(mailbox.utf8)), []))) + let next = encoder.nextChunk() + let chunk = try #require(next) + #expect(chunk.bytes.regionCount == Self.encoderRegionCap) + #expect(chunk.bytes.copiedBytes() == Array("A1 CREATE \"\(mailbox)\"\r\n".utf8)) + #expect(chunk.nextStep == .proceed) + } +} diff --git a/Tests/NIOIMAPTests/Bytes/ByteBufferOutputTests.swift b/Tests/NIOIMAPTests/Bytes/ByteBufferOutputTests.swift deleted file mode 100644 index 4eb20e56..00000000 --- a/Tests/NIOIMAPTests/Bytes/ByteBufferOutputTests.swift +++ /dev/null @@ -1,472 +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 Testing - -@_spi(NIOIMAPInternal) @testable import NIOIMAP -@_spi(NIOIMAPInternal) import NIOIMAPCore - -extension ByteBufferOutput { - /// Appends bytes, spelled for readability in tests. - fileprivate mutating func appendBytes(_ bytes: [UInt8]) { - bytes.withUnsafeBytes { append($0) } - } - - /// A run of `count` distinct-ish bytes, so that a misplaced range shows up as wrong content. - fileprivate static func pattern(_ count: Int, seed: UInt8 = 0) -> [UInt8] { - (0.. UInt { - region.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) } -} - -/// The address of a `ByteBuffer`'s first readable byte. -private func address(of buffer: ByteBuffer) -> UInt { - buffer.withUnsafeReadableBytes { UInt(bitPattern: $0.baseAddress) } -} - -@Suite("ByteBufferOutput") -struct ByteBufferOutputTests { - - // MARK: - Appending and byteCount - - @Test("a fresh buffer holds nothing and has allocated nothing") - func fresh() { - let buffer = ByteBufferOutput() - #expect(buffer.byteCount == 0) - #expect(buffer.pendingRegionCount == 0) - #expect(buffer.writeBufferIdentity.capacity == 0, "creating a sink must not allocate") - } - - @Test("appending nothing allocates nothing") - func appendEmpty() { - var buffer = ByteBufferOutput() - buffer.appendBytes([]) - buffer.append(IMAPBuffer()) - #expect(buffer.byteCount == 0) - #expect(buffer.pendingRegionCount == 0) - #expect(buffer.writeBufferIdentity.capacity == 0) - } - - @Test("consecutive writes coalesce into one region") - func coalescing() { - var buffer = ByteBufferOutput() - buffer.append("A001 SELECT ") - buffer.append("INBOX") - buffer.append("\r\n") - #expect(buffer.byteCount == 19) - // A command written as many small writes is one region, hence one write to the network. - #expect(buffer.pendingRegionCount == 1) - #expect(buffer.takeFirst(19).string == "A001 SELECT INBOX\r\n") - } - - @Test("byteCount counts pending bytes and goes down as they are handed out") - func byteCountIsPending() { - var buffer = ByteBufferOutput() - buffer.append("0123456789") - #expect(buffer.byteCount == 10) - _ = buffer.takeFirst(4) - #expect(buffer.byteCount == 6) - buffer.append("abc") - #expect(buffer.byteCount == 9) - _ = buffer.takeFirst(9) - #expect(buffer.byteCount == 0) - } - - @Test("a write larger than the buffer grows it in one step") - func largeWrite() { - var buffer = ByteBufferOutput() - let bytes = ByteBufferOutput.pattern(100_000) - buffer.appendBytes(bytes) - #expect(buffer.pendingRegionCount == 1) - #expect(buffer.takeFirst(100_000).copiedBytes() == bytes) - } - - @Test("appending a string with no contiguous UTF-8 still appends its bytes") - func appendForeignString() { - var buffer = ByteBufferOutput() - let name = "Ünïcødé Mailbox 📬" - let written = buffer.append(name) - #expect(written == name.utf8.count) - #expect(buffer.takeFirst(buffer.byteCount).copiedBytes() == Array(name.utf8)) - } - - // MARK: - Handing out - - @Test("a handed-out region is a slice of the buffer it was written into, not a copy") - func handOutIsZeroCopy() { - var buffer = ByteBufferOutput() - buffer.append("A001 NOOP\r\n") - let written = buffer.writeBufferIdentity.address - - let chunk = buffer.takeFirst(buffer.byteCount) - #expect(chunk.regionCount == 1) - #expect(address(of: chunk.regions[0]) == written, "the chunk should point at the encoded bytes") - - // ...and recovering a `ByteBuffer` from it shares that storage too, which is the whole point: - // the bytes are copied once, on their way in, and never again. - let recovered = chunk.regions[0].byteBuffer - #expect(address(of: recovered) == written) - #expect(String(buffer: recovered) == "A001 NOOP\r\n") - } - - @Test("takeFirst splits the pending bytes and the remainder is still correct") - func takeFirstSplits() { - var buffer = ByteBufferOutput() - buffer.append("HELLO WORLD") - - let first = buffer.takeFirst(5) - #expect(first.string == "HELLO") - #expect(buffer.byteCount == 6) - - let second = buffer.takeFirst(6) - #expect(second.string == " WORLD") - #expect(buffer.byteCount == 0) - #expect(first.string == "HELLO", "the first chunk must not have moved underneath") - } - - @Test("takeFirst of nothing is an empty list, and does not touch what is pending") - func takeFirstZero() { - var buffer = ByteBufferOutput() - buffer.append("XYZ") - let chunk = buffer.takeFirst(0) - #expect(chunk.byteCount == 0) - #expect(chunk.regionCount == 0) - #expect(buffer.byteCount == 3) - } - - @Test("bytes already handed out do not change as encoding continues") - func handedOutBytesAreImmutable() { - var buffer = ByteBufferOutput() - buffer.append("A001 APPEND ") - let chunk = buffer.takeFirst(buffer.byteCount) - #expect(chunk.string == "A001 APPEND ") - - buffer.append("INBOX {3}\r\n") - buffer.append("abc") - #expect(buffer.takeFirst(buffer.byteCount).string == "INBOX {3}\r\nabc") - - #expect(chunk.string == "A001 APPEND ") - } - - @Test("the synchronizing-literal shape: hand out a prefix, keep writing, hand out the rest") - func synchronizingLiteralShape() { - var buffer = ByteBufferOutput() - buffer.append("A001 LOGIN {4}\r\n") - buffer.append("user") // written before the first chunk goes out, and handed out after it - let first = buffer.takeFirst(16) - #expect(first.string == "A001 LOGIN {4}\r\n") - #expect(buffer.byteCount == 4) - - buffer.append(" {4}\r\n") - let second = buffer.takeFirst(buffer.byteCount) - #expect(second.string == "user {4}\r\n") - #expect(first.string == "A001 LOGIN {4}\r\n") - // The bytes carried over joined the ones written after them, rather than staying a region of - // their own. - #expect(second.regionCount == 1) - } - - @Test("a chunk keeps its bytes alive after the sink has gone away") - func chunkOutlivesTheSink() { - var chunk = IMAPBufferList() - do { - var buffer = ByteBufferOutput() - buffer.append("kept alive") - chunk = buffer.takeFirst(buffer.byteCount) - buffer.removeAll() - } - #expect(chunk.string == "kept alive") - } - - // MARK: - Recycling - - @Test("the buffer is reused once the bytes handed out of it have been released") - func reusesTheBufferWhenNothingRefersToIt() { - var buffer = ByteBufferOutput() - buffer.append("first response\r\n") - let first = buffer.writeBufferIdentity.address - // Take the chunk and drop it immediately, as a channel does once the write has completed. - #expect(buffer.takeFirst(buffer.byteCount).byteCount == 16) - buffer.removeAll() - - buffer.append("second response\r\n") - #expect(buffer.writeBufferIdentity.address == first, "a drained buffer should be written again") - #expect(buffer.takeFirst(buffer.byteCount).string == "second response\r\n") - } - - @Test("a buffer whose bytes are still in flight is not written into again") - func doesNotWriteIntoBytesStillInFlight() { - var buffer = ByteBufferOutput() - buffer.append("in flight\r\n") - let first = buffer.writeBufferIdentity.address - let chunk = buffer.takeFirst(buffer.byteCount) - - buffer.append("next\r\n") - #expect(buffer.writeBufferIdentity.address != first) - #expect(chunk.string == "in flight\r\n", "the bytes in flight must be untouched") - #expect(buffer.takeFirst(buffer.byteCount).string == "next\r\n") - } - - @Test("a buffer grown for one large message is not held for the rest of the connection") - func dropsAnOversizedBuffer() { - var buffer = ByteBufferOutput() - buffer.appendBytes(ByteBufferOutput.pattern(4 * 1_024 * 1_024)) - #expect(buffer.writeBufferIdentity.capacity >= 4 * 1_024 * 1_024) - _ = buffer.takeFirst(buffer.byteCount) - - #expect( - buffer.writeBufferIdentity.capacity <= ByteBufferOutput.maximumRetainedCapacity, - "megabytes should not be retained because one message needed them" - ) - } - - @Test("the buffer size learned from one message is kept for the next") - func keepsLearnedCapacity() { - var buffer = ByteBufferOutput() - buffer.appendBytes(ByteBufferOutput.pattern(8_000)) - _ = buffer.takeFirst(buffer.byteCount) - buffer.removeAll() - - buffer.appendBytes([1]) - #expect( - buffer.writeBufferIdentity.capacity >= 8_000, - "re-climbing the growth curve inside every message would reallocate repeatedly" - ) - } - - // MARK: - Foreign regions - - @Test("a region at or above the copy threshold is kept by reference, not copied") - func foreignRegionRetained() { - var buffer = ByteBufferOutput() - let payload = IMAPBuffer(ByteBufferOutput.pattern(IMAPBuffer.copyThreshold)) - buffer.append(payload) - - #expect(buffer.byteCount == IMAPBuffer.copyThreshold) - #expect(buffer.pendingRegionCount == 1) - #expect(buffer.pendingRegionIsForeign(0)) - #expect(buffer.writeBufferIdentity.capacity == 0, "a by-reference append must not allocate") - - let chunk = buffer.takeFirst(buffer.byteCount) - #expect(chunk.regionCount == 1) - #expect(address(of: chunk.regions[0]) == address(of: payload), "the payload must not be copied") - } - - @Test("a region below the copy threshold is copied into the buffer") - func foreignRegionCopied() { - var buffer = ByteBufferOutput() - let payload = IMAPBuffer(ByteBufferOutput.pattern(IMAPBuffer.copyThreshold - 1)) - buffer.append(payload) - - #expect(buffer.byteCount == IMAPBuffer.copyThreshold - 1) - #expect(buffer.pendingRegionCount == 1) - #expect(buffer.pendingRegionIsForeign(0) == false) - #expect(buffer.takeFirst(buffer.byteCount).copiedBytes() == payload.copiedBytes()) - } - - @Test("a short region copied in coalesces with the writes around it") - func shortForeignRegionCoalesces() { - var buffer = ByteBufferOutput() - buffer.append("<") - buffer.append(IMAPBuffer("short")) - buffer.append(">") - #expect(buffer.pendingRegionCount == 1) - #expect(buffer.takeFirst(buffer.byteCount).string == "") - } - - @Test("bytes written around a by-reference region stay in one buffer, in order") - func writesAroundAForeignRegion() { - var buffer = ByteBufferOutput() - let before = ByteBufferOutput.pattern(40, seed: 1) - let payload = ByteBufferOutput.pattern(2048, seed: 2) - let after = ByteBufferOutput.pattern(30, seed: 3) - buffer.appendBytes(before) - buffer.append(IMAPBuffer(payload)) - buffer.appendBytes(after) - - #expect(buffer.pendingRegionCount == 3) - #expect(buffer.pendingRegionIsForeign(1)) - - let chunk = buffer.takeFirst(buffer.byteCount) - #expect(chunk.regionCount == 3) - #expect(chunk.copiedBytes() == before + payload + after) - // The bytes written after the payload went into the same buffer as the ones before it — one - // allocation for the command, not one per payload. - #expect(address(of: chunk.regions[2]) == address(of: chunk.regions[0]) + 40) - } - - @Test("a chunk of an APPEND payload converts to ByteBuffers without copying the payload") - func appendPayloadSurvivesAsByteBuffers() { - var buffer = ByteBufferOutput() - let payload = ByteBuffer(repeating: UInt8(ascii: "x"), count: 1_024 * 1_024) - buffer.append("A1 APPEND \"INBOX\" {1048576}\r\n") - buffer.append(IMAPBuffer(payload)) - buffer.append("\r\n") - - let chunk = buffer.takeFirst(buffer.byteCount) - #expect(chunk.regionCount == 3) - - let buffers = chunk.makeByteBuffers() - #expect(buffers.count == 3) - #expect(address(of: buffers[1]) == address(of: payload), "the payload must reach the network uncopied") - #expect(buffers[1].readableBytes == 1_024 * 1_024) - #expect(String(buffer: buffers[0]) == "A1 APPEND \"INBOX\" {1048576}\r\n") - #expect(String(buffer: buffers[2]) == "\r\n") - } - - @Test("splitting a by-reference region does not copy it") - func splitForeignRegion() { - var buffer = ByteBufferOutput() - let payload = ByteBufferOutput.pattern(4096) - buffer.append(IMAPBuffer(payload)) - - let first = buffer.takeFirst(1000) - #expect(first.copiedBytes() == Array(payload[0..<1000])) - #expect(buffer.byteCount == 3096) - #expect(buffer.pendingRegionIsForeign(0), "the remainder should stay by-reference") - #expect(buffer.takeFirst(3096).copiedBytes() == Array(payload[1000...])) - } - - // MARK: - removeAll - - @Test("removeAll drops what is pending and the buffer is reusable") - func removeAll() { - var buffer = ByteBufferOutput() - buffer.append("first") - buffer.append(IMAPBuffer(ByteBufferOutput.pattern(2048))) - buffer.removeAll() - #expect(buffer.byteCount == 0) - #expect(buffer.pendingRegionCount == 0) - - buffer.append("second") - #expect(buffer.takeFirst(buffer.byteCount).string == "second") - } - - @Test("removeAll leaves bytes already handed out alone") - func removeAllKeepsHandedOutBytesIntact() { - var buffer = ByteBufferOutput() - buffer.append("first message") - let first = buffer.takeFirst(buffer.byteCount) - buffer.removeAll() - - buffer.append("second message") - let second = buffer.takeFirst(buffer.byteCount) - - #expect(first.string == "first message") - #expect(second.string == "second message") - } - - // MARK: - Value semantics - - @Test("writing to a copy leaves the original alone, and neither corrupts the other") - func copyOnWrite() { - var original = ByteBufferOutput() - original.append("SHARED ") - - var copy = original - copy.append("copy") - original.append("original") - - #expect(original.takeFirst(original.byteCount).string == "SHARED original") - #expect(copy.takeFirst(copy.byteCount).string == "SHARED copy") - } - - @Test("a copy taken before a hand-out still has all of its bytes") - func copyIsUnaffectedByHandOut() { - var original = ByteBufferOutput() - original.append("A001 NOOP\r\n") - var copy = original - - _ = original.takeFirst(original.byteCount) - #expect(original.byteCount == 0) - #expect(copy.byteCount == 11) - #expect(copy.takeFirst(11).string == "A001 NOOP\r\n") - } - - @Test("removeAll on a copy leaves the original alone") - func removeAllIsPerCopy() { - var original = ByteBufferOutput() - original.append("kept") - var copy = original - copy.removeAll() - - #expect(copy.byteCount == 0) - #expect(original.byteCount == 4) - #expect(original.takeFirst(4).string == "kept") - } - - // MARK: - Reading back - - @Test("withPendingRegions yields the pending regions, in order, without consuming them") - func withPendingRegions() { - var buffer = ByteBufferOutput() - buffer.append("ABCD") - buffer.append(IMAPBuffer(ByteBufferOutput.pattern(2048, seed: 9))) - buffer.append("EFG") - - let counts = buffer.withPendingRegions { regions -> [Int] in - var counts: [Int] = [] - for index in regions.indices { - counts.append(regions[index].count) - } - return counts - } - #expect(counts == [4, 2048, 3]) - #expect(buffer.byteCount == 2055, "reading back must not consume") - - let bytes = buffer.withPendingRegions { regions -> [UInt8] in - var all: [UInt8] = [] - for index in regions.indices { - all += regions[index].copiedBytes() - } - return all - } - #expect(bytes == Array("ABCD".utf8) + ByteBufferOutput.pattern(2048, seed: 9) + Array("EFG".utf8)) - - // And the buffer still works afterwards, even though the read-back briefly shared its storage. - buffer.append("HI") - #expect(buffer.takeFirst(buffer.byteCount).byteCount == 2057) - } - - @Test("withPendingRegions on an empty buffer yields nothing") - func withPendingRegionsEmpty() { - let buffer = ByteBufferOutput() - #expect(buffer.withPendingRegions { $0.count } == 0) - } - - @Test("debugDescription reports what is pending") - func debugDescription() { - var buffer = ByteBufferOutput() - #expect(buffer.debugDescription == "ByteBufferOutput(0 bytes pending in 0 regions)") - buffer.append("abc") - #expect(buffer.debugDescription == "ByteBufferOutput(3 bytes pending in 1 region)") - } - - @Test("a chunk from the sink converts to a DispatchData with the right bytes") - func dispatchData() { - var buffer = ByteBufferOutput() - buffer.append("A001 NOOP\r\n") - let data = buffer.takeFirst(buffer.byteCount).makeDispatchData() - #expect(Array(data) == Array("A001 NOOP\r\n".utf8)) - } -} diff --git a/Tests/NIOIMAPTests/Coders/AppendLiteralTests.swift b/Tests/NIOIMAPTests/Coders/AppendLiteralTests.swift index b7a2dca6..1d9250e4 100644 --- a/Tests/NIOIMAPTests/Coders/AppendLiteralTests.swift +++ b/Tests/NIOIMAPTests/Coders/AppendLiteralTests.swift @@ -163,6 +163,67 @@ struct AppendLiteralTests { helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(code: nil, text: "done"))))) } + /// A zero-length literal ends the part, yet the next part must still wait for its `+`. + @Test("APPEND to an empty mailbox sent as a literal waits for +") + func appendToEmptyLiteralMailbox() { + var helper = IMAPClientHandlerTests.Helper() + defer { helper.check() } + var options = CommandEncodingOptions.rfc3501 + options.useQuotedString = false + helper.writeOutbound(.setEncodingOptions(.fixed(options))) + + let start = helper.writeOutbound(.append(.start(tag: "A1", appendingTo: .init(""))), wait: false) + #expect(helper.drainOutbound() == "A1 APPEND {0}\r\n") + + let begin = helper.writeOutbound( + .append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 5)))), + wait: false + ) + #expect(helper.drainOutbound() == "") + + helper.writeInbound("+ OK\r\n") + #expect(helper.drainOutbound() == " {5}\r\n") + helper.expectSucceeded(start) + helper.expectSucceeded(begin) + + helper.writeOutbound(.append(.messageBytes("hello")), wait: false) + helper.writeOutbound(.append(.endMessage), wait: false) + helper.writeOutbound(.append(.finish), wait: false) + helper.writeInbound("+ OK\r\n") + #expect(helper.drainOutbound() == "hello\r\n") + + helper.writeInbound("A1 OK done\r\n") + helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(code: nil, text: "done"))))) + } + + @Test("CATENATE with an empty URL sent as a literal waits for +") + func catenateEmptyLiteralURL() { + var helper = IMAPClientHandlerTests.Helper() + defer { helper.check() } + helper.writeOutbound(.append(.start(tag: "A1", appendingTo: .inbox))) + helper.writeOutbound(.append(.beginCatenate(options: .init()))) + #expect(helper.drainOutbound() == "A1 APPEND \"INBOX\" CATENATE (") + + var options = CommandEncodingOptions.rfc3501 + options.useQuotedString = false + helper.writeOutbound(.setEncodingOptions(.fixed(options))) + + let urlPart = helper.writeOutbound(.append(.catenateURL("")), wait: false) + #expect(helper.drainOutbound() == "URL {0}\r\n") + + let endCatenate = helper.writeOutbound(.append(.endCatenate), wait: false) + helper.writeOutbound(.append(.finish), wait: false) + #expect(helper.drainOutbound() == "") + + helper.writeInbound("+ OK\r\n") + #expect(helper.drainOutbound() == ")\r\n") + helper.expectSucceeded(urlPart) + helper.expectSucceeded(endCatenate) + + helper.writeInbound("A1 OK done\r\n") + helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(code: nil, text: "done"))))) + } + @Test("untagged response while waiting for an APPEND literal's + is forwarded") func untaggedWhileWaitingForLiteral() { var helper = IMAPClientHandlerTests.Helper() diff --git a/Tests/NIOIMAPTests/CommandEncoder+Tests.swift b/Tests/NIOIMAPTests/CommandEncodeBuffer+Tests.swift similarity index 89% rename from Tests/NIOIMAPTests/CommandEncoder+Tests.swift rename to Tests/NIOIMAPTests/CommandEncodeBuffer+Tests.swift index 4375727f..8a2d4635 100644 --- a/Tests/NIOIMAPTests/CommandEncoder+Tests.swift +++ b/Tests/NIOIMAPTests/CommandEncodeBuffer+Tests.swift @@ -14,14 +14,34 @@ import NIO @testable import NIOIMAP -@testable import NIOIMAPCore +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore import NIOTestUtils import OrderedCollections import Testing -@Suite("CommandEncoder") -struct CommandEncoder_Tests { +@Suite("CommandEncodeBuffer") +struct CommandEncodeBuffer_Tests { + /// Encodes one command stream part and returns every byte of it, draining all chunks. + private func encode( + _ command: CommandStreamPart, + capabilities: [Capability] = [], + loggingMode: Bool = false + ) -> ByteBuffer { + var encodeBuffer = CommandEncodeBuffer( + capabilities: capabilities, + loggingMode: loggingMode + ) + encodeBuffer.writeCommandStream(command) + var bytes: [UInt8] = [] + while true { + let chunk = encodeBuffer.buffer.nextChunk() + bytes.append(contentsOf: chunk.bytes.copiedBytes()) + guard chunk.waitForContinuation else { break } + } + return ByteBuffer(bytes: bytes) + } + @Test func encoding() { // For now this is a fairly limited sequence of test @@ -101,9 +121,7 @@ struct CommandEncoder_Tests { ] for (command, expected, _) in inputs { - var buffer = ByteBuffer() - let encoder = CommandEncoder(loggingMode: false) - encoder.encode(data: command, out: &buffer) + let buffer = encode(command) #expect( expected == buffer, "\(String(buffer: expected)) is not equal to \(String(buffer: buffer))" @@ -196,10 +214,7 @@ struct CommandEncoder_Tests { ] for (command, expected, _) in inputs { - var buffer = ByteBuffer() - let encoder = CommandEncoder(loggingMode: true) - encoder.capabilities.append(.literalPlus) - encoder.encode(data: command, out: &buffer) + let buffer = encode(command, capabilities: [.literalPlus], loggingMode: true) #expect( expected == buffer, "'\(String(buffer: expected))' is not equal to '\(String(buffer: buffer))'" diff --git a/Tests/NIOIMAPTests/TestUtilities.swift b/Tests/NIOIMAPTests/TestUtilities.swift index c9beae11..67403a5d 100644 --- a/Tests/NIOIMAPTests/TestUtilities.swift +++ b/Tests/NIOIMAPTests/TestUtilities.swift @@ -86,3 +86,20 @@ extension ByteBuffer: @retroactive ExpressibleByStringLiteral { self.writeString(value) } } + +// Encoded chunks are `IMAPBufferList`s, and the state-machine tests spell the bytes they expect as +// string literals. A literal makes a one-region list; equality is byte-wise and ignores segmentation, +// so it compares equal to whatever the encoder's sink actually produced. +extension IMAPBufferList: ExpressibleByUnicodeScalarLiteral {} +extension IMAPBufferList: ExpressibleByExtendedGraphemeClusterLiteral {} +extension IMAPBufferList: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self = IMAPBufferList(IMAPBuffer(Array(value.utf8))) + } +} + +extension String { + init(buffer list: IMAPBufferList) { + self = String(decoding: list.copiedBytes(), as: UTF8.self) + } +}