From e4d23f01237b7efa25bea2c112e2e736f7aeaf69 Mon Sep 17 00:00:00 2001 From: Daniel Eggert Date: Wed, 11 Nov 2026 11:44:28 +0100 Subject: [PATCH] Add parser input types ParseInput: a ~Escapable, BitwiseCopyable cursor over a table of region pointers, with the primitives and combinators as methods. Input buffers: ParserInputBuffer (+ Consumable, StableRegion refinements), conformances for ByteBuffer / Array / Data, and IMAPInputBuffer, the staging deque that can hand out payloads by reference. IMAPInputBuffer keeps reads of at least copyThreshold (1 KiB) by reference and copies smaller ones into a 1 KiB tail (an OutputSegment), so a peer sending a byte per read costs a region per KiB, not a region, an object and a retained receive buffer per byte. A tail is written only past its end, only while the buffer holds the sole reference, and never reallocated; a used-up tail with room is continued by the next small read into an empty buffer. Only a StableAddressByteRegion (arrays, ByteBuffer) or an IMAPBuffer over one is kept by reference; any other large region, e.g. Data, is copied once. A bare DispatchData.Region is copied too: it points into its DispatchData without keeping it alive, so it is not a StableAddressByteRegion. append(contentsOf:) is the zero-copy path for DispatchData. Public API additions: IMAPInputBuffer.append(contentsOf: DispatchData) walks a read's regions with enumerateBytes, so it builds no regions array; a large region is kept with the DispatchData that owns it (also the owner a makeDispatchData() donation retains), small ones go to the tail. append(_:) gains overloads for a StableAddressByteRegion and an IMAPBuffer, so appending a ByteBuffer, an array or an IMAPBuffer pays no dynamic cast; IMAPByteStorage.init(_:) gains one for an IMAPBuffer. Additive; the grammar still runs on ParseBuffer. Review focus: _span(_:) and RegionSink (the two read-side unsafe seams), the head invariant in advance(by:), the gather's 64-frame recursion cap, IMAPInputBuffer.writableTail(fitting:), and DispatchDataRegion, what append(contentsOf:) keeps: its @unchecked Sendable and its StableAddressByteRegion (fixed-address) promise. Temporary: main's SubParser is renamed LegacySubParser so both coexist. --- .../Bytes/ByteBuffer+ParserInput.swift | 41 +- Sources/NIOIMAPCore/Bytes/ByteRegion.swift | 39 +- Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift | 49 +- .../Bytes/IMAPBufferList+DispatchData.swift | 11 +- .../NIOIMAPCore/Bytes/IMAPByteStorage.swift | 62 +- .../NIOIMAPCore/Bytes/IMAPInputBuffer.swift | 348 +++++++++ Sources/NIOIMAPCore/Bytes/OutputSegment.swift | 7 +- .../Bytes/ParserInputBuffer+Foundation.swift | 133 ++++ .../NIOIMAPCore/Bytes/ParserInputBuffer.swift | 430 +++++++++++ .../NIOIMAPCore.docc/ParsingAndEncoding.md | 11 + .../Parser/Grammar/GrammarParser.swift | 4 +- .../Parser/ParseInput+Combinators.swift | 338 +++++++++ Sources/NIOIMAPCore/Parser/ParseInput.swift | 690 ++++++++++++++++++ Sources/NIOIMAPCore/Parser/ParserErrors.swift | 18 + .../NIOIMAPCore/Parser/ParserLibrary.swift | 46 +- .../IMAPInputBufferDispatchDataTests.swift | 254 +++++++ .../Bytes/IMAPInputBufferTests.swift | 499 +++++++++++++ .../Bytes/StableAddressByteRegionTests.swift | 56 ++ .../Parser/ParseInputCombinatorTests.swift | 389 ++++++++++ .../Parser/ParseInputHarness.swift | 170 +++++ .../Parser/ParseInputTests.swift | 636 ++++++++++++++++ .../Parser/ParserInputBufferTests.swift | 304 ++++++++ Tests/NIOIMAPCoreTests/TestUtilities.swift | 52 ++ .../Bytes/IMAPBufferByteBufferTests.swift | 10 + 24 files changed, 4546 insertions(+), 51 deletions(-) create mode 100644 Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift create mode 100644 Sources/NIOIMAPCore/Bytes/ParserInputBuffer+Foundation.swift create mode 100644 Sources/NIOIMAPCore/Bytes/ParserInputBuffer.swift create mode 100644 Sources/NIOIMAPCore/Parser/ParseInput+Combinators.swift create mode 100644 Sources/NIOIMAPCore/Parser/ParseInput.swift create mode 100644 Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferDispatchDataTests.swift create mode 100644 Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferTests.swift create mode 100644 Tests/NIOIMAPCoreTests/Parser/ParseInputCombinatorTests.swift create mode 100644 Tests/NIOIMAPCoreTests/Parser/ParseInputHarness.swift create mode 100644 Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift create mode 100644 Tests/NIOIMAPCoreTests/Parser/ParserInputBufferTests.swift diff --git a/Sources/NIOIMAP/Bytes/ByteBuffer+ParserInput.swift b/Sources/NIOIMAP/Bytes/ByteBuffer+ParserInput.swift index 34fb5057..bcea546a 100644 --- a/Sources/NIOIMAP/Bytes/ByteBuffer+ParserInput.swift +++ b/Sources/NIOIMAP/Bytes/ByteBuffer+ParserInput.swift @@ -34,5 +34,42 @@ extension ByteBuffer: ByteRegion { // A copy of a `ByteBuffer` keeps its storage alive, and while copies share storage a write through any of // them copies it first — so the readable bytes a copy sees neither move nor change. That lets -// `makeDispatchData()` donate them rather than copy. -extension ByteBuffer: StableAddressByteRegion {} +// `IMAPInputBuffer` keep a large one and `makeDispatchData()` donate one, rather than copy. +extension ByteBuffer: StableAddressByteRegion { + /// The capacity of the storage, which every copy and slice of this buffer keeps alive: a 1 KiB + /// slice of a 64 KiB read pins 64 KiB. + public var pinnedByteCount: Int { storageCapacity } +} + +extension ByteBuffer: ParserInputBuffer { + /// The buffer's readable bytes, as the one region they are. + public var byteRegions: CollectionOfOne { CollectionOfOne(self) } + + /// The number of readable bytes. + /// + /// This is ``ParserInputBuffer/count`` — bytes the parser can see — which for a `ByteBuffer` means + /// its readable bytes and not its capacity. + public var count: Int { readableBytes } + + /// One, always: a `ByteBuffer`'s bytes are contiguous by construction. + public var regionCount: Int { 1 } +} + +extension ByteBuffer: ConsumableParserInputBuffer { + /// Moves the reader index forward by `k`. + /// + /// O(1), and it satisfies ``ConsumableParserInputBuffer``'s requirement that discarding a prefix + /// must not move the remaining bytes — a `ByteBuffer` keeps its read head as an index. + /// + /// - Parameter k: How many bytes to discard. Must not exceed ``count``. + public mutating func discardFirst(_ k: Int) { + moveReaderIndex(forwardBy: k) + } +} + +// A `ByteBuffer` deliberately does *not* conform to `StableRegionParserInputBuffer`, so a payload +// extracted from one is copied rather than referred to. Vouching for a region means handing the gather +// an `IMAPByteStorage` that outlives it, and `RegionSink.append` takes that owner *unretained* — so a +// conformer that boxes inside `withStableRegions` would hand over a box that is already dead. Only +// something that *stores* the box can promise this, which is what `IMAPInputBuffer` is for: append a +// `ByteBuffer` to one of those and a multi-megabyte literal reaches the caller uncopied. diff --git a/Sources/NIOIMAPCore/Bytes/ByteRegion.swift b/Sources/NIOIMAPCore/Bytes/ByteRegion.swift index 5e895301..f4074c8b 100644 --- a/Sources/NIOIMAPCore/Bytes/ByteRegion.swift +++ b/Sources/NIOIMAPCore/Bytes/ByteRegion.swift @@ -16,14 +16,14 @@ /// /// This is the narrowest thing the library needs in order to read somebody else's bytes: a single /// scoped accessor. The signature deliberately matches Foundation's `ContiguousBytes`, so Foundation -/// types conform with an empty extension and the core of `NIOIMAPCore` never has to -/// `import Foundation`. +/// types conform with an empty extension and `NIOIMAPCore` never needs full Foundation on Linux: +/// `FoundationEssentials` is enough. /// /// ## Conforming /// /// Most conformances are empty, because the type already has a `withUnsafeBytes(_:)` of the right /// shape — that is true of `Array`, `ArraySlice` and `ContiguousArray` over `UInt8`, all of which -/// conform below, and of `Foundation.Data`. +/// conform below, and of `Data`. /// /// ## Immutability /// @@ -55,19 +55,38 @@ extension ContiguousArray: ByteRegion where Element == UInt8 {} /// /// Conforming promises more: `withUnsafeBytes(_:)` yields the region's actual storage, at a fixed /// address, and those bytes stay valid and unchanged for as long as any copy of the value is alive. -/// In return, ``IMAPBufferList/makeDispatchData()`` donates a region of at least -/// ``IMAPBuffer/dispatchDonationThreshold`` bytes to the `DispatchData`, keeping a copy of the value -/// alive in its place, instead of copying it. +/// In return, the library keeps a copy of the value where it would otherwise copy the bytes: +/// ``IMAPInputBuffer`` keeps a large region by reference, and ``IMAPBufferList/makeDispatchData()`` +/// donates a region of at least ``IMAPBuffer/dispatchDonationThreshold`` bytes to the `DispatchData`. /// /// This is the extension point for a byte-buffer type of your own; `NIOIMAP` conforms `ByteBuffer` /// with nothing more. A region that does not conform is copied instead, which is always correct. +/// `DispatchData.Region` does not conform: it does not keep its `DispatchData` alive. /// /// - Important: The promise cannot be checked. A conformer whose bytes move or change while a copy of -/// it is alive leaves a donated pointer dangling. -public protocol StableAddressByteRegion: ByteRegion {} +/// it is alive leaves the parser's or a `DispatchData`'s pointer dangling. +public protocol StableAddressByteRegion: ByteRegion { + /// How many bytes holding this value keeps alive: its allocation, which may be larger than the + /// bytes it exposes. + /// + /// The parser refers to a large literal only if it is a large enough share of this; a smaller one + /// is copied, so it does not pin a mostly unused allocation. Defaults to the region's byte count. + var pinnedByteCount: Int { get } +} + +extension StableAddressByteRegion { + /// The region's byte count: right for a conformer whose allocation is exactly its bytes. + public var pinnedByteCount: Int { withUnsafeBytes { $0.count } } +} // An `Array`'s buffer does not move while the array is alive, and holding a copy of the array is // enough to keep it alive: any write to another copy goes through copy-on-write. -extension Array: StableAddressByteRegion where Element == UInt8 {} +extension Array: StableAddressByteRegion where Element == UInt8 { + public var pinnedByteCount: Int { capacity } +} +// An `ArraySlice`'s `capacity` is not its base's allocation, so it takes the default, which undercounts +// what a slice of a larger array pins. extension ArraySlice: StableAddressByteRegion where Element == UInt8 {} -extension ContiguousArray: StableAddressByteRegion where Element == UInt8 {} +extension ContiguousArray: StableAddressByteRegion where Element == UInt8 { + public var pinnedByteCount: Int { capacity } +} diff --git a/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift b/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift index 8fdf5d6a..ec6fbd89 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPBuffer.swift @@ -65,7 +65,8 @@ public struct IMAPBuffer: Sendable { case copied([UInt8], Range) /// Bytes somebody else owns, plus the live sub-range within that owner. case retained(IMAPByteStorage, Range) - /// Bytes in an encoder output segment, plus the range of it this value exposes. + /// Bytes in an encoder output segment or an input buffer's tail, plus the range of it this value + /// exposes. /// /// The encoder's own bytes get their own case rather than going through an /// ``IMAPByteStorage``, because a box per handed-out region is a class allocation per @@ -117,7 +118,7 @@ public struct IMAPBuffer: Sendable { self.storage = .retained(storage, 0.. Bool { + guard byteCount >= minimumRetainedLiteralByteCount else { return false } + // `byteCount * factor >= pinnedByteCount`, without the multiplication that could overflow. + let (product, overflow) = byteCount.multipliedReportingOverflow(by: retainedLiteralMaximumPinnedFactor) + return overflow || product >= pinnedByteCount + } } // MARK: - Representation @@ -370,6 +392,29 @@ extension IMAPBuffer { return (storage, range) } } + + /// How many bytes holding this value keeps alive: the whole backing allocation, not just ``count``. + internal var pinnedByteCount: Int { + switch storage { + case .copied(let bytes, _): + return bytes.capacity + case .retained(let storage, _): + return storage.pinnedByteCount + case .segment(let segment, _): + return segment.capacity + } + } + + /// Whether these bytes stay at one address for as long as this value is alive: an array and a + /// segment never move; a retained region does if its owner promises it. + internal var hasStableAddress: Bool { + switch storage { + case .copied, .segment: + return true + case .retained(let storage, _): + return storage.hasStableAddress + } + } } // MARK: - Equatable & Hashable diff --git a/Sources/NIOIMAPCore/Bytes/IMAPBufferList+DispatchData.swift b/Sources/NIOIMAPCore/Bytes/IMAPBufferList+DispatchData.swift index bffdd45a..b34d722d 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPBufferList+DispatchData.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPBufferList+DispatchData.swift @@ -37,11 +37,12 @@ import ucrt // `DispatchData(bytesNoCopy:deallocator:)` takes ownership of a pointer, so the pointer has to // outlive the `withUnsafeBytes(_:)` call it came from. `ByteRegion` does not promise that — a region // is free to yield a temporary buffer — so this file only escapes a pointer that -// `IMAPBuffer.withUnsafeBytesAndOwner(_:)` hands out: bytes this library owns, or a region that -// conforms to `StableAddressByteRegion` (the stdlib arrays; `ByteBuffer`, in `NIOIMAP`). It copies -// from any other. A third-party `ByteRegion` is therefore correct by default and merely pays a copy, -// unless it conforms too. That method is public, so a conversion to another adopting type can be -// written outside the library the same way. +// `IMAPBuffer.withUnsafeBytesAndOwner(_:)` hands out: bytes this library owns, or storage with a fixed +// address — a `StableAddressByteRegion` (the stdlib arrays, a region `IMAPInputBuffer.append(contentsOf:)` +// kept with its `DispatchData`; `ByteBuffer`, in `NIOIMAP`) or an `IMAPBuffer` over one. It copies +// from any other, `DispatchData.Region` included. A third-party `ByteRegion` is +// therefore correct by default and merely pays a copy, unless it conforms too. That method is public, +// so a conversion to another adopting type can be written outside the library the same way. // // The deallocator closure holds the owner, which is what keeps the memory alive for as long as the // `DispatchData` refers to it. This file goes through the internal `withUnsafeBytesAndStableOwner(_:)`: diff --git a/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift b/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift index 43ed17e1..920b932a 100644 --- a/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift +++ b/Sources/NIOIMAPCore/Bytes/IMAPByteStorage.swift @@ -37,8 +37,8 @@ /// /// This is a correctness contract of the same kind as `Hashable` consistency, not a memory-safety /// assertion — nothing here stores a pointer. The exception is ``StableAddressByteRegion``: -/// ``IMAPBufferList/makeDispatchData()`` lets a pointer outlive the accessor on its word, so a false -/// conformance does leave one dangling. +/// ``IMAPInputBuffer`` and ``IMAPBufferList/makeDispatchData()`` let a pointer outlive the accessor on +/// its word, so a false conformance does leave one dangling. public final class IMAPByteStorage: Sendable { private let region: any ByteRegion & Sendable @@ -51,11 +51,19 @@ public final class IMAPByteStorage: Sendable { /// Whether the wrapped region promises a fixed address, so a pointer to its bytes may outlive a /// ``withUnsafeBytes(_:)`` call as long as this object stays alive. /// - /// Determined once, when the region is wrapped. `false` for any region that does not conform to - /// ``StableAddressByteRegion``, which is the safe answer: ``IMAPBuffer/withUnsafeBytesAndOwner(_:)`` - /// then hands out no pointer, and its callers copy instead. + /// Determined once, when the region is wrapped: `true` for a ``StableAddressByteRegion``, and for + /// an ``IMAPBuffer`` whose own bytes have a fixed address. `false` otherwise — a `Data` included, + /// since it may flatten into a temporary buffer. `false` is the safe answer: ``IMAPInputBuffer`` + /// then copies, and ``IMAPBuffer/withUnsafeBytesAndOwner(_:)`` hands out no pointer, so its callers copy. internal let hasStableAddress: Bool + /// How many bytes this object keeps alive: at least ``count``, more when the wrapped region's + /// allocation is larger than its bytes — a `ByteBuffer` read into a 64 KiB buffer, say. + /// + /// Captured once, when the region is wrapped. The parser weighs a literal against it before + /// referring to it rather than copying it. + internal let pinnedByteCount: Int + /// Wraps a region, taking ownership of it. /// /// Whether the region has a fixed address is checked at run time, once. A caller whose region type @@ -64,14 +72,24 @@ public final class IMAPByteStorage: Sendable { /// - Parameter region: The bytes to keep alive. Must satisfy the immutability requirement /// described on ``IMAPByteStorage``. public convenience init(_ region: some ByteRegion & Sendable) { - self.init(region, address: region is any StableAddressByteRegion ? .fixed : .unknown) + if let stable = region as? any StableAddressByteRegion { + self.init(region, address: .fixed, pinnedByteCount: stable.pinnedByteCount) + } else if let buffer = region as? IMAPBuffer { + self.init( + region, + address: buffer.hasStableAddress ? .fixed : .unknown, + pinnedByteCount: buffer.pinnedByteCount + ) + } else { + self.init(region, address: .unknown, pinnedByteCount: nil) + } } /// Wraps a region whose address is fixed, taking ownership of it. /// /// Overload resolution picks this wherever the region's type is known to conform — `ByteBuffer`, /// the stdlib arrays — so wrapping one costs no dynamic cast. The other init is not specialized - /// across modules, so its cast runs on every call. + /// across modules, so its casts run on every call. /// /// - Parameter region: The bytes to keep alive. Must satisfy the immutability requirement /// described on ``IMAPByteStorage``. @@ -79,18 +97,42 @@ public final class IMAPByteStorage: Sendable { self.init(region, address: .fixed) } + /// Wraps an ``IMAPBuffer``, taking ownership of it. + /// + /// The buffer's own fixed address, if it has one, carries over, without the dynamic cast the generic + /// init needs to find out. + /// + /// - Parameter buffer: The bytes to keep alive. + public convenience init(_ buffer: IMAPBuffer) { + self.init( + buffer, + address: buffer.hasStableAddress ? .fixed : .unknown, + pinnedByteCount: buffer.pinnedByteCount + ) + } + /// What a wrapped region promises about its address. private enum Address { - /// A ``StableAddressByteRegion``: a pointer may outlive the accessor. + /// Fixed: a pointer may outlive the accessor. case fixed /// No promise: a pointer is valid only inside the accessor. case unknown } - private init(_ region: some ByteRegion & Sendable, address: Address) { + /// Reads what a region with a fixed address pins without a cast: what overload resolution picks for + /// the ``StableAddressByteRegion`` init. + private convenience init(_ region: some StableAddressByteRegion & Sendable, address: Address) { + self.init(region, address: address, pinnedByteCount: region.pinnedByteCount) + } + + /// - Parameter pinnedByteCount: What the region keeps alive, or `nil` if it does not say; never + /// taken as less than its byte count. + private init(_ region: some ByteRegion & Sendable, address: Address, pinnedByteCount: Int?) { self.region = region - self.count = region.withUnsafeBytes { $0.count } + let count = region.withUnsafeBytes { $0.count } + self.count = count self.hasStableAddress = address == .fixed + self.pinnedByteCount = Swift.max(count, pinnedByteCount ?? count) } /// Calls the given closure with a pointer to the wrapped bytes. diff --git a/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift b/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift new file mode 100644 index 00000000..fef26082 --- /dev/null +++ b/Sources/NIOIMAPCore/Bytes/IMAPInputBuffer.swift @@ -0,0 +1,348 @@ +//===----------------------------------------------------------------------===// +// +// 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 DequeModule + +/// Received bytes, waiting to be parsed. +/// +/// This is what a connection accumulates into: it appends whatever a read produced, parses as many +/// messages out of the front as have arrived, and never moves a byte in between. +/// +/// ```swift +/// var buffer = IMAPInputBuffer() +/// buffer.append(bytesFromTheNetwork) +/// while let response = try parser.parseResponseStream(buffer: &buffer) { … } +/// ``` +/// +/// ## How this relates to `ParserInputBuffer` +/// +/// ``ParserInputBuffer`` is the protocol the parser reads through; this is the conformer to use for a +/// connection, and the one ``CommandParser/parseCommandStream(buffer:)`` and +/// ``ResponseParser/parseResponseStream(buffer:)`` are written for. Other types conform too, but only +/// some of them can be passed to those entry points, which need a ``ConsumableParserInputBuffer``: +/// `DispatchData` and `NIOIMAP`'s `ByteBuffer` can, while `Data` and the array types deliberately +/// cannot, because trimming them moves the remaining bytes. Bytes held in one of those reach the parser +/// by being appended here, which copies an array only if it is small (a `Data` always; see below) — so +/// this is both the streaming answer and the one-shot answer, and the alternatives are for a caller +/// that already has a `ByteBuffer` or a `DispatchData` in hand. +/// +/// Two properties are the reason to use this rather than an array or a `Data`: +/// +/// - **Appending never moves appended bytes, and never copies a large read at a fixed address.** Such +/// a read, of at least ``IMAPBuffer/copyThreshold`` bytes, is kept as-is, so a message that straddles +/// two reads is parsed across them instead of being memmoved into one buffer. A smaller read is +/// copied into a shared fixed-capacity *tail*, so a peer sending a byte per read pins 1 KiB tails, +/// not a receive buffer and an object per byte. +/// - **Consuming is O(1) in the bytes consumed.** The read head is an offset into the first run, and +/// runs are dropped whole once they are used up. A buffer that moved the remainder down instead +/// pays per byte moved, and pays it again on every message. +/// +/// It is also the only input type that lets the parser hand out large payloads *without copying +/// them*: because it owns the runs it was given, a multi-megabyte literal can be delivered as a +/// reference to the received bytes. A payload delivered that way keeps its run's whole allocation alive +/// for as long as the caller holds it, even after the buffer has moved past it — which is the point, and +/// is why ``count`` counts bytes waiting to be parsed rather than bytes still allocated. So the parser +/// delivers a payload by reference only if it is at least 512 bytes and at least a third of that +/// allocation — a 1 KiB literal in a 64 KiB `ByteBuffer` is copied — which caps what a payload pins at +/// three times its size. +/// +/// - Important: A region kept by reference must not change for as long as this buffer or any payload +/// extracted from it refers to it. Only a large region whose address is known to be fixed is kept: +/// a ``StableAddressByteRegion`` — the stdlib arrays, NIO's `ByteBuffer` — or an ``IMAPBuffer`` +/// over one. Any other region, `Data` and `DispatchData.Region` included, is copied whatever its +/// size: one exact-size array for a large one, the tail for a small one. For a `DispatchData`, use +/// ``append(contentsOf:)``, which keeps large regions without copying. +public struct IMAPInputBuffer: Sendable { + /// One run of bytes in the queue. + fileprivate enum Chunk: Sendable { + /// A read of at least ``IMAPBuffer/copyThreshold`` bytes: kept as received if its address is + /// fixed, otherwise copied into an array. Either way its storage has a stable address. + case received(IMAPByteStorage) + /// Small reads copied together. Its `used` is the run's length. + /// + /// Invariants: only the last chunk (or `spareTail`) is written into, only past `used`, and only + /// while this buffer holds the sole reference — so no struct copy, ``Regions`` view or + /// ``IMAPBuffer`` can see a write. The allocation is never resized, so bytes keep their address. + case tail(OutputSegment) + + var count: Int { + switch self { + case .received(let storage): storage.count + case .tail(let segment): segment.used + } + } + } + + /// The appended runs, oldest first, each one boxed so that a payload can outlive its place in the + /// queue. Fully consumed runs are dropped from the front. + private var chunks: Deque + + /// How many bytes of `chunks.first` have already been consumed. + /// + /// Always less than that run's length: a run that is used up is dropped rather than left at + /// offset `count`, which is what keeps `chunks.first` meaningful and the head region non-empty. + private var headOffset: Int + + /// The last tail, used up and dropped while it still had room, kept so that the next small read into + /// an empty buffer continues past its end instead of allocating. Not a region: nothing exposes it. + /// Reused only while this is its sole reference. + private var spareTail: OutputSegment? + + /// The number of bytes waiting to be parsed. + /// + /// This counts *live* bytes, not allocated ones. A run that has been consumed is no longer + /// counted even if a payload extracted from it is keeping it alive. + public private(set) var count: Int + + /// Capacity of a fresh tail: `copyThreshold`, so a full tail is as large as the smallest read kept by + /// reference. + internal static let minimumTailCapacity = IMAPBuffer.copyThreshold + + /// Creates an empty buffer. + public init() { + self.chunks = [] + self.headOffset = 0 + self.spareTail = nil + self.count = 0 + } + + /// Whether there are no bytes waiting to be parsed. + public var isEmpty: Bool { count == 0 } + + /// Adds received bytes to the end of the buffer. + /// + /// A region of at least ``IMAPBuffer/copyThreshold`` bytes whose address is fixed — a + /// ``StableAddressByteRegion``, or an ``IMAPBuffer`` over one — is not copied: it is retained as-is + /// and parsed where it lies, for one small object per call. Any other region that large — a `Data`, + /// say — is copied once into an exact-size array, which is retained instead. A smaller one is copied + /// into the tail, or into a fresh ``minimumTailCapacity`` tail if it does not fit, and is not + /// retained. + /// + /// Appending an empty region does nothing. + /// + /// - Parameter region: The bytes to add. If retained, it must satisfy the immutability requirement + /// described on ``IMAPInputBuffer``. + public mutating func append(_ region: some ByteRegion & Sendable) { + guard !appendToTail(ifSmall: region) else { return } + // `withStableRegions` lets pointers into a retained run outlive its accessor, so a run without a + // fixed address is copied into an array, which never moves, and that is kept instead. + var storage = IMAPByteStorage(region) + if !storage.hasStableAddress { + storage = IMAPByteStorage(region.withUnsafeBytes { [UInt8]($0) }) + } + appendReceived(storage) + } + + /// Adds received bytes whose address is fixed to the end of the buffer. + /// + /// The same as the overload for any region, chosen at compile time for a region type known to be a + /// ``StableAddressByteRegion`` — NIO's `ByteBuffer`, the stdlib arrays — so keeping a large one costs + /// no dynamic cast. + /// + /// - Parameter region: The bytes to add. If retained, it must satisfy the immutability requirement + /// described on ``IMAPInputBuffer``. + public mutating func append(_ region: some StableAddressByteRegion & Sendable) { + guard !appendToTail(ifSmall: region) else { return } + appendReceived(IMAPByteStorage(region)) + } + + /// Adds an ``IMAPBuffer`` to the end of the buffer. + /// + /// The same as the overload for any region, without its dynamic casts: a large buffer is retained if + /// its own bytes have a fixed address, and copied once into an array otherwise. + /// + /// - Parameter buffer: The bytes to add. + public mutating func append(_ buffer: IMAPBuffer) { + guard !appendToTail(ifSmall: buffer) else { return } + guard buffer.hasStableAddress else { + appendReceived(IMAPByteStorage(buffer.withUnsafeBytes { [UInt8]($0) })) + return + } + appendReceived(IMAPByteStorage(buffer)) + } + + /// Copies `region` into the tail if it is shorter than ``IMAPBuffer/copyThreshold``. + /// + /// - Returns: Whether it was copied. + private mutating func appendToTail(ifSmall region: some ByteRegion) -> Bool { + region.withUnsafeBytes { bytes in + guard bytes.count < IMAPBuffer.copyThreshold else { return false } + appendToTail(bytes) + return true + } + } + + /// Queues a run of at least ``IMAPBuffer/copyThreshold`` bytes at a fixed address. + internal mutating func appendReceived(_ storage: IMAPByteStorage) { + assert(storage.hasStableAddress, "a retained run must have a fixed address") + chunks.append(.received(storage)) + count += storage.count + } + + /// Copies `bytes` past the end of the tail, starting a new tail if the last one cannot take them. + internal mutating func appendToTail(_ bytes: UnsafeRawBufferPointer) { + guard !bytes.isEmpty else { return } + let segment = writableTail(fitting: bytes.count) + let written = segment.append(bytes) + precondition(written == bytes.count, "a tail took \(written) of \(bytes.count) bytes") + count += bytes.count + } + + /// The last chunk if it is a tail with room for `byteCount` bytes that only `chunks` refers to; + /// otherwise a new tail, appended. + private mutating func writableTail(fitting byteCount: Int) -> OutputSegment { + // Removed, not peeked, so the uniqueness check does not count our own reference twice. + if case .tail? = chunks.last, case .tail(var segment) = chunks.removeLast() { + let isWritable = isKnownUniquelyReferenced(&segment) && segment.availableCapacity >= byteCount + chunks.append(.tail(segment)) + if isWritable { return segment } + } + // Nothing buffered: continue the used-up tail from its end. The bytes before it stay unexposed. + if chunks.isEmpty, isKnownUniquelyReferenced(&spareTail), let spare = spareTail, + spare.availableCapacity >= byteCount + { + spareTail = nil + headOffset = spare.used + chunks.append(.tail(spare)) + return spare + } + spareTail = nil + let segment = OutputSegment(capacity: Swift.max(Self.minimumTailCapacity, byteCount)) + chunks.append(.tail(segment)) + return segment + } + + /// Discards the first `k` bytes. + /// + /// O(1) in `k`: the read head moves, and runs it has moved past are dropped. Nothing is copied and + /// nothing is moved. + /// + /// - Parameter k: How many bytes to discard. Must not exceed ``count``. + public mutating func discardFirst(_ k: Int) { + precondition(k >= 0, "cannot discard \(k) bytes") + precondition(k <= count, "cannot discard \(k) bytes from a buffer holding \(count)") + var remaining = k + // Indexed rather than bound with `let`, so no extra reference to a tail is held while it is + // checked for uniqueness below. + while remaining > 0, !chunks.isEmpty { + let available = chunks[chunks.startIndex].count - headOffset + if remaining < available { + headOffset += remaining + count -= remaining + return + } + // This run is used up; drop it. A received run stays alive while a large payload extracted + // from it does — deliberately. A tail does not: payloads from it are copies. The last tail, if + // it has room and is ours alone, is kept as `spareTail`. + if case .tail(var segment) = chunks.removeFirst(), chunks.isEmpty, segment.availableCapacity > 0, + isKnownUniquelyReferenced(&segment) + { + spareTail = segment + } + headOffset = 0 + count -= available + remaining -= available + } + } + + /// Drops every byte, keeping the buffer usable. + public mutating func removeAll() { + chunks.removeAll(keepingCapacity: true) + headOffset = 0 + spareTail = nil + count = 0 + } +} + +// MARK: - Reading + +extension IMAPInputBuffer: ConsumableParserInputBuffer, StableRegionParserInputBuffer { + /// The buffer's runs, in order, the first one starting at the read head. + /// + /// A view rather than an array: it allocates nothing, and it *slices* the first run rather than + /// handing over the whole thing, which is the conformance requirement + /// ``ParserInputBuffer/byteRegions`` states. + public struct Regions: RandomAccessCollection, Sendable { + fileprivate let chunks: Deque + fileprivate let headOffset: Int + + public var startIndex: Int { 0 } + public var endIndex: Int { chunks.count } + + public subscript(position: Int) -> IMAPBuffer { + let start = position == 0 ? headOffset : 0 + switch chunks[position] { + case .received(let storage): + return IMAPBuffer(storage, start..(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R { + try _stableWithParseInput(limit: limit, body) + } +} + +extension IMAPInputBuffer: CustomStringConvertible { + public var description: String { + "IMAPInputBuffer(\(count) bytes in \(chunks.count) region\(chunks.count == 1 ? "" : "s"))" + } +} diff --git a/Sources/NIOIMAPCore/Bytes/OutputSegment.swift b/Sources/NIOIMAPCore/Bytes/OutputSegment.swift index e1a2bde9..3089b4ca 100644 --- a/Sources/NIOIMAPCore/Bytes/OutputSegment.swift +++ b/Sources/NIOIMAPCore/Bytes/OutputSegment.swift @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// -/// A `malloc`'d, append-only, uniquely-owned run of bytes. One allocation, never reallocated. +/// A `malloc`'d, append-only, single-writer run of bytes. One allocation, never reallocated. /// /// This is the unit of storage the encoder writes into. `used` only ever grows and the allocation /// never moves, which is the property that lets a chunk be handed out while encoding continues: the @@ -24,9 +24,10 @@ /// /// - Important: A segment must be written by at most one owner. Nothing here enforces that; the /// staging type above it does, by sealing a segment rather than sharing it when its state is -/// copied. +/// copied. ``IMAPInputBuffer``, which uses segments as tails for small reads, writes only while it +/// holds the sole reference. /// -/// - Note: **Unsafe seam**. `@unchecked Sendable` rests on the +/// - Note: **Unsafe seam** (all are listed at the top of `ParseInput.swift`). `@unchecked Sendable` rests on the /// disjointness above: a handed-out region exposes a range that has already been written and that /// nothing writes into again, while the writer only ever touches bytes beyond it. So a chunk may /// cross to another thread while encoding continues, and the mutable `used` — which only ever diff --git a/Sources/NIOIMAPCore/Bytes/ParserInputBuffer+Foundation.swift b/Sources/NIOIMAPCore/Bytes/ParserInputBuffer+Foundation.swift new file mode 100644 index 00000000..74d4d5e9 --- /dev/null +++ b/Sources/NIOIMAPCore/Bytes/ParserInputBuffer+Foundation.swift @@ -0,0 +1,133 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// The Foundation half of the input seam, kept in one file. Like the rest of `NIOIMAPCore`, it never +// needs full Foundation on Linux: `Data` is in `FoundationEssentials`, `DispatchData` in `Dispatch`. +// `ByteRegion`'s single requirement is spelled the same way as `ContiguousBytes`', so most of what +// follows is an empty extension. + +import Dispatch + +#if canImport(FoundationEssentials) +import FoundationEssentials +#else +import Foundation +#endif + +extension Data: ByteRegion {} +// Darwin only: corelibs-libdispatch has no `DispatchData.Region`. +#if canImport(Darwin) +extension DispatchData.Region: ByteRegion {} +#endif + +// Not a `StableAddressByteRegion`: a `DispatchData.Region` points into its `DispatchData` without +// keeping it alive, so its bytes are valid only while that `DispatchData` is. `IMAPInputBuffer.append(_:)` +// therefore copies a large one; `append(contentsOf:)` keeps the whole `DispatchData` instead. + +// `Data` presents as one region even when the storage behind it is not contiguous: `withUnsafeBytes` +// flattens in that case, and nothing promises the flattened bytes outlive the call. So `Data` is not +// a `StableAddressByteRegion`, and `IMAPInputBuffer` copies a large one rather than keeping it. This +// is the "parse all of this" source, and it is read-only — trimming a `Data` moves its remaining +// bytes down, which is the cost `ConsumableParserInputBuffer` exists to keep out of connection code. +extension Data: ParserInputBuffer { + public var byteRegions: CollectionOfOne { CollectionOfOne(self) } +} + +// `DispatchData` is the genuinely multi-region source: concatenating two of them copies nothing, so a +// buffer assembled from many reads really does arrive as many regions. It takes the one-pass gather, +// which is why an arbitrary region count costs it no stack. +extension DispatchData: ParserInputBuffer { + public var byteRegions: [DispatchData.Region] { regions } + + /// The number of regions, counted without materialising them. + /// + /// `regions` allocates an array; `enumerateBytes` walks the same regions and allocates nothing. + /// The gather only ever needs the number, so this is the cheaper way to answer. + public var regionCount: Int { + var count = 0 + enumerateBytes { _, _, _ in count += 1 } + return count + } + + public func withParseInput(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R { + try _stableWithParseInput(limit: limit, body) + } +} + +extension DispatchData: ConsumableParserInputBuffer { + /// Discards the first `k` bytes. + /// + /// `subdata(in:)` is `dispatch_data_create_subrange`, which copies nothing. + /// + /// - Parameter k: How many bytes to discard. + public mutating func discardFirst(_ k: Int) { + self = subdata(in: k..= IMAPBuffer.copyThreshold else { + appendToTail(bytes) + return + } + appendReceived(IMAPByteStorage(DispatchDataRegion(data: data, bytes: bytes))) + } + } +} + +/// One region of a `DispatchData`, kept alive by holding the whole `DispatchData`. +/// +/// A `dispatch_data_t` is immutable and keeps its leaf buffers alive, so `bytes` stays put for as long +/// as `data` does. Holding all of `data` costs a retain rather than the allocation that +/// `subdata(in:)` may make, and pins all of `data` — usually one read — while the region is alive. +private struct DispatchDataRegion: StableAddressByteRegion, @unchecked Sendable { // @unchecked: `bytes` is in `data`. + let data: DispatchData + let bytes: UnsafeRawBufferPointer + + /// All of `data`. A lower bound: a leaf may itself be a sub-range of a larger allocation, and + /// `DispatchData` does not say how large. + var pinnedByteCount: Int { data.count } + + func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + try body(bytes) + } +} diff --git a/Sources/NIOIMAPCore/Bytes/ParserInputBuffer.swift b/Sources/NIOIMAPCore/Bytes/ParserInputBuffer.swift new file mode 100644 index 00000000..e29f038a --- /dev/null +++ b/Sources/NIOIMAPCore/Bytes/ParserInputBuffer.swift @@ -0,0 +1,430 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// Bytes the parser can read from, in one or more contiguous runs. +/// +/// This is the library's input seam. A caller hands over whatever it already holds — a `Data`, a +/// `DispatchData`, an array of bytes, an ``IMAPInputBuffer`` of network reads, or a type of its own — +/// and the parser reads through it without asking for the bytes to be flattened into one buffer +/// first. +/// +/// ```swift +/// var buffer = IMAPInputBuffer() +/// buffer.append(bytesFromTheNetwork) +/// while let response = try parser.parseResponseStream(buffer: &buffer) { … } +/// ``` +/// +/// ## Which type to use +/// +/// - **A connection accumulating received bytes: ``IMAPInputBuffer``.** That is what the parser entry +/// points are written for. Appending a read copies it only if it is small or has no fixed address +/// (a `Data`), discarding what has been parsed is O(1), and it is the only input a large literal can +/// be delivered out of without being copied. +/// - **Bytes you already hold: hand them over if they are consumable, otherwise append them to an +/// ``IMAPInputBuffer``.** ``CommandParser/parseCommandStream(buffer:)`` and +/// ``ResponseParser/parseResponseStream(buffer:)`` take a ``ConsumableParserInputBuffer``, because +/// they discard whatever they parsed; `DispatchData` and — in `NIOIMAP` — `ByteBuffer` are that, so +/// they can be passed directly. `Data`, `[UInt8]`, `ArraySlice` and `ContiguousArray` +/// conform to *this* protocol but deliberately not to that one, because trimming them moves the +/// remaining bytes. Appending an array to an ``IMAPInputBuffer`` costs one small object and no copy +/// (below 1 KiB, a copy into a shared tail), appending a `Data` one copy, and either is the way to +/// parse out of it. +/// - **Bytes in a shape of your own: conform.** Two members, ``byteRegions`` and ``count``, and the +/// library does the rest. See *Conforming*, below. +/// +/// Conforming does not mean writing anything that reads bytes. Reading happens through a +/// ``ParseInput``, whose surface is internal: the cursor appears in this protocol's signatures because +/// the default implementation of ``withParseInput(limit:_:)`` builds one and hands it to the parser, +/// and a conformer never has to look inside it. +/// +/// ## Conforming +/// +/// A conformer describes its bytes as an ordered collection of ``ByteRegion``s and says how many +/// bytes there are in total. Everything else has a default implementation. +/// +/// Two refinements are worth knowing about before writing one. ``ConsumableParserInputBuffer`` adds +/// "the parser may discard what it consumed", which the entry points above require, and +/// ``StableRegionParserInputBuffer`` adds "my region pointers stay valid for a borrow of me", which buys +/// a single-pass gather and copy-free extraction of large payloads. ``IMAPInputBuffer`` is all three, +/// and is the worked example of each. +/// +/// A conformance to this protocol alone is still worth having: it is what +/// ``SynchronizingLiteralParser/parseContinuationsNecessary(_:)`` takes, and it is how the package's own +/// tests parse out of arrays. +/// +/// - Important: ``byteRegions`` must begin at the read position, and its regions must add up to +/// ``count``. A conformer that keeps a read head as an offset has to *slice* its first region +/// rather than hand over the whole thing and expect the parser to skip the prefix — the parser +/// reports how much it consumed relative to what it was shown, so a skipped prefix gets counted +/// twice and bytes go missing. Both halves are asserted in debug builds. +/// +/// ## Cost +/// +/// The parser's per-region overhead is small but not free — each move from one region to +/// the next costs something, and bulk scans restart at every boundary. That is invisible for +/// network-sized reads and dominant for pathologically small ones: one-byte regions parse far slower +/// per byte than contiguous bytes do. Callers that can hand over larger regions should. +public protocol ParserInputBuffer { + /// The collection of contiguous byte runs this buffer is made of. + associatedtype Regions: Collection where Regions.Element: ByteRegion + + /// The buffer's bytes, in order, starting at the read position. + var byteRegions: Regions { get } + + /// The total number of bytes, across every region. + var count: Int { get } + + /// How many regions ``byteRegions`` holds. + /// + /// The default implementation counts ``byteRegions``. Override it when the count is cheaper to + /// come by than the regions themselves — `DispatchData` allocates an array to present its + /// regions, and the gather only needs the number in order to size its table. + var regionCount: Int { get } + + /// Reads through the buffer's bytes. + /// + /// This is the gather: it collects the buffer's regions into one flat table and hands `body` a + /// cursor over them. Nothing about the cursor may outlive the call. + /// + /// The default implementation walks ``byteRegions``, holding each region's accessor open for as + /// long as the cursor exists. ``StableRegionParserInputBuffer`` conformers replace it with a + /// single pass, and must do so with an explicit one-line witness of their own — see that + /// protocol. + /// + /// - Parameters: + /// - limit: The most bytes the parser may consume. Bytes past it are invisible to it, which is + /// how a caller parses a prefix of what it holds without slicing first. + /// - body: A closure that reads through the cursor. + /// - Returns: Whatever `body` returns. + func withParseInput(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R +} + +/// A ``ParserInputBuffer`` the parser can also consume from, so that a caller does not have to trim +/// it by hand. +/// +/// ``ConsumableParserInputBuffer/parse(limit:_:)`` is the entry point that trims: whatever the +/// parser consumed is discarded when it returns, including when it throws. +/// +/// - Important: ``discardFirst(_:)`` must be O(1) amortised in the number of bytes discarded. A +/// conformer that moves the remaining bytes down instead makes a caller that trims after every +/// message quadratic over the life of a connection. That is why `Data` and `Array` are deliberately +/// *not* consumable here, even though removing a prefix from them is one line: the one line is the slow +/// one. Callers that want to consume a `Data` can conform it themselves and know what it costs. +public protocol ConsumableParserInputBuffer: ParserInputBuffer { + /// Discards the first `k` bytes. + /// + /// - Parameter k: How many bytes to discard. Must not exceed ``ParserInputBuffer/count``. + mutating func discardFirst(_ k: Int) +} + +/// A ``ParserInputBuffer`` whose region pointers stay valid for as long as the buffer is borrowed. +/// +/// **This is one of the two unsafe seams on the parser's read side, and conforming to it is an +/// assertion the compiler cannot check.** ``ByteRegion`` promises only that a pointer is valid for the +/// duration of a ``ByteRegion/withUnsafeBytes(_:)`` call. A conformer here promises more: that the +/// pointers it pushes into a ``RegionSink`` stay valid for as long as a borrow of `self` lasts, so the +/// gather can collect them in one pass instead of nesting one accessor scope per region. +/// +/// What that buys is not mainly speed. The generic gather recurses once per region, so it needs a +/// depth cap and has to coalesce the tail beyond it; a single pass needs neither, at any region +/// count. +/// +/// It is also where zero-copy extraction comes from. A conformer that owns its bytes can pass an +/// ``IMAPByteStorage`` to ``RegionSink/append(_:owner:offset:)``, and a large payload extracted from +/// that region is then handed to the caller as a reference to the input rather than as a copy — if it +/// is at least a third of what the storage keeps alive (see ``StableAddressByteRegion/pinnedByteCount``). +/// Passing `nil` is always correct and means such an extraction copies. +public protocol StableRegionParserInputBuffer: ParserInputBuffer { + /// Pushes every region, in order, into `sink`. + /// + /// - Parameter sink: The table to fill. The only thing that can be done with it is appending. + borrowing func withStableRegions(into sink: inout RegionSink) +} + +/// The table a ``StableRegionParserInputBuffer`` fills, one region at a time. +/// +/// The library owns the storage and validates every push, so a conformer cannot get the bookkeeping +/// wrong: it cannot overrun the table, and it cannot describe a range that lies outside the owner it +/// names. It is neither copyable nor escapable, so it cannot outlive the gather that created it. +public struct RegionSink: ~Copyable, ~Escapable { + /// Where the entries go. Sized from ``ParserInputBuffer/regionCount``. + private let table: UnsafeMutableBufferPointer + + /// How many entries have been pushed. + private(set) var filled: Int + + /// How many bytes have been pushed, for the conformance assertion in the gather. + private(set) var byteCount: Int + + @_lifetime(immortal) + internal init(table: UnsafeMutableBufferPointer) { + self.table = table + self.filled = 0 + self.byteCount = 0 + } + + /// Adds one region. + /// + /// - Parameters: + /// - bytes: The region's bytes. Must stay valid for as long as `self` and the borrow of the + /// buffer that produced it — this is the promise + /// ``StableRegionParserInputBuffer`` makes. + /// - owner: Who keeps `bytes` alive, if the buffer can vouch for them, so that a large + /// extraction can refer to the input rather than copying it. `nil` means an extraction + /// copies, which is always correct. + /// - offset: Where `bytes` begins inside `owner`. Zero when the region is all of the owner; + /// the head offset when the region is the unconsumed tail of one. + @_lifetime(self: copy self) + public mutating func append(_ bytes: UnsafeBufferPointer, owner: IMAPByteStorage?, offset: Int) { + precondition( + filled < table.count, + "a ParserInputBuffer pushed more than the \(table.count) regions its regionCount promised" + ) + if let owner { + precondition( + offset >= 0 && offset + bytes.count <= owner.count, + "a region of \(bytes.count) bytes at offset \(offset) does not fit its owner's \(owner.count)" + ) + } + table[filled] = RegionEntry( + bytes: bytes, + owner: owner.map { Unmanaged.passUnretained($0) }, + ownerOffset: offset + ) + filled += 1 + byteCount += bytes.count + } + + /// The entries pushed so far. + internal var filledTable: ChunkTable { + ChunkTable(rebasing: table[..(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R { + let regions = byteRegions + assertRegionsAddUp(regions) + // One entry per region up to the cap, plus one for a coalesced tail. + let capacity = Swift.min(regionCount, Self.maximumGatherDepth) + 1 + return try withUnsafeTemporaryAllocation(of: RegionEntry.self, capacity: capacity) { table in + try Self.descend(regions, regions.startIndex, 0, 0, table, limit, body) + } + } + + /// Reads through the buffer's bytes, with no limit on how many the parser may consume. + /// + /// - Parameter body: A closure that reads through the cursor. + /// - Returns: Whatever `body` returns. + /// + /// - Note: This is deliberately a *different* signature from + /// ``ParserInputBuffer/withParseInput(limit:_:)`` rather than a default argument on it. A + /// default argument here would shadow a conformer's own witness, so a one-pass conformer would + /// silently take the generic path whenever the caller left the limit out — which is the common + /// case, and the failure is invisible. + public func withParseInput(_ body: (inout ParseInput) throws -> R) rethrows -> R { + try withParseInput(limit: .max, body) + } + + /// Fills the table one region deeper per frame. + /// + /// The nesting is forced: a cursor cannot be threaded *through* a chain of accessor scopes, so + /// the descent writes pointers into a flat table on the way down and builds the cursor at the + /// innermost frame, where every scope is still open. Do not restructure this into a loop that + /// opens and closes one region at a time. + private static func descend( + _ regions: Regions, + _ index: Regions.Index, + _ depth: Int, + _ filled: Int, + _ table: UnsafeMutableBufferPointer, + _ limit: Int, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + guard index != regions.endIndex else { + var input = ParseInput(table: ChunkTable(rebasing: table[.. R in + guard !raw.isEmpty else { + // An empty region carries no bytes, so it needs no entry — but it does cost a frame. + return try descend(regions, next, depth + 1, filled, table, limit, body) + } + table[filled] = RegionEntry(bytes: raw.bindMemory(to: UInt8.self)) + return try descend(regions, next, depth + 1, filled + 1, table, limit, body) + } + } + + /// Copies every region from `index` onwards into one buffer, and parses that as a single region. + /// + /// This is the pathological path: a caller that hands over more regions than the recursion can + /// safely descend gets a copy of the tail rather than a stack overflow. Nothing is dropped, and + /// the copy is bounded by the bytes the caller passed. + private static func coalescing( + _ regions: Regions, + _ index: Regions.Index, + _ filled: Int, + _ table: UnsafeMutableBufferPointer, + _ limit: Int, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + var tail = [UInt8]() + for region in regions[index...] { + region.withUnsafeBytes { tail.append(contentsOf: $0) } + } + return try tail.withUnsafeBytes { raw -> R in + var count = filled + if !raw.isEmpty { + table[filled] = RegionEntry(bytes: raw.bindMemory(to: UInt8.self)) + count += 1 + } + var input = ParseInput(table: ChunkTable(rebasing: table[..(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R { + /// try _stableWithParseInput(limit: limit, body) + /// } + /// ``` + /// + /// The forward has to be written out like that rather than left to a default implementation on + /// this protocol. A default here satisfies the *base* protocol's requirement, and which of the + /// two the compiler picks depends on where the call is made from — so `parse` would take the + /// generic path while a direct call took this one, with nothing failing to announce it. + /// + /// - Parameters: + /// - limit: The most bytes the parser may consume. + /// - body: A closure that reads through the cursor. + /// - Returns: Whatever `body` returns. + public func _stableWithParseInput( + limit: Int, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + try withUnsafeTemporaryAllocation( + of: RegionEntry.self, + capacity: Swift.max(regionCount, 1) + ) { table in + var sink = RegionSink(table: table) + withStableRegions(into: &sink) + assert( + sink.byteCount == count, + "\(Self.self) pushed \(sink.byteCount) bytes but its count is \(count). Regions must " + + "begin at the read position and add up to count." + ) + var input = ParseInput(table: sink.filledTable, owner: self, limit: limit) + return try body(&input) + } + } +} + +// MARK: - Consuming + +extension ConsumableParserInputBuffer { + /// Reads through the buffer's bytes and discards whatever the parser consumed. + /// + /// This is the entry point a connection uses: the caller cannot forget to trim, and cannot trim + /// by the wrong amount. + /// + /// Trimming happens on every exit path, a thrown error included, because the streaming literal + /// modes legitimately make progress and *then* report that they need more bytes. A parser that + /// wants its position back on failure gets that from the cursor's own backtracking instead, which + /// leaves nothing consumed to trim. + /// + /// - Parameters: + /// - limit: The most bytes the parser may consume. + /// - body: A closure that reads through the cursor. + /// - Returns: Whatever `body` returns. + public mutating func parse( + limit: Int = .max, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + var consumed = 0 + defer { if consumed > 0 { self.discardFirst(consumed) } } + // `limit:` is passed explicitly so that this binds a conformer's own witness rather than the + // no-limit convenience overload, which would send a one-pass conformer down the generic path. + return try withParseInput(limit: limit) { input in + defer { consumed = input.consumed } + return try body(&input) + } + } +} + +// MARK: - Stdlib conformances + +// Read-only on purpose: removing a prefix from an array moves the rest of it, so these are the +// "parse all of this" sources — tests, fuzzing, one-shot callers — and not connection buffers. +extension Array: ParserInputBuffer where Element == UInt8 { + public var byteRegions: CollectionOfOne<[UInt8]> { CollectionOfOne(self) } +} + +extension ArraySlice: ParserInputBuffer where Element == UInt8 { + public var byteRegions: CollectionOfOne> { CollectionOfOne(self) } +} + +extension ContiguousArray: ParserInputBuffer where Element == UInt8 { + public var byteRegions: CollectionOfOne> { CollectionOfOne(self) } +} diff --git a/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md b/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md index 59373546..c34e06ef 100644 --- a/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md +++ b/Sources/NIOIMAPCore/NIOIMAPCore.docc/ParsingAndEncoding.md @@ -35,6 +35,17 @@ Types for carrying raw message payloads without copying them. - ``ByteRegion`` - ``StableAddressByteRegion`` +### Parser input + +Where received bytes wait to be parsed, and how the parser reads them. + +- ``IMAPInputBuffer`` +- ``ParserInputBuffer`` +- ``ConsumableParserInputBuffer`` +- ``StableRegionParserInputBuffer`` +- ``ParseInput`` +- ``RegionSink`` + ### Encoder output Where encoded bytes go. diff --git a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift index 6517505e..0c1be7bb 100644 --- a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift +++ b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift @@ -839,7 +839,7 @@ extension GrammarParser { func parseLastCommandSet( buffer: inout ParseBuffer, tracker: StackTracker, - setParser: SubParser> + setParser: LegacySubParser> ) throws -> LastCommandSet { func parseLastCommandSet_lastCommand( buffer: inout ParseBuffer, @@ -864,7 +864,7 @@ extension GrammarParser { func parseLastCommandMessageID( buffer: inout ParseBuffer, tracker: StackTracker, - setParser: SubParser + setParser: LegacySubParser ) throws -> LastCommandMessageID { func parseLastCommandMessageID_lastCommand( buffer: inout ParseBuffer, diff --git a/Sources/NIOIMAPCore/Parser/ParseInput+Combinators.swift b/Sources/NIOIMAPCore/Parser/ParseInput+Combinators.swift new file mode 100644 index 00000000..2a80eb0f --- /dev/null +++ b/Sources/NIOIMAPCore/Parser/ParseInput+Combinators.swift @@ -0,0 +1,338 @@ +//===----------------------------------------------------------------------===// +// +// 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 OrderedCollections.OrderedDictionary + +/// One step of the grammar: reads from the cursor, and either produces a value or throws. +/// +/// Pass a closure literal, `{ try parseX(buffer: &$0, tracker: $1) }`, rather than a bare local function +/// `parseX`. A local `func` taking `inout ParseInput` carries an inferred lifetime dependency that function types +/// cannot express before Swift 6.4 (swiftlang/swift#86842), so 6.2 and 6.3 reject the bare reference. +/// Method references (`self.parseX`) are fine. Revisit once 6.4 is the minimum: +/// https://github.com/apple/swift-nio-imap/issues/875 +typealias SubParser = (inout ParseInput, StackTracker) throws -> T + +// MARK: - Character classes + +extension ParseInput { + /// Consumes and returns the leading bytes that satisfy `predicate`, of which there may be none. + /// + /// - Throws: `IncompleteMessage` when every visible byte satisfies `predicate`, since the run may + /// continue into bytes that have not arrived yet. + @_lifetime(self: copy self) + mutating func parseZeroOrMoreCharacters(where predicate: (UInt8) -> Bool) throws -> [UInt8] { + guard let count = scanWhile(predicate) else { throw IncompleteMessage() } + return try extractBytes(length: count) + } + + /// Consumes and returns the leading bytes that satisfy `predicate`, of which there must be at least + /// one. + /// + /// - Throws: `IncompleteMessage` when every visible byte satisfies `predicate`; ``ParserError`` when + /// the very first byte does not. + @_lifetime(self: copy self) + mutating func parseOneOrMoreCharacters(where predicate: (UInt8) -> Bool) throws -> [UInt8] { + guard let count = scanWhile(predicate) else { throw IncompleteMessage() } + guard count > 0 else { throw ParserError(hint: "Unexpected byte") } + return try extractBytes(length: count) + } + + /// Consumes one or more spaces. + /// + /// Consumes nothing unless it succeeds, so a caller does not need to wrap this in + /// ``composite(tracker:_:)`` to keep its position on a failure. + /// + /// - Throws: `IncompleteMessage` when the input is empty, or when everything visible is a space and + /// more bytes could follow; ``ParserError`` when the first byte is not a space. + mutating func parseSpaces() throws { + // Not `scanWhile == nil`-as-incomplete: a run of spaces reaching the end of the input *is* a + // complete run of spaces as far as this cursor can tell, and the old implementation consumed it. + guard let first = peek(at: 0) else { throw IncompleteMessage() } + guard first == UInt8(ascii: " ") else { throw ParserError(hint: "Expected space") } + guard let count = scanWhile({ $0 == UInt8(ascii: " ") }) else { + advance(by: remaining) + return + } + advance(by: count) + } +} + +// MARK: - Matching + +extension ParseInput { + /// Whether ``matchFixed(_:caseSensitivity:leadingSpaces:)`` skips spaces before the needle. + enum LeadingSpaces { + /// `")"` also matches `" )"`. + case allowed + /// `")"` matches only `")"`. + case rejected + } + + /// Consumes `needle`, optionally allowing spaces in front of it, and consumes nothing otherwise. + /// + /// The leading-space form saves and restores the cursor itself rather than taking a + /// ``StackTracker``: skipping spaces cannot recurse, so it needs no stack frame. + @_lifetime(self: copy self) + mutating func matchFixed( + _ needle: String, + caseSensitivity: CaseSensitivity = .caseInsensitive, + leadingSpaces: LeadingSpaces + ) throws { + guard leadingSpaces == .allowed else { + return try matchFixed(needle, caseSensitivity: caseSensitivity) + } + let save = copy self + do { + try? parseSpaces() + try matchFixed(needle, caseSensitivity: caseSensitivity) + } catch { + self = save + throw error + } + } + + /// Consumes one byte and requires it to be `needle`. Consumes nothing otherwise. + @_lifetime(self: copy self) + mutating func matchByte(_ needle: Character) throws { + assert(needle.isASCII) + guard let byte = peek(at: 0) else { throw IncompleteMessage() } + guard byte == needle.asciiValue! else { throw ParserError(hint: "Unexpected byte") } + advance(by: 1) + } +} + +// MARK: - Numbers + +extension ParseInput { + /// Whether ``parseUnsignedInt64(tracker:leadingZeros:)`` accepts a number that starts with `0`. + enum LeadingZeros { + /// `007` parses as 7. + case allowed + /// A leading `0` is a mismatch, even `0` itself. + case rejected + } + + /// Consumes a run of ASCII digits and returns its value along with how many digits it took. + @_lifetime(self: copy self) + mutating func parseUnsignedInteger( + tracker: StackTracker, + leadingZeros: LeadingZeros = .rejected + ) throws -> (number: Int, bytesConsumed: Int) { + let largeInt = try parseUnsignedInt64(tracker: tracker, leadingZeros: leadingZeros) + guard let int = Int(exactly: largeInt.number) else { + throw ParserError(hint: "integer too large") + } + return (number: int, bytesConsumed: largeInt.bytesConsumed) + } + + /// Consumes a run of ASCII digits and returns its value along with how many digits it took. + @_lifetime(self: copy self) + mutating func parseUnsignedInt64( + tracker: StackTracker, + leadingZeros: LeadingZeros = .rejected + ) throws -> (number: UInt64, bytesConsumed: Int) { + try composite(tracker: tracker) { input, _ in + let digits = try input.parseOneOrMoreCharacters { char in + char >= UInt8(ascii: "0") && char <= UInt8(ascii: "9") + } + if leadingZeros == .rejected, digits.first == UInt8(ascii: "0") { + throw ParserError(hint: "starts with 0") + } + // Accumulating rather than going through `UInt64(String)` keeps a per-integer allocation off + // a path taken for every UID, size and sequence number. + var value: UInt64 = 0 + for digit in digits { + let (multiplied, overflowedMultiply) = value.multipliedReportingOverflow(by: 10) + guard !overflowedMultiply else { throw ParserError(hint: "number is too large") } + let (added, overflowedAdd) = multiplied.addingReportingOverflow( + UInt64(digit - UInt8(ascii: "0")) + ) + guard !overflowedAdd else { throw ParserError(hint: "number is too large") } + value = added + } + return (value, digits.count) + } + } +} + +// MARK: - Combinators + +extension ParseInput { + /// Runs `parser`, and returns `nil` — having consumed nothing — if it fails to match. + /// + /// Only a ``ParserError`` means "did not match": an `IncompleteMessage` propagates, because more + /// bytes could still make this parser succeed and the caller must be able to wait for them. + @_lifetime(self: copy self) + mutating func parseOptional(tracker: StackTracker, parser: SubParser) throws -> T? { + do { + return try composite(tracker: tracker, parser) + } catch is ParserError { + return nil + } + } + + /// Runs each of `subParsers` in turn and returns the first result, consuming nothing for the + /// alternatives that fail. + @_lifetime(self: copy self) + mutating func parseOneOf( + _ subParsers: [SubParser], + tracker: StackTracker, + file: String = (#fileID), + line: Int = #line + ) throws -> T { + for parser in subParsers { + do { + return try composite(tracker: tracker, parser) + } catch is ParserError { + continue + } catch is BadCommand { + continue + } + } + throw ParserError(hint: "none of the options match", file: file, line: line) + } + + /// Two-alternative form. Spelled out rather than built on the array form so that the common case + /// does not allocate an array of closures per call. + @_lifetime(self: copy self) + mutating func parseOneOf( + _ parser1: SubParser, + _ parser2: SubParser, + tracker: StackTracker, + file: String = (#fileID), + line: Int = #line + ) throws -> T { + do { + return try composite(tracker: tracker) { input, tracker in + try parser1(&input, tracker) + } + } catch is ParserError { + // Try the next alternative. + } catch is BadCommand { + // Try the next alternative. + } + + return try composite(tracker: tracker) { input, tracker in + try parser2(&input, tracker) + } + } + + /// Three-alternative form. + @_lifetime(self: copy self) + mutating func parseOneOf( + _ parser1: SubParser, + _ parser2: SubParser, + _ parser3: SubParser, + tracker: StackTracker, + file: String = (#fileID), + line: Int = #line + ) throws -> T { + do { + return try composite(tracker: tracker) { input, tracker in + try parser1(&input, tracker) + } + } catch is ParserError { + // Try the next alternative. + } catch is BadCommand { + // Try the next alternative. + } + + do { + return try composite(tracker: tracker) { input, tracker in + try parser2(&input, tracker) + } + } catch is ParserError { + // Try the next alternative. + } catch is BadCommand { + // Try the next alternative. + } + + return try composite(tracker: tracker) { input, tracker in + try parser3(&input, tracker) + } + } + + /// Runs `parser` until it stops matching, requiring at least one match. + @_lifetime(self: copy self) + mutating func parseOneOrMore(tracker: StackTracker, parser: SubParser) throws -> [T] { + var parsed: [T] = [] + try parseOneOrMore(into: &parsed, tracker: tracker, parser: parser) + return parsed + } + + /// Runs `parser` until it stops matching, requiring at least one match, appending as it goes. + @_lifetime(self: copy self) + mutating func parseOneOrMore( + into parsed: inout [T], + tracker: StackTracker, + parser: SubParser + ) throws { + try composite(tracker: tracker) { input, tracker in + parsed.append(try parser(&input, tracker)) + while let next = try input.parseOptional(tracker: tracker, parser: parser) { + parsed.append(next) + } + } + } + + /// Runs `parser` until it stops matching, which may be immediately. + @_lifetime(self: copy self) + mutating func parseZeroOrMore(tracker: StackTracker, parser: SubParser) throws -> [T] { + var parsed: [T] = [] + try parseZeroOrMore(into: &parsed, tracker: tracker, parser: parser) + return parsed + } + + /// Runs `parser` until it stops matching, which may be immediately, appending as it goes. + @_lifetime(self: copy self) + mutating func parseZeroOrMore( + into parsed: inout [T], + tracker: StackTracker, + parser: SubParser + ) throws { + try composite(tracker: tracker) { input, tracker in + while let next = try input.parseOptional(tracker: tracker, parser: parser) { + parsed.append(next) + } + } + } + + /// Runs `parser` until it stops matching, collecting key/value pairs. + @_lifetime(self: copy self) + mutating func parseZeroOrMore( + into orderedDictionary: inout OrderedDictionary, + tracker: StackTracker, + parser: SubParser<(K, V)> + ) throws { + try composite(tracker: tracker) { input, tracker in + while let next = try input.parseOptional(tracker: tracker, parser: parser) { + orderedDictionary[next.0] = next.1 + } + } + } + + /// Runs `parser` until it stops matching, collecting ``KeyValue`` pairs. + @_lifetime(self: copy self) + mutating func parseZeroOrMore( + into orderedDictionary: inout OrderedDictionary, + tracker: StackTracker, + parser: SubParser> + ) throws { + try composite(tracker: tracker) { input, tracker in + while let next = try input.parseOptional(tracker: tracker, parser: parser) { + orderedDictionary[next.key] = next.value + } + } + } +} diff --git a/Sources/NIOIMAPCore/Parser/ParseInput.swift b/Sources/NIOIMAPCore/Parser/ParseInput.swift new file mode 100644 index 00000000..16d1ebc9 --- /dev/null +++ b/Sources/NIOIMAPCore/Parser/ParseInput.swift @@ -0,0 +1,690 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif os(Windows) +import ucrt +#elseif canImport(Android) +import Android +#endif + +// Compiler constraints not obvious from the code (the others are at their sites: `RegionEntry`, +// `_span(_:)`, `ParseInput.head`): +// +// - The lifetime checker is a SIL pass. `swiftc -typecheck` accepts code a real build rejects, so +// verify lifetime changes with a full build. +// - Spell it `@_lifetime`. `@lifetime` without the underscore only warns. Annotations name +// parameters, never properties. +// +// 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 +// `withUnsafe…` closure that produced it. Outside that scope, `Base64/Chromium.swift` and +// `MailboxName.swift` use pointers too; both predate this list. +// +// 1. Read: `_span(_:)`, below, and the region table it reads, a `withUnsafeTemporaryAllocation` the +// gather fills (ParserInputBuffer.swift). A `Span` may be rebuilt from a table entry. Entries are written +// only below the table's capacity and read only below the count filled. +// 2. Read: `StableRegionParserInputBuffer.withStableRegions(into:)` via `RegionSink` +// (ParserInputBuffer.swift). The conformer's region pointers outlive their accessor and its owners +// keep them alive. `RegionSink` holds owners unretained (`Unmanaged`) and its init is +// `@_lifetime(immortal)`; it is `~Copyable`, and only the gather creates one. `IMAPInputBuffer` +// retains only regions with `IMAPByteStorage.hasStableAddress` and copies the rest. +// 3. Write: `OutputSegment: @unchecked Sendable` (OutputSegment.swift). Handed-out ranges and the bytes +// still being written are disjoint; a segment never reallocates. An `IMAPInputBuffer` tail is written +// only while that buffer is its sole owner, and its `Regions` view reads only up to `used`. +// 4. Write: `IMAPOutputBuffer.OpenTail` (IMAPOutputBuffer.swift). Writes go through its cached raw +// pointer into the open segment, not through the segment. `Storage.tail` holds that segment for as +// long as `open` describes it. +// 5. Write: `@exclusivity(unchecked)` on `IMAPOutputBuffer.Storage`'s properties (IMAPOutputBuffer.swift). +// No runtime exclusivity check. `Storage` is private, `IMAPOutputBuffer` is not `Sendable`, and every +// write first checks that the box is uniquely referenced. +// 6. Write: `IMAPBuffer.makeDispatchData()` donating a pointer to `bytesNoCopy` +// (IMAPBufferList+DispatchData.swift). Contained by `IMAPByteStorage.hasStableAddress`: other +// regions copy. +// 7. Write: `IMAPBufferList.makeDispatchData()` copying a run of regions into a `malloc` it hands to +// `bytesNoCopy` (IMAPBufferList+DispatchData.swift). Exact-size, filled before the +// hand-off, and not touched after it. +// 8. Write: `EncodeBuffer.writeDecimal(_:minimumDigits:)` formats into a `withUnsafeTemporaryAllocation` +// (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 +// 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 +// 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 +// `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 +// `parsedStringCache` closure is not `@Sendable`. + +/// One contiguous run of input bytes, plus whoever can keep those bytes alive. +/// +/// The gather (a later phase) fills a flat table of these and hands it to a ``ParseInput``. A table of +/// `Span` is not expressible — no container may hold a non-escapable element — which is why the +/// bytes are a pointer here and become a `Span` only inside the cursor. +/// +/// `owner` is *unretained* on purpose. The gather borrows whatever holds the boxes for as long as the +/// cursor exists, so the boxes cannot go away underneath it, and reading an `Unmanaged` emits no +/// reference counting. Exactly one retain happens per extraction, when the owner is handed to an +/// ``IMAPBuffer``. +/// +/// `nil` is always a correct answer for `owner`: it means an extraction copies rather than pinning the +/// input, which is the right default for a caller whose region pointers this package cannot vouch for. +internal struct RegionEntry { + /// The bytes of this region. Valid for as long as the gather that produced the table is running. + internal var bytes: UnsafeBufferPointer + + /// Who owns `bytes`, if anybody can vouch for them, so that an extraction can retain instead of copy. + internal var owner: Unmanaged? + + /// Where `bytes` begins inside the owner's storage. + /// + /// - Important: This is *not* redundant, and leaving it out silently returns the wrong bytes. An + /// owner box spans a whole network read while a region may be a *slice* of that read — a staging + /// type slices its head region rather than re-boxing it after a partial consume — so the offset of + /// the region inside its owner is not generally zero. + internal var ownerOffset: Int + + internal init( + bytes: UnsafeBufferPointer, + owner: Unmanaged? = nil, + ownerOffset: Int = 0 + ) { + self.bytes = bytes + self.owner = owner + self.ownerOffset = ownerOffset + } +} + +/// The flat region table a ``ParseInput`` reads from. One allocation per gather, never per byte. +internal typealias ChunkTable = UnsafeBufferPointer + +/// Rebuilds a `Span` from a region table entry. +/// +/// **This is the one unsafe seam in the parser cursor**, and it is deliberately ten lines long so that +/// it can be audited in ten seconds. What it asserts is that the bytes a table entry points at outlive +/// the cursor: the gather holds every region's accessor scope open — or, for a stable-region conformer, +/// vouches for the pointers explicitly — for as long as the cursor exists. +/// +/// Two spellings that do not work, recorded so they are not retried: +/// +/// - It must be a *free function*. `@_unsafeNonescapableResult` on a `mutating` method does not work. +/// - It must be `@_lifetime(immortal)`. `@_lifetime(borrow x)` fails the SIL lifetime checker here, +/// because the reconstructed span is stored into `self`. +@_unsafeNonescapableResult +@_lifetime(immortal) +@inline(__always) +internal func _span(_ bytes: UnsafeBufferPointer) -> Span { + Span(_unsafeElements: bytes) +} + +/// A borrowing cursor over one or more runs of input bytes. +/// +/// This is what the parser reads through, and what ``ParserInputBuffer/withParseInput(limit:_:)`` +/// hands to its closure. It is a plain 56-byte `BitwiseCopyable` value, so saving and +/// restoring it for backtracking — which every `parseOneOf` and `parseOptional` does — is a `memcpy` +/// with no reference counting. +/// +/// It is `~Escapable` because it caches the current region as a `Span`, and that is load-bearing rather +/// than incidental: it makes it structurally impossible for the parser to keep input bytes past the +/// call. Nobody can drop `~Escapable` in a later refactor without first deleting the cached span. +/// Bytes the parser wants to keep are copied out with `extractBytes(length:)`, or referred to through +/// an owner with `extractBuffer(upTo:)` — both `internal`, like the rest of the reading surface; see +/// below. +/// +/// ## This is not the type to hand the parser +/// +/// If you are looking for how to give the parser bytes, you want ``ParserInputBuffer`` — in a +/// connection, ``IMAPInputBuffer``. `ParseInput` is `public` for one reason only: it appears in the +/// closure signature of ``ParserInputBuffer/withParseInput(limit:_:)`` and +/// ``ConsumableParserInputBuffer/parse(limit:_:)``, which a caller outside this module has to be able +/// to spell in order to conform. Everything that *reads* through a cursor — both initialisers, every +/// primitive, every combinator, and the read position itself — is `internal`. +/// +/// So there is nothing a client can do with one, and nothing it needs to do: no public API takes a +/// cursor. ``CommandParser/parseCommandStream(buffer:)`` and +/// ``ResponseParser/parseResponseStream(buffer:)`` take the *buffer* and open their own cursor over +/// it, and a conformer's obligation is to describe its bytes, not to read them — see +/// ``ParserInputBuffer``, whose gather is where every `ParseInput` is built. +/// +/// - Note: The reading surface becomes public if a parser entry point is ever added that takes a +/// cursor directly, so that one gather can serve several parses. Until then, treat the parameter as +/// opaque. +/// +/// ## The invariant +/// +/// `head` is empty **if and only if** the whole input is consumed. The initialisers establish that and +/// `advance(by:)` restores it, so every primitive may read the head's length as "bytes available right +/// now" and no primitive needs to know that regions exist. Do not reintroduce a per-primitive +/// "normalize first" precondition: it is an invariant to remember at a dozen sites, guarding a failure +/// mode that is silent — a multi-region extraction that stops after its first region. +/// +/// ## The limit +/// +/// `limit` caps how many bytes may ever be consumed through this cursor. It replaces clamping the input +/// down to a slice before parsing, so bytes past it are invisible to every primitive rather than merely +/// discouraged. +public struct ParseInput: ~Escapable { + /// Every region, in order. Empty for a single-span cursor. + private var table: ChunkTable + + /// The current region, already advanced past what has been consumed of it. + /// + /// Storing this is what forces `~Escapable`, and what makes the common case — a byte from the region + /// we are already in — a subscript rather than a table lookup. + private var head: Span + + /// Which entry of `table` `head` came from. + /// + /// `Int32` rather than `Int` so that ``lastParsedNewline`` fits in the same word and the cursor stays + /// compact. A table of more than two billion regions is not a thing that happens; + /// the gather bounds it far below that. + private var regionIndex: Int32 + + /// The line ending of the most recent ``matchNewline()``. + /// + /// It lives on the cursor because the caller that needs it — a response parser deciding whether a + /// bare CR was a split CRLF — is several grammar frames above the primitive that knows the answer, + /// and because ``composite(tracker:_:)``'s whole-value restore then rewinds it for free along with + /// the read position. + internal private(set) var lastParsedNewline: Newline? + + /// How many bytes have been consumed since this cursor was built. + /// + /// - Important: Relative to *this cursor*, not to the buffer it was gathered from. A staging type + /// that trims by this number must present its regions starting at its own read head; the + /// conformance requirement in the gather says so, and it is asserted there. + internal private(set) var consumed: Int + + /// The most bytes this cursor may ever consume. + internal private(set) var limit: Int + + /// Multi-region entry point. `owner` ties the cursor's lifetime to a borrow of whatever holds the + /// regions — the gather's own storage — so the table cannot outlive the bytes it describes. + @_lifetime(borrow owner) + internal init( + table: ChunkTable, + owner: borrowing Owner, + limit: Int = .max + ) { + self.table = table + self.head = table.isEmpty ? _span(UnsafeBufferPointer(start: nil, count: 0)) : _span(table[0].bytes) + self.regionIndex = 0 + self.lastParsedNewline = nil + self.consumed = 0 + self.limit = limit + self.normalizeHead() + } + + /// Single contiguous region. No table, no owner — so an extraction always copies, which is the right + /// answer when there is nobody to keep the bytes alive. + @_lifetime(copy bytes) + internal init(_ bytes: Span, limit: Int = .max) { + self.table = ChunkTable(start: nil, count: 0) + self.head = bytes + self.regionIndex = 0 + self.lastParsedNewline = nil + self.consumed = 0 + self.limit = limit + } +} + +// MARK: - The head invariant + +// `@_lifetime(self: copy self)` on mutating methods with parameters, here, in `ParseInput+Combinators.swift` +// and in `ParserInputBuffer.swift`, is what Swift 6.3+ infers. Swift 6.2 infers it only for methods without +// parameters. Remove once 6.4 is the minimum: https://github.com/apple/swift-nio-imap/issues/875 + +extension ParseInput { + /// Moves to the next region. Returns `false` when there is none. + private mutating func loadNext() -> Bool { + let next = Int(regionIndex) + 1 + guard next < table.count else { return false } + regionIndex = Int32(next) + head = _span(table[next].bytes) + return true + } + + /// Restores the invariant: `head` is empty only when the input is exhausted. + /// + /// Loops rather than loading one region, because a gather is allowed to hand over empty regions — the + /// recursive one skips them, the one-pass one is not obliged to. + @discardableResult + private mutating func normalizeHead() -> Bool { + while head.isEmpty { + guard loadNext() else { return false } + } + return true + } + + /// Bytes available in the current region without crossing a region boundary or the limit. + /// + /// This, not `head.count`, is what every primitive measures against: bytes past the limit are + /// invisible, and the cheapest way to hold that everywhere is to have one accessor say so. + private var headAvailable: Int { + Swift.min(head.count, limit - consumed) + } + + /// Consumes `n` bytes, or everything visible if `n` exceeds that, and restores the invariant. + /// + /// Note the loop shape: the take is computed, applied, and *only then* is the head refilled, so + /// landing exactly on a region boundary refills before returning. Advancing an exhausted cursor, or + /// advancing by zero, is a no-op that still leaves the invariant true. + @_lifetime(self: copy self) + internal mutating func advance(by n: Int) { + precondition(n >= 0, "cannot advance by \(n)") + var wanted = n + while true { + let take = Swift.min(wanted, headAvailable) + head = head.extracting(droppingFirst: take) + consumed += take + wanted -= take + guard normalizeHead() else { return } // exhausted; `wanted` may still be positive + if wanted == 0 || headAvailable == 0 { return } + } + } + + /// Narrows the limit to the next `count` bytes. + /// + /// This is how a caller that has to *look* at bytes before it knows how many of them may be parsed + /// clamps the cursor afterwards — the command parser frames synchronizing literals over everything + /// that has arrived, and only then knows how much of it is valid to parse. The alternative is + /// gathering the same regions twice, once per pass. + /// + /// - Parameter count: How many more bytes may be consumed. The limit only ever narrows, so passing + /// more than is already allowed leaves it alone. + @_lifetime(self: copy self) + internal mutating func narrowLimit(toNext count: Int) { + precondition(count >= 0, "cannot narrow the limit to \(count) bytes") + limit = Swift.min(limit, consumed + count) + } +} + +// MARK: - Reading without consuming + +extension ParseInput { + /// Whether any byte is available. + internal var isEmpty: Bool { + headAvailable == 0 + } + + /// How many bytes are visible, across every remaining region and inside the limit. + /// + /// O(regions remaining). Prefer ``isEmpty`` or a `peek` when that is the actual question. + internal var remaining: Int { + var total = head.count + var index = Int(regionIndex) + 1 + while index < table.count { + total += table[index].bytes.count + index += 1 + } + return Swift.min(total, limit - consumed) + } + + /// The byte `k` bytes ahead of the read position, or `nil` if it is past the end or the limit. + /// + /// Because the cursor is a `BitwiseCopyable` value, a cross-region look-ahead walks a *local copy* + /// rather than needing indexed access to the table. + internal func peek(at k: Int = 0) -> UInt8? { + precondition(k >= 0, "cannot peek at \(k)") + guard k < limit - consumed else { return nil } + if k < head.count { return head[k] } // fast path: no copy + var walker = copy self + var offset = k + while true { + offset -= walker.head.count + guard walker.loadNext() else { return nil } + if offset < walker.head.count { return walker.head[offset] } + } + } + + /// The next two bytes, or `nil` if fewer than two are visible. + internal func peek2() -> (UInt8, UInt8)? { + if 2 <= headAvailable { return (head[0], head[1]) } // fast path: one region, no copy + guard let first = peek(at: 0), let second = peek(at: 1) else { return nil } + return (first, second) + } + + /// Scoped access to the current contiguous run — for `memchr` and other bulk operations. + /// + /// Scoped rather than a property: a `Span` cannot be returned out of a borrow of the cursor, and a + /// chunk *iterator* is not expressible at all, which is why cross-region walks live in here rather + /// than in the grammar. + /// + /// By the invariant the span handed to `body` is empty only when the input is exhausted. It is + /// clamped to the limit, so a bulk operation cannot read past it. + internal func withCurrentChunk(_ body: (Span) throws -> R) rethrows -> R { + try body(head.extracting(first: headAvailable)) + } +} + +// MARK: - Bulk scans + +extension ParseInput { + /// The distance to the first occurrence of `byte`, or `nil` if it is not among the visible bytes. + /// + /// Non-consuming. `memchr` per region: a bounds-checked byte-at-a-time loop over the same bytes + /// is much slower, so this and ``scanWhile(_:)`` are the only two places that scan, and + /// everything that needs to find something goes through one of them. + internal func scanUntil(byte: UInt8) -> Int? { + var scanned = 0 + var walker = copy self + while true { + let available = walker.headAvailable + guard available > 0 else { return nil } + let hit = walker.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { buffer -> Int? in + guard let base = buffer.baseAddress, + let found = memchr(base, Int32(byte), buffer.count) + else { return nil } + return UnsafeRawPointer(found) - UnsafeRawPointer(base) + } + } + if let hit { return scanned + hit } + scanned += available + walker.advance(by: available) + } + } + + /// How many leading bytes satisfy `predicate`, or `nil` if *every* visible byte does. + /// + /// Non-consuming. `nil` means "the run might continue in bytes that have not arrived yet", which is + /// what both character-class parsers turn into `IncompleteMessage`. Callers therefore never have to + /// compare a count against the input length to work out which case they are in. + /// + /// The pointer is hoisted once per region: this is the primitive behind every atom and every number, + /// so a naive loop here would be the parser's slowest path rather than a detail. + internal func scanWhile(_ predicate: (UInt8) -> Bool) -> Int? { + var scanned = 0 + var walker = copy self + while true { + let available = walker.headAvailable + guard available > 0 else { return nil } + let stop = walker.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { buffer -> Int? in + for index in 0.. UInt8 { + guard let byte = peek(at: 0) else { throw IncompleteMessage() } + advance(by: 1) + return byte + } + + /// Consumes and copies the next `length` bytes. + /// + /// Copying is the right answer for everything the parsed model keeps as a small field: those are + /// bounded by ``IMAPDefaults/lineLengthLimit`` and almost always far smaller, so owning them + /// outright beats pinning the whole input. Raw message payloads go through + /// ``extractBuffer(upTo:)`` instead. + @_lifetime(self: copy self) + internal mutating func extractBytes(length: Int) throws -> [UInt8] { + precondition(length >= 0, "cannot extract \(length) bytes") + guard length > 0 else { return [] } + // Only walk the table when the answer isn't already in the current region. + guard headAvailable >= length || remaining >= length else { throw IncompleteMessage() } + var bytes = [UInt8]() + bytes.reserveCapacity(length) + var wanted = length + while wanted > 0 { + let take = Swift.min(wanted, headAvailable) + withCurrentChunk { chunk in + chunk.extracting(first: take).withUnsafeBufferPointer { bytes.append(contentsOf: $0) } + } + advance(by: take) + wanted -= take + } + return bytes + } + + /// Consumes raw message bytes — the streaming-literal path. + /// + /// Returns what is available, never more than `maxLength`, and never crossing a region boundary: a + /// short return costs the three streaming drivers one extra trip through their state machine and + /// nothing else, and it is what keeps an ``IMAPBuffer`` to one owner and one range. + /// + /// A run is handed out as a reference to the input's storage when the current region has an owner + /// and ``IMAPBuffer/retainsLiteral(byteCount:pinnedByteCount:)`` — at least 512 bytes, and at least a + /// third of what the owner keeps alive — so a multi-megabyte literal reaches the caller without + /// being copied, and a small one does not pin a large receive buffer. That decision lives here and + /// nowhere else, so no call site has to know which representation it got. + /// + /// - Important: The emptiness check is on the *input*, not on how many bytes are about to be taken. + /// `maxLength == 0` with bytes available returns an empty result rather than throwing, which is + /// what `APPEND … {0+}` needs: the command parser has no zero-remaining special case and relies on + /// getting an empty payload back so that it can move on to the end of the literal. + @_lifetime(self: copy self) + internal mutating func extractBuffer(upTo maxLength: Int) throws -> IMAPBuffer { + precondition(maxLength >= 0, "cannot extract up to \(maxLength) bytes") + let available = headAvailable + guard available > 0 else { throw IncompleteMessage() } + let take = Swift.min(maxLength, available) + if take >= IMAPBuffer.minimumRetainedLiteralByteCount, Int(regionIndex) < table.count { + let entry = table[Int(regionIndex)] + if let owner = entry.owner, + IMAPBuffer.retainsLiteral(byteCount: take, pinnedByteCount: owner.takeUnretainedValue().pinnedByteCount) + { + // The offset within the OWNER, not within the region: `ownerOffset` is where the region + // starts inside the owner's storage, and `bytes.count - head.count` is how far into the + // region we already are. Dropping either term returns the wrong bytes. + let offset = entry.ownerOffset + (entry.bytes.count - head.count) + advance(by: take) + return IMAPBuffer(owner.takeUnretainedValue(), offset..<(offset + take)) + } + } + return IMAPBuffer(try extractBytes(length: take)) + } +} + +// MARK: - Matching + +extension ParseInput { + /// How ``matchFixed(_:caseSensitivity:)`` compares letters. + enum CaseSensitivity { + /// `SELECT` matches only `SELECT`. + case caseSensitive + /// `SELECT` also matches `select` and `Select`: what IMAP keywords need. + case caseInsensitive + } + + /// Consumes `needle` if it is next, and consumes nothing otherwise. + /// + /// - Parameters: + /// - needle: The bytes to match. Must be ASCII. + /// - caseSensitivity: How to compare letters. ASCII case folding is a mask, so the insensitive + /// compare costs nothing extra. + /// - Throws: `IncompleteMessage` when everything that has arrived matches a prefix of `needle`, so + /// more bytes could still complete it; ``ParserError`` when a byte disagrees, which no + /// continuation can fix. + @_lifetime(self: copy self) + internal mutating func matchFixed(_ needle: String, caseSensitivity: CaseSensitivity = .caseInsensitive) throws { + assert(needle.utf8.allSatisfy { $0 & 0b1000_0000 == 0 }, "needle needs to be ASCII but \(needle) isn't") + let caseSensitive = caseSensitivity == .caseSensitive + let mask: UInt8 = caseSensitive ? 0xFF : 0xDF + let count = needle.utf8.count + // Fast path: the whole needle is in the current region, so compare through two hoisted pointers. + // This runs on every failed alternative of every `parseOneOf`, which is most of the parser's work. + if count <= headAvailable { + let matches = withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { buffer in + Self.bytesMatch(buffer, needle: needle, mask: mask) + } + } + guard matches else { + throw ParserError(hint: caseSensitive ? "Fixed string mismatch" : "Fixed string mismatch (ci)") + } + advance(by: count) + return + } + var offset = 0 + for expected in needle.utf8 { + guard let byte = peek(at: offset) else { throw IncompleteMessage() } + guard byte & mask == expected & mask else { + throw ParserError(hint: caseSensitive ? "Fixed string mismatch" : "Fixed string mismatch (ci)") + } + offset += 1 + } + advance(by: offset) + } + + /// Whether `buffer` starts with `needle`, comparing under `mask`. + /// + /// `static` so that the closure below captures the needle rather than the cursor: handing a + /// `self`-capturing closure to something that also borrows `self` is what makes the compiler take a + /// copy, and on the encode side that cost an allocation per call before anyone noticed. + /// + /// `utf8Span` is what the package's macOS 26 floor buys here: the needle's bytes come out as a + /// `Span` with no optional to unwrap and no fallback path for a string that turns out not to be + /// contiguous, which is what `withContiguousStorageIfAvailable` needs and what makes the same + /// comparison in the encoder longer than this one. + private static func bytesMatch(_ buffer: UnsafeBufferPointer, needle: String, mask: UInt8) -> Bool { + let expected = needle.utf8Span.span + for index in 0.. Newline { + let (newline, length) = try newlineAhead() + advance(by: length) + lastParsedNewline = newline + return newline + } + + /// Most stray spaces tolerated before a line ending. + /// + /// Lenient towards peers that pad lines, but bounded so a hostile run of spaces cannot make the + /// parser scan without limit. 1024 is far beyond any real padding. + internal static let maximumStraySpaces = 1024 + + /// The line ending at the read position, and how many bytes it takes up including skipped spaces. + private func newlineAhead() throws -> (Newline, Int) { + // One linear pass over the spaces: `peek(at:)` walks from the head each call, so peeking at a + // growing offset would be quadratic in the spaces times the regions. + // The scan stops one past the cap, so a hostile run is not read in full. A space at `offset` + // after that means the cap was exceeded, and falls through to the error below. + var scanned = 0 + let spaces = scanWhile { byte in + scanned += 1 + return byte == UInt8(ascii: " ") && scanned <= Self.maximumStraySpaces + } + // Only spaces so far, within the cap: more spaces, or the line ending, may still arrive. + guard let offset = spaces else { throw IncompleteMessage() } + + guard let first = peek(at: offset) else { throw IncompleteMessage() } + guard let second = peek(at: offset + 1) else { + // One byte, and no more may ever arrive as far as this cursor is concerned. + switch first { + case UInt8(ascii: "\n"): return (.lf, offset + 1) + case UInt8(ascii: "\r"): return (.cr, offset + 1) + default: throw ParserError(hint: "Expected newline") + } + } + switch (first, second) { + case (UInt8(ascii: "\r"), UInt8(ascii: "\n")): return (.crlf, offset + 2) + case (UInt8(ascii: "\n"), _): return (.lf, offset + 1) + case (UInt8(ascii: "\r"), _): return (.cr, offset + 1) + default: throw ParserError(hint: "Expected newline") + } + } + + /// Consumes a leading `LF`, if there is one. Reports whether it did. + /// + /// This is how a CRLF split across two reads is stitched back together: the CR ended one parse and + /// the LF is skipped at the start of the next. + @discardableResult + internal mutating func skipLF() -> Bool { + guard peek(at: 0) == UInt8(ascii: "\n") else { return false } + advance(by: 1) + return true + } +} + +extension ParseInput { + /// A line ending kind. + internal enum Newline: Sendable, Hashable { + case crlf + case cr + case lf + } +} + +/// `ParseInput` is deliberately **not** `Sendable`, and could not honestly be. +/// +/// It holds pointers into somebody else's bytes that are valid only for the gather that produced it, and +/// being non-escapable is what enforces that. What crosses a thread is what the parser *extracted* — an +/// `[UInt8]` or an ``IMAPBuffer``, both of which own or retain their bytes. +@available(*, unavailable) +extension ParseInput: Sendable {} + +// MARK: - Backtracking + +extension ParseInput { + /// Runs `body`, and restores the read position if it throws. + /// + /// This is the parser's backtracking primitive, and it is why the cursor is a small + /// `BitwiseCopyable` value: the save is a `memcpy` and the restore is another, with no reference + /// counting, and it runs on every alternative of every `parseOneOf`. + /// + /// `let save = copy self` completes before `body(&self, …)` is called, so there is no overlapping + /// access to `self` even though both mention it. + @_lifetime(self: copy self) + internal mutating func composite( + tracker: StackTracker, + _ body: (inout ParseInput, StackTracker) throws -> T + ) throws -> T { + var tracker = tracker + try tracker.newStackFrame() + let save = copy self + do { + return try body(&self, tracker) + } catch { + self = save + throw error + } + } +} diff --git a/Sources/NIOIMAPCore/Parser/ParserErrors.swift b/Sources/NIOIMAPCore/Parser/ParserErrors.swift index d87e9e3d..10d4ba01 100644 --- a/Sources/NIOIMAPCore/Parser/ParserErrors.swift +++ b/Sources/NIOIMAPCore/Parser/ParserErrors.swift @@ -12,6 +12,24 @@ // //===----------------------------------------------------------------------===// +/// Decodes `bytes` as UTF-8. +/// +/// A free function rather than a `String` initialiser because it throws a ``ParserError`` carrying the +/// source location that asked for the decode, which is what the grammar wants and what a general-purpose +/// initialiser has no business reporting. +/// +/// - Throws: ``ParserError`` when `bytes` are not valid UTF-8. +func decodeUTF8( + _ bytes: some Collection, + file: String = (#fileID), + line: Int = #line +) throws -> String { + guard let string = String(validatingUTF8Bytes: bytes) else { + throw ParserError.invalidUTF8(file: file, line: line) + } + return string +} + /// The parser needs more bytes before it can decide. /// /// Thrown, rather than returned, because it can arise anywhere in the grammar; the entry points turn diff --git a/Sources/NIOIMAPCore/Parser/ParserLibrary.swift b/Sources/NIOIMAPCore/Parser/ParserLibrary.swift index 227f3b50..c78fa269 100644 --- a/Sources/NIOIMAPCore/Parser/ParserLibrary.swift +++ b/Sources/NIOIMAPCore/Parser/ParserLibrary.swift @@ -17,7 +17,9 @@ import struct OrderedCollections.OrderedDictionary enum ParserLibrary {} -typealias SubParser = (inout ParseBuffer, StackTracker) throws -> T +// Temporary: renamed to coexist with `SubParser` in ParseInput+Combinators.swift; removed in +// "Parse from ParseInput instead of ByteBuffer". +typealias LegacySubParser = (inout ParseBuffer, StackTracker) throws -> T internal struct ParseBuffer: Hashable { fileprivate var bytes: ByteBuffer @@ -124,8 +126,11 @@ extension ParserLibrary { } } - static func parseOneOrMore(buffer: inout ParseBuffer, tracker: StackTracker, parser: SubParser) throws -> [T] - { + static func parseOneOrMore( + buffer: inout ParseBuffer, + tracker: StackTracker, + parser: LegacySubParser + ) throws -> [T] { var parsed: [T] = [] try Self.parseOneOrMore(buffer: &buffer, into: &parsed, tracker: tracker, parser: parser) return parsed @@ -135,7 +140,7 @@ extension ParserLibrary { buffer: inout ParseBuffer, into parsed: inout [T], tracker: StackTracker, - parser: SubParser + parser: LegacySubParser ) throws { try PL.composite(buffer: &buffer, tracker: tracker) { buffer, tracker in parsed.append(try parser(&buffer, tracker)) @@ -149,7 +154,7 @@ extension ParserLibrary { buffer: inout ParseBuffer, into parsed: inout [T], tracker: StackTracker, - parser: SubParser + parser: LegacySubParser ) throws { try PL.composite(buffer: &buffer, tracker: tracker) { buffer, tracker in while let next = try PL.parseOptional(buffer: &buffer, tracker: tracker, parser: parser) { @@ -162,7 +167,7 @@ extension ParserLibrary { buffer: inout ParseBuffer, into orderedDictionary: inout OrderedDictionary, tracker: StackTracker, - parser: SubParser<(K, V)> + parser: LegacySubParser<(K, V)> ) throws { try PL.composite(buffer: &buffer, tracker: tracker) { buffer, tracker in while let next = try PL.parseOptional(buffer: &buffer, tracker: tracker, parser: parser) { @@ -175,7 +180,7 @@ extension ParserLibrary { buffer: inout ParseBuffer, into orderedDictionary: inout OrderedDictionary, tracker: StackTracker, - parser: SubParser> + parser: LegacySubParser> ) throws { try PL.composite(buffer: &buffer, tracker: tracker) { buffer, tracker in while let next = try PL.parseOptional(buffer: &buffer, tracker: tracker, parser: parser) { @@ -184,8 +189,11 @@ extension ParserLibrary { } } - static func parseZeroOrMore(buffer: inout ParseBuffer, tracker: StackTracker, parser: SubParser) throws -> [T] - { + static func parseZeroOrMore( + buffer: inout ParseBuffer, + tracker: StackTracker, + parser: LegacySubParser + ) throws -> [T] { var parsed: [T] = [] try Self.parseZeroOrMore(buffer: &buffer, into: &parsed, tracker: tracker, parser: parser) return parsed @@ -301,7 +309,7 @@ extension ParserLibrary { } static func parseOneOf( - _ subParsers: [SubParser], + _ subParsers: [LegacySubParser], buffer: inout ParseBuffer, tracker: StackTracker, file: String = (#fileID), @@ -320,8 +328,8 @@ extension ParserLibrary { } static func parseOneOf( - _ parser1: SubParser, - _ parser2: SubParser, + _ parser1: LegacySubParser, + _ parser2: LegacySubParser, buffer: inout ParseBuffer, tracker: StackTracker, file: String = (#fileID), @@ -344,9 +352,9 @@ extension ParserLibrary { } static func parseOneOf( - _ parser1: SubParser, - _ parser2: SubParser, - _ parser3: SubParser, + _ parser1: LegacySubParser, + _ parser2: LegacySubParser, + _ parser3: LegacySubParser, buffer: inout ParseBuffer, tracker: StackTracker, file: String = (#fileID), @@ -379,7 +387,11 @@ extension ParserLibrary { } } - static func parseOptional(buffer: inout ParseBuffer, tracker: StackTracker, parser: SubParser) throws -> T? { + static func parseOptional( + buffer: inout ParseBuffer, + tracker: StackTracker, + parser: LegacySubParser + ) throws -> T? { do { return try PL.composite(buffer: &buffer, tracker: tracker, parser) } catch is ParserError { @@ -387,7 +399,7 @@ extension ParserLibrary { } } - static func composite(buffer: inout ParseBuffer, tracker: StackTracker, _ body: SubParser) throws -> T { + static func composite(buffer: inout ParseBuffer, tracker: StackTracker, _ body: LegacySubParser) throws -> T { var tracker = tracker try tracker.newStackFrame() diff --git a/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferDispatchDataTests.swift b/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferDispatchDataTests.swift new file mode 100644 index 00000000..15488f17 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferDispatchDataTests.swift @@ -0,0 +1,254 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// Public API only — no `@testable`, no `@_spi`: a transport that reads into `DispatchData` uses exactly this. +import Dispatch +import Foundation // `DispatchData.regions` +import NIOIMAPCore +import Testing + +/// One `DispatchData` holding `parts` as separate regions: concatenating copies nothing. +private func dispatchData(_ parts: [[UInt8]]) -> DispatchData { + var data = DispatchData.empty + for part in parts { + part.withUnsafeBytes { data.append(DispatchData(bytes: $0)) } + } + return data +} + +/// The address of each of `data`'s regions. +private func regionAddresses(_ data: DispatchData) -> [UnsafeRawPointer?] { + var addresses: [UnsafeRawPointer?] = [] + data.enumerateBytes { bytes, _, _ in addresses.append(UnsafeRawPointer(bytes.baseAddress)) } + return addresses +} + +/// Every byte `input` holds, in order. +private func contents(_ input: IMAPInputBuffer) -> [UInt8] { + input.byteRegions.flatMap { region in region.withUnsafeBytes { Array($0) } } +} + +/// Which deallocators have run. Touched only on the deallocator queue, so `@unchecked` is safe. +private final class Deallocations: @unchecked Sendable { + var freed: Set = [] +} + +/// `DispatchData` over `byteCount` bytes of `fill`, freed on `queue`, so a drained `queue` has run any +/// deallocator that is due. The deallocator zeroes the bytes first, so a read after it sees no `fill`. +private func trackedData( + _ name: String, + byteCount: Int, + fill: UInt8, + queue: DispatchQueue, + deallocations: Deallocations +) -> DispatchData { + // Only the deallocator touches `bytes` once `DispatchData` owns it. + nonisolated(unsafe) let bytes = UnsafeMutableRawBufferPointer.allocate(byteCount: byteCount, alignment: 1) + bytes.initializeMemory(as: UInt8.self, repeating: fill) + return DispatchData( + bytesNoCopy: UnsafeRawBufferPointer(bytes), + deallocator: .custom(queue) { + bytes.initializeMemory(as: UInt8.self, repeating: 0) + bytes.deallocate() + deallocations.freed.insert(name) + } + ) +} + +@Suite("IMAPInputBuffer.append(contentsOf: DispatchData)") +struct IMAPInputBufferDispatchDataTests { + /// The smallest region kept by reference. + static let large = IMAPBuffer.copyThreshold + /// A region copied into the tail. + static let small = 10 + + @Test("keeps large regions where they are and coalesces small ones, bytes in order") + func mixedRegions() { + let parts: [[UInt8]] = [ + Array(repeating: UInt8(ascii: "a"), count: Self.small), + Array(repeating: UInt8(ascii: "b"), count: Self.large), + Array(repeating: UInt8(ascii: "c"), count: Self.small), + Array(repeating: UInt8(ascii: "d"), count: Self.small), + Array(repeating: UInt8(ascii: "e"), count: 2 * Self.large), + ] + let data = dispatchData(parts) + let leaves = regionAddresses(data) + #expect(leaves.count == parts.count, "precondition: one region per part") + + var input = IMAPInputBuffer() + input.append(contentsOf: data) + + #expect(contents(input) == parts.flatMap { $0 }) + #expect(input.count == parts.reduce(0) { $0 + $1.count }) + // a | b | c d | e + #expect(input.regionCount == 4) + #expect(input.byteRegions[1].withUnsafeBytes { UnsafeRawPointer($0.baseAddress) } == leaves[1]) + #expect(input.byteRegions[3].withUnsafeBytes { UnsafeRawPointer($0.baseAddress) } == leaves[4]) + } + + @Test("copies only-small regions into one tail") + func smallRegionsOnly() { + let parts: [[UInt8]] = [Array("A1 ".utf8), Array("NOOP".utf8), Array("\r\n".utf8)] + let data = dispatchData(parts) + #expect(regionAddresses(data).count == parts.count, "precondition: one region per part") + + var input = IMAPInputBuffer() + input.append(contentsOf: data) + + #expect(contents(input) == Array("A1 NOOP\r\n".utf8)) + #expect(input.regionCount == 1) + } + + @Test("appending an empty DispatchData does nothing") + func empty() { + var input = IMAPInputBuffer() + input.append(contentsOf: .empty) + #expect(input.isEmpty) + #expect(input.regionCount == 0) + + input.append(contentsOf: dispatchData([Array("A1".utf8)])) + input.append(contentsOf: .empty) + #expect(contents(input) == Array("A1".utf8)) + #expect(input.regionCount == 1) + } + + @Test("a kept region keeps the DispatchData's storage alive after the DispatchData is gone") + func keptRegionOutlivesData() { + let queue = DispatchQueue(label: "IMAPInputBufferDispatchDataTests.deallocator") + let deallocations = Deallocations() + let fill = UInt8(ascii: "k") + + var input = IMAPInputBuffer() + do { + let kept = trackedData( + "kept", + byteCount: Self.large, + fill: fill, + queue: queue, + deallocations: deallocations + ) + input.append(contentsOf: kept) + _ = trackedData("dropped", byteCount: Self.large, fill: fill, queue: queue, deallocations: deallocations) + } + queue.sync {} + + #expect(queue.sync { deallocations.freed } == ["dropped"]) + #expect(contents(input) == Array(repeating: fill, count: Self.large)) + } + + // corelibs-libdispatch marks `DispatchData.Region`'s `Sendable` conformance unavailable. + #if canImport(Darwin) + /// A `DispatchData.Region` is a pointer into its `DispatchData` and does not retain it. + @Test("a large DispatchData.Region appended on its own is copied, so it outlives the DispatchData") + func regionIsCopied() throws { + let queue = DispatchQueue(label: "IMAPInputBufferDispatchDataTests.deallocator") + let deallocations = Deallocations() + let fill = UInt8(ascii: "r") + + var input = IMAPInputBuffer() + do { + let data = trackedData( + "region", + byteCount: Self.large, + fill: fill, + queue: queue, + deallocations: deallocations + ) + input.append(try #require(data.regions.first)) + } + queue.sync {} + + #expect(queue.sync { deallocations.freed } == ["region"], "precondition: nothing keeps the data alive") + #expect(contents(input) == Array(repeating: fill, count: Self.large)) + } + + @Test("makeDispatchData of an IMAPBuffer over a DispatchData.Region outlives the DispatchData") + func regionBufferConversionOutlivesData() throws { + let queue = DispatchQueue(label: "IMAPInputBufferDispatchDataTests.deallocator") + let deallocations = Deallocations() + let fill = UInt8(ascii: "c") + + let converted: DispatchData + do { + let data = trackedData( + "region", + byteCount: Self.large, + fill: fill, + queue: queue, + deallocations: deallocations + ) + converted = IMAPBuffer(IMAPByteStorage(try #require(data.regions.first))).makeDispatchData() + } + queue.sync {} + + #expect(queue.sync { deallocations.freed } == ["region"], "precondition: nothing keeps the data alive") + #expect(Array(converted) == Array(repeating: fill, count: Self.large)) + } + + @Test("withUnsafeBytesAndOwner on an IMAPBuffer over a DispatchData.Region: the owner keeps the bytes") + func regionBufferOwnerKeepsBytes() throws { + let queue = DispatchQueue(label: "IMAPInputBufferDispatchDataTests.deallocator") + let deallocations = Deallocations() + let fill = UInt8(ascii: "o") + + let escaped: (bytes: UnsafeRawBufferPointer, owner: any Sendable)? + do { + let data = trackedData( + "region", + byteCount: Self.large, + fill: fill, + queue: queue, + deallocations: deallocations + ) + let buffer = IMAPBuffer(IMAPByteStorage(try #require(data.regions.first))) + escaped = buffer.withUnsafeBytesAndOwner { ($0, $1) } + } + queue.sync {} + + // No pointer is a valid answer; a pointer must stay valid while its owner is held. + guard let escaped else { return } + #expect( + withExtendedLifetime(escaped.owner) { Array(escaped.bytes) } == Array(repeating: fill, count: Self.large) + ) + } + #endif + + @Test("a kept region is donated to makeDispatchData, and the donation keeps the DispatchData alive") + func keptRegionIsDonated() throws { + let queue = DispatchQueue(label: "IMAPInputBufferDispatchDataTests.deallocator") + let deallocations = Deallocations() + let fill = UInt8(ascii: "d") + + let converted: DispatchData + let leaf: UnsafeRawPointer? + do { + let data = trackedData( + "kept", + byteCount: Self.large, + fill: fill, + queue: queue, + deallocations: deallocations + ) + leaf = try #require(regionAddresses(data).first) + var input = IMAPInputBuffer() + input.append(contentsOf: data) + converted = input.byteRegions[0].makeDispatchData() + } + queue.sync {} + + #expect(queue.sync { deallocations.freed }.isEmpty) + #expect(regionAddresses(converted) == [leaf], "donated, not copied") + #expect(Array(converted) == Array(repeating: fill, count: Self.large)) + } +} diff --git a/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferTests.swift b/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferTests.swift new file mode 100644 index 00000000..0d6432d1 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Bytes/IMAPInputBufferTests.swift @@ -0,0 +1,499 @@ +//===----------------------------------------------------------------------===// +// +// 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 Dispatch +import Foundation +import Testing + +/// Coverage for the buffer a connection accumulates received bytes into. +/// +/// Three properties are the reason this type exists rather than an array, and each one has a test here +/// that an array would fail: appending does not copy, discarding a prefix does not move the remainder, +/// and a payload handed to a caller stays valid after the buffer has moved past it. +@Suite("IMAPInputBuffer") +struct IMAPInputBufferTests {} + +// MARK: - Helpers + +/// Whether a deallocator has run. Touched only on the deallocator queue, so `@unchecked` is safe. +private final class Deallocation: @unchecked Sendable { + var hasRun = false +} + +extension IMAPInputBufferTests { + private static func buffer(_ pieces: [String]) -> IMAPInputBuffer { + var buffer = IMAPInputBuffer() + for piece in pieces { buffer.append(Array(piece.utf8)) } + return buffer + } + + private static func text(_ buffer: IMAPInputBuffer) -> String { + buffer.byteRegions.map { String(decoding: $0.copiedBytes(), as: UTF8.self) }.joined() + } + + /// A read big enough to be kept as its own region rather than copied into a tail. + private static func large(_ letter: Character) -> String { + String(repeating: letter, count: IMAPBuffer.copyThreshold) + } + + /// Where region `index` currently starts. The view is released before this returns, so it does not + /// count as a reference to the region afterwards. + private static func address(of index: Int, in buffer: IMAPInputBuffer) -> UInt { + buffer.byteRegions[index].withUnsafeBytes { UInt(bitPattern: $0.baseAddress) } + } +} + +// MARK: - Appending + +extension IMAPInputBufferTests { + @Test("Appending adds bytes and regions") + func appending() { + var buffer = IMAPInputBuffer() + #expect(buffer.isEmpty) + #expect(buffer.count == 0) + #expect(buffer.regionCount == 0) + + buffer.append(Array("A001 ".utf8)) + buffer.append(Array("NOOP\r\n".utf8)) + #expect(buffer.count == 11) + #expect(buffer.regionCount == 1, "two small reads share a tail") + #expect(buffer.isEmpty == false) + #expect(buffer.description == "IMAPInputBuffer(11 bytes in 1 region)") + + buffer.append(Array(Self.large("x").utf8)) + #expect(buffer.description == "IMAPInputBuffer(1035 bytes in 2 regions)") + } + + @Test("Appending nothing does nothing") + func appendingEmpty() { + // Worth pinning: an empty region in the queue would make `chunks.first` present with no bytes to + // read, which is the state the cursor's head invariant exists to rule out. + var buffer = IMAPInputBuffer() + buffer.append([UInt8]()) + #expect(buffer.regionCount == 0) + buffer.append(Array("x".utf8)) + buffer.append([UInt8]()) + #expect(buffer.regionCount == 1) + #expect(buffer.count == 1) + } + + @Test("Appended bytes are parsed where they lie, not copied") + func appendingDoesNotCopy() throws { + let payload = Array(repeating: UInt8(ascii: "p"), count: 2048) + // The array's storage does not move while it is alive, and appending it retains that storage + // rather than copying it — so this address must come back out of the parser. + let appendedAt = payload.withUnsafeBytes { $0.baseAddress! } + var buffer = IMAPInputBuffer() + buffer.append(payload) + let extracted = try buffer.parse { try $0.extractBuffer(upTo: payload.count) } + #expect(extracted.withUnsafeBytes { $0.baseAddress! } == appendedAt) + } +} + +// MARK: - Discarding + +extension IMAPInputBufferTests { + @Test("Discarding part of the first region moves the read head") + func discardWithinARegion() { + var buffer = Self.buffer(["abcdef"]) + buffer.discardFirst(2) + #expect(buffer.count == 4) + #expect(buffer.regionCount == 1, "the region is sliced, not dropped") + #expect(Self.text(buffer) == "cdef") + } + + @Test("Discarding a whole region drops it") + func discardWholeRegions() { + let size = IMAPBuffer.copyThreshold + var buffer = Self.buffer([Self.large("a"), Self.large("b"), Self.large("c")]) + buffer.discardFirst(size) + #expect(buffer.regionCount == 2) + #expect(Self.text(buffer) == Self.large("b") + Self.large("c")) + + buffer.discardFirst(2 * size - 2) + #expect(buffer.count == 2) + #expect(buffer.regionCount == 1) + #expect(Self.text(buffer) == "cc") + + buffer.discardFirst(2) + #expect(buffer.isEmpty) + #expect(buffer.regionCount == 0) + } + + @Test("Discarding nothing, and discarding everything") + func discardEdges() { + var buffer = Self.buffer(["abc", "def"]) + buffer.discardFirst(0) + #expect(buffer.count == 6) + buffer.discardFirst(6) + #expect(buffer.isEmpty) + #expect(Self.text(buffer) == "") + + buffer.append(Array("gh".utf8)) + #expect(Self.text(buffer) == "gh", "a buffer that has been drained is still usable") + } + + @Test("Removing everything keeps the buffer usable") + func removeAll() { + var buffer = Self.buffer(["abc", "def"]) + buffer.removeAll() + #expect(buffer.isEmpty) + #expect(buffer.regionCount == 0) + buffer.append(Array("xy".utf8)) + #expect(Self.text(buffer) == "xy") + } + + @Test("The regions begin at the read head and add up to the count") + func regionsBeginAtTheReadHead() { + // The conformance requirement the gather asserts. A buffer that handed over the consumed prefix + // as well would have the parser report consuming bytes it was shown twice, and the trim would + // then skip past bytes nobody parsed. + let first = "abcd" + Self.large("p") + var buffer = Self.buffer([first, Self.large("q")]) + buffer.discardFirst(3) + let regions = buffer.byteRegions + #expect(regions.count == 2) + #expect(regions[0].copiedBytes() == Array(first.utf8.dropFirst(3))) + #expect(regions[1].copiedBytes() == Array(Self.large("q").utf8)) + #expect(regions.reduce(0) { $0 + $1.count } == buffer.count) + } +} + +// MARK: - Parsing + +extension IMAPInputBufferTests { + @Test("A message split across two reads is parsed across them") + func straddlingMessage() throws { + // No copy: two large reads stay where they are and the cursor walks from one into the other. + let first = "A001 " + Self.large("x") + let second = Self.large("y") + "\r\nA002 " + var buffer = Self.buffer([first, second]) + let lineLength = first.utf8.count + IMAPBuffer.copyThreshold + 2 + let line = try buffer.parse { try $0.extractBytes(length: lineLength) } + #expect(String(decoding: line, as: UTF8.self) == first + Self.large("y") + "\r\n") + #expect(buffer.count == 5) + #expect(buffer.regionCount == 1, "the used-up first region is gone") + #expect(Self.text(buffer) == "A002 ") + } + + @Test("A payload outlives the bytes' place in the queue") + func payloadOutlivesTheBuffer() throws { + // This is what "the buffer owns its runs" buys, and it is why `count` counts live bytes rather + // than allocated ones: the run stays alive as long as somebody is holding a payload from it, even + // though the buffer has moved on. + let payload = Array(repeating: UInt8(ascii: "q"), count: 4096) + var buffer = IMAPInputBuffer() + buffer.append(payload) + let extracted = try buffer.parse { try $0.extractBuffer(upTo: payload.count) } + #expect(buffer.isEmpty) + #expect(extracted.retainedRegion != nil, "a payload this size should not have been copied") + + buffer.removeAll() + buffer.append(Array(repeating: UInt8(ascii: "z"), count: 4096)) + #expect(extracted.copiedBytes() == payload) + } + + @Test("Many regions parse in one pass, at any count") + func manyRegions() throws { + // The one-pass gather has no recursion, so this costs no stack no matter how many regions there + // are — the case the recursive gather has to cap and coalesce. Each read is large enough to stay + // its own region. + let regionCount = 2000 + let reads = (0..(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + var temporary = bytes + return try temporary.withUnsafeMutableBytes { try body(UnsafeRawBufferPointer($0)) } + } + } + + /// The storage behind region `index`, which every large read is kept in. + private static func storage(of index: Int, in buffer: IMAPInputBuffer) throws -> IMAPByteStorage { + try #require(buffer.byteRegions[index].retainedRegion).storage + } + + @Test("A large Data is copied: it may flatten into a temporary buffer") + func largeDataIsCopied() throws { + let data = Data(repeating: UInt8(ascii: "d"), count: 2 * IMAPBuffer.copyThreshold) + var buffer = IMAPInputBuffer() + buffer.append(data) + let storage = try Self.storage(of: 0, in: buffer) + #expect(storage.wrappedRegion(as: Data.self) == nil) + #expect(storage.hasStableAddress) + #expect(Self.address(of: 0, in: buffer) != data.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) }) + #expect(buffer.byteRegions[0].copiedBytes() == Array(data)) + } + + @Test("A large region that yields temporary bytes is copied") + func largeUnstableRegionIsCopied() throws { + let bytes = Array(repeating: UInt8(ascii: "u"), count: IMAPBuffer.copyThreshold) + var buffer = IMAPInputBuffer() + buffer.append(UnstableRegion(bytes: bytes)) + let storage = try Self.storage(of: 0, in: buffer) + #expect(storage.wrappedRegion(as: UnstableRegion.self) == nil) + #expect(storage.hasStableAddress) + #expect(buffer.byteRegions[0].copiedBytes() == bytes) + } + + @Test("Large regions with a fixed address are retained, not copied") + func largeStableRegionsAreRetained() throws { + let wrapped = IMAPBuffer(Array(repeating: UInt8(ascii: "b"), count: IMAPBuffer.copyThreshold)) + + var buffer = IMAPInputBuffer() + buffer.append(wrapped) + #expect(try Self.storage(of: 0, in: buffer).wrappedRegion(as: IMAPBuffer.self) != nil) + #expect(Self.address(of: 0, in: buffer) == wrapped.withUnsafeBytes { UInt(bitPattern: $0.baseAddress) }) + } + + @Test("An IMAPBuffer over storage with no fixed address is copied") + func imapBufferOverUnstableStorageIsCopied() throws { + let bytes = Array(repeating: UInt8(ascii: "s"), count: IMAPBuffer.copyThreshold) + var buffer = IMAPInputBuffer() + buffer.append(IMAPBuffer(IMAPByteStorage(UnstableRegion(bytes: bytes)))) + #expect(try Self.storage(of: 0, in: buffer).wrappedRegion(as: IMAPBuffer.self) == nil) + #expect(buffer.byteRegions[0].copiedBytes() == bytes) + } + + @Test("A copied Data parses, and a large extraction refers to the copy") + func parseFromCopiedData() throws { + let header = "* 1 FETCH (BODY[] {2048}\r\n" + let literal = Self.large("L") + Self.large("M") + var buffer = IMAPInputBuffer() + buffer.append(Data((header + literal).utf8)) + let copy = try Self.storage(of: 0, in: buffer) + + let parsed = try buffer.parse { input in + (try input.extractBytes(length: header.utf8.count), try input.extractBuffer(upTo: literal.utf8.count)) + } + #expect(String(decoding: parsed.0, as: UTF8.self) == header) + #expect(String(decoding: parsed.1.copiedBytes(), as: UTF8.self) == literal) + #expect(parsed.1.retainedRegion?.storage === copy) + #expect(buffer.isEmpty) + } + + @Test("A payload parsed from a DispatchData is donated, and the donation keeps the DispatchData alive") + func parsedDispatchPayloadIsDonated() throws { + let header = "* 1 FETCH (BODY[] {1024}\r\n" + let literal = Array(Self.large("P").utf8) + let queue = DispatchQueue(label: "IMAPInputBufferTests.deallocator") + let deallocation = Deallocation() + + let converted: DispatchData + let leaf: UInt + do { + // Header and literal as two regions; only the literal is large enough to be kept. + // Only the deallocator touches `payload` once `DispatchData` owns it. + nonisolated(unsafe) let payload = UnsafeMutableRawBufferPointer.allocate( + byteCount: literal.count, + alignment: 1 + ) + literal.withUnsafeBytes { payload.copyMemory(from: $0) } + leaf = UInt(bitPattern: payload.baseAddress) + var data = Array(header.utf8).withUnsafeBytes { DispatchData(bytes: $0) } + data.append( + DispatchData( + bytesNoCopy: UnsafeRawBufferPointer(payload), + deallocator: .custom(queue) { + payload.initializeMemory(as: UInt8.self, repeating: 0) + payload.deallocate() + deallocation.hasRun = true + } + ) + ) + var buffer = IMAPInputBuffer() + buffer.append(contentsOf: data) + let parsed = try buffer.parse { input in + _ = try input.extractBytes(length: header.utf8.count) + return try input.extractBuffer(upTo: literal.count) + } + #expect(parsed.retainedRegion != nil, "precondition: extracted by reference") + converted = parsed.makeDispatchData() + } + queue.sync {} + + #expect(queue.sync { deallocation.hasRun } == false) + var addresses: [UInt] = [] + converted.enumerateBytes { bytes, _, _ in addresses.append(UInt(bitPattern: bytes.baseAddress)) } + #expect(addresses == [leaf], "donated, not copied") + #expect(Array(converted) == literal) + } +} diff --git a/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift b/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift index 34b0f3aa..c500edc6 100644 --- a/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift +++ b/Tests/NIOIMAPCoreTests/Bytes/StableAddressByteRegionTests.swift @@ -66,6 +66,12 @@ private func wrapGenerically(_ region: some ByteRegion & Sendable) -> IMAPBuffer IMAPBuffer(IMAPByteStorage(region)) } +/// Appends `region` from generic code that knows only `ByteRegion`, which takes the overload that checks +/// at run time. +private func appendGenerically(_ region: some ByteRegion & Sendable, to input: inout IMAPInputBuffer) { + input.append(region) +} + @Suite("A third-party StableAddressByteRegion") struct StableAddressByteRegionTests { /// Large enough to be kept by reference wherever the library has a size cut-off (1 KiB). @@ -81,6 +87,56 @@ struct StableAddressByteRegionTests { #expect(leaf == foreign.baseAddress) } + @Test("is kept by IMAPInputBuffer, not copied") + func inputBufferRetains() { + let foreign = ForeignBuffer(storage: ForeignStorage(repeating: UInt8(ascii: "f"), count: Self.byteCount)) + var input = IMAPInputBuffer() + input.append(foreign) + #expect(input.count == Self.byteCount) + #expect(input.byteRegions[0].withUnsafeBytes { UnsafeRawPointer($0.baseAddress) } == foreign.baseAddress) + } + + @Test("is kept by IMAPInputBuffer through the generic append, and through an IMAPBuffer") + func inputBufferRetainsThroughGenericAppend() { + let foreign = ForeignBuffer(storage: ForeignStorage(repeating: UInt8(ascii: "f"), count: Self.byteCount)) + var input = IMAPInputBuffer() + appendGenerically(foreign, to: &input) + appendGenerically(IMAPBuffer(IMAPByteStorage(foreign)), to: &input) + input.append(IMAPBuffer(IMAPByteStorage(foreign))) + #expect(input.regionCount == 3) + for region in input.byteRegions { + #expect(address(of: region) == foreign.baseAddress) + } + } + + @Test("is kept by IMAPInputBuffer through an IMAPBuffer, where an unstable region is copied") + func inputBufferAppendsIMAPBuffer() { + let foreign = ForeignBuffer(storage: ForeignStorage(repeating: UInt8(ascii: "f"), count: Self.byteCount)) + let unstable = UnstableBuffer(bytes: Array(repeating: UInt8(ascii: "u"), count: Self.byteCount)) + var input = IMAPInputBuffer() + input.append(IMAPBuffer(IMAPByteStorage(foreign))) + input.append(IMAPBuffer(IMAPByteStorage(unstable))) + + #expect(input.regionCount == 2) + #expect(address(of: input.byteRegions[0]) == foreign.baseAddress, "kept") + let copy = input.byteRegions[1] + #expect(address(of: copy) != unstable.bytes.withUnsafeBytes { UnsafeRawPointer($0.baseAddress) }, "copied") + #expect(donatedAddress(of: copy) == address(of: copy), "the copy has a fixed address") + #expect(copy.copiedBytes() == unstable.bytes) + } + + @Test("carries its fixed address through an IMAPBuffer into IMAPByteStorage") + func stableThroughWrappedBuffer() { + let foreign = ForeignBuffer(storage: ForeignStorage(repeating: UInt8(ascii: "f"), count: Self.byteCount)) + let buffer = IMAPBuffer(IMAPByteStorage(foreign)) + #expect(donatedAddress(of: IMAPBuffer(IMAPByteStorage(buffer))) == foreign.baseAddress, "static") + #expect(donatedAddress(of: wrapGenerically(buffer)) == foreign.baseAddress, "run time") + + let unstable = IMAPBuffer(IMAPByteStorage(UnstableBuffer(bytes: Array(repeating: 0, count: Self.byteCount)))) + #expect(donatedAddress(of: IMAPBuffer(IMAPByteStorage(unstable))) == nil, "static") + #expect(donatedAddress(of: wrapGenerically(unstable)) == nil, "run time") + } + @Test("backingRegion recovers the region and range, without copying") func backingRegionRoundTrips() throws { let foreign = ForeignBuffer(storage: ForeignStorage(repeating: UInt8(ascii: "f"), count: Self.byteCount)) diff --git a/Tests/NIOIMAPCoreTests/Parser/ParseInputCombinatorTests.swift b/Tests/NIOIMAPCoreTests/Parser/ParseInputCombinatorTests.swift new file mode 100644 index 00000000..c4c212aa --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Parser/ParseInputCombinatorTests.swift @@ -0,0 +1,389 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@testable import NIOIMAPCore + +import Testing + +/// The grammar's building blocks, as methods on the cursor. +/// +/// These were tests of `ParserLibrary`'s free functions. The cursor is non-escapable, so a test cannot +/// build one and read from it across statements — every case runs inside a closure instead. +@Suite("ParseInput combinators") +struct ParseInputCombinatorTests {} + +// MARK: - parseOptional + +extension ParseInputCombinatorTests { + @Test("parseOptional throws incomplete message when buffer is empty") + func parseOptionalThrowsIncompleteMessageWhenBufferIsEmpty() { + TestUtilities.withParseInput(for: "") { buffer in + let error = errorThrown { + try buffer.parseOptional(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + } + } + #expect(error is IncompleteMessage) + } + } + + @Test("parseOptional succeeds when element is present") + func parseOptionalSucceedsWhenElementIsPresent() throws { + try TestUtilities.withParseInput(for: "x") { buffer in + try buffer.parseOptional(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + } + } + } + + @Test("parseOptional succeeds when element is not present") + func parseOptionalSucceedsWhenElementIsNotPresent() throws { + try TestUtilities.withParseInput(for: "y") { buffer in + try buffer.parseOptional(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + } + #expect(buffer.remaining == 1) + } + } + + @Test("parseOptional resets buffer correctly for composite parsers with incomplete input") + func parseOptionalResetsBufferCorrectlyForCompositeParsersWithIncompleteInput() { + TestUtilities.withParseInput(for: "x") { buffer in + let error = errorThrown { + try buffer.parseOptional(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + try buffer.matchFixed("y") + } + } + #expect(error is IncompleteMessage) + #expect(buffer.remaining == 1) + } + } + + @Test("parseOptional resets buffer correctly for composite parsers with non-matching input") + func parseOptionalResetsBufferCorrectlyForCompositeParsersWithNonMatchingInput() throws { + try TestUtilities.withParseInput(for: "xz") { buffer in + try buffer.parseOptional(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + try buffer.matchFixed("y") + } + #expect(buffer.remaining == 2) + } + } +} + +// MARK: - matchFixed + +extension ParseInputCombinatorTests { + @Test("matchFixed with case sensitive matching") + func matchFixedWithCaseSensitiveMatching() throws { + try TestUtilities.withParseInput(for: "fooFooFOO") { buffer in + try buffer.matchFixed("fooFooFOO", caseSensitivity: .caseSensitive) + } + + TestUtilities.withParseInput(for: "fooFooFOO") { buffer in + #expect(errorThrown { try buffer.matchFixed("foofoofoo", caseSensitivity: .caseSensitive) } is ParserError) + } + + TestUtilities.withParseInput(for: "foo") { buffer in + #expect( + errorThrown { try buffer.matchFixed("fooFooFOO", caseSensitivity: .caseSensitive) } is IncompleteMessage + ) + } + } + + @Test("matchFixed with case insensitive matching") + func matchFixedWithCaseInsensitiveMatching() throws { + try TestUtilities.withParseInput(for: "fooFooFOO") { buffer in + try buffer.matchFixed("fooFooFOO") + } + + try TestUtilities.withParseInput(for: "fooFooFOO") { buffer in + try buffer.matchFixed("foofoofoo") + } + + TestUtilities.withParseInput(for: "foo") { buffer in + #expect(errorThrown { try buffer.matchFixed("fooFooFOO") } is IncompleteMessage) + } + } + + @Test("matchFixed rejects non-ASCII characters") + func matchFixedRejectsNonAsciiCharacters() { + TestUtilities.withParseInput(for: "fooFooFOÖ") { buffer in + #expect(errorThrown { try buffer.matchFixed("fooFooFOO", caseSensitivity: .caseSensitive) } is ParserError) + } + } + + @Test("matchFixed with leading spaces") + func matchFixedWithLeadingSpaces() throws { + try TestUtilities.withParseInput(for: String(repeating: " ", count: 500) + "fooFooFOO") { buffer in + try buffer.matchFixed("fooFooFOO", caseSensitivity: .caseSensitive, leadingSpaces: .allowed) + } + } + + @Test("matchFixed with leading spaces consumes nothing when the needle does not follow") + func matchFixedWithLeadingSpacesConsumesNothingOnMismatch() { + TestUtilities.withParseInput(for: " bar") { buffer in + #expect(errorThrown { try buffer.matchFixed("foo", leadingSpaces: .allowed) } is ParserError) + #expect(buffer.remaining == 6) + } + } +} + +// MARK: - parseZeroOrMore + +extension ParseInputCombinatorTests { + @Test("parseZeroOrMore parses nothing when no match but data present") + func parseZeroOrMoreParsesNothingWhenNoMatchButDataPresent() throws { + TestUtilities.withParseInput("", terminator: "xy") { buffer in + let result = try buffer.parseZeroOrMore(tracker: .testTracker) { buffer, _ -> Int in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + return 1 + } + #expect(result == []) + } + } + + @Test("parseZeroOrMore throws incomplete message when no data") + func parseZeroOrMoreThrowsIncompleteMessageWhenNoData() throws { + TestUtilities.withParseInput("") { buffer in + let error = errorThrown { + try buffer.parseZeroOrMore(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + } + } + #expect(error is IncompleteMessage) + } + } + + @Test("parseZeroOrMore parses one item when more data present") + func parseZeroOrMoreParsesOneItemWhenMoreDataPresent() throws { + TestUtilities.withParseInput("xx", terminator: "xy") { buffer in + let result = try buffer.parseZeroOrMore(tracker: .testTracker) { buffer, _ -> Int in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + return 1 + } + #expect(result == [1]) + } + } + + @Test("parseZeroOrMore parses two items when more data present") + func parseZeroOrMoreParsesTwoItemsWhenMoreDataPresent() throws { + TestUtilities.withParseInput("xxxx", terminator: "xy") { buffer in + let result = try buffer.parseZeroOrMore(tracker: .testTracker) { buffer, _ -> Int in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + return 1 + } + #expect(result == [1, 1]) + } + } +} + +// MARK: - parseOneOrMore + +extension ParseInputCombinatorTests { + @Test("parseOneOrMore throws parser error when no match but data present") + func parseOneOrMoreThrowsParserErrorWhenNoMatchButDataPresent() throws { + TestUtilities.withParseInput("", terminator: "xy") { buffer in + let error = errorThrown { + try buffer.parseOneOrMore(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + } + } + #expect(error is ParserError) + } + } + + @Test("parseOneOrMore throws incomplete message when no data") + func parseOneOrMoreThrowsIncompleteMessageWhenNoData() throws { + TestUtilities.withParseInput("") { buffer in + let error = errorThrown { + try buffer.parseOneOrMore(tracker: .testTracker) { buffer, _ in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + } + } + #expect(error is IncompleteMessage) + } + } + + @Test("parseOneOrMore parses one item when more data present") + func parseOneOrMoreParsesOneItemWhenMoreDataPresent() throws { + TestUtilities.withParseInput("xx", terminator: "xy") { buffer in + let result = try buffer.parseOneOrMore(tracker: .testTracker) { buffer, _ -> Int in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + return 1 + } + #expect(result == [1]) + } + } + + @Test("parseOneOrMore parses two items when more data present") + func parseOneOrMoreParsesTwoItemsWhenMoreDataPresent() throws { + TestUtilities.withParseInput("xxxx", terminator: "xy") { buffer in + let result = try buffer.parseOneOrMore(tracker: .testTracker) { buffer, _ -> Int in + try buffer.matchFixed("x") + try buffer.matchFixed("x") + return 1 + } + #expect(result == [1, 1]) + } + } +} + +// MARK: - parseSpaces + +extension ParseInputCombinatorTests { + @Test( + "parseSpaces consumes leading spaces", + arguments: [ + (" a", "a"), + (" a", "a"), + (" a ", "a "), + ] + ) + func parseSpacesConsumesLeadingSpaces(input: String, expectedRemaining: String) throws { + try TestUtilities.withParseInput(for: input) { buffer in + try buffer.parseSpaces() + let rest = try buffer.extractBytes(length: buffer.remaining) + #expect(String(decoding: rest, as: UTF8.self) == expectedRemaining) + } + } + + @Test("parseSpaces consumes an input that is nothing but spaces") + func parseSpacesConsumesAnInputOfOnlySpaces() throws { + try TestUtilities.withParseInput(for: " ") { buffer in + try buffer.parseSpaces() + #expect(buffer.remaining == 0) + } + } + + @Test("parseSpaces consumes nothing when the first byte is not a space") + func parseSpacesConsumesNothingWhenTheFirstByteIsNotASpace() { + TestUtilities.withParseInput(for: "a ") { buffer in + #expect(errorThrown { try buffer.parseSpaces() } is ParserError) + #expect(buffer.remaining == 2) + } + } +} + +// MARK: - parseUnsignedInt64 + +extension ParseInputCombinatorTests { + @Test( + "parseUnsignedInt64 parses numbers correctly", + arguments: [ + ("12345\r", 12345, 5), + ("18446744073709551615\r", UInt64.max, 20), + ("12345 a", 12345, 5), + ("18446744073709551615b", UInt64.max, 20), + ] + ) + func parseUnsignedInt64ParsesNumbersCorrectly( + input: String, + expectedResult: UInt64, + expectedConsumed: Int + ) throws { + try TestUtilities.withParseInput(for: input) { buffer in + let (id, actualConsumed) = try buffer.parseUnsignedInt64(tracker: .makeNewDefault) + #expect(actualConsumed == expectedConsumed) + #expect(id == expectedResult) + } + } + + @Test("parseUnsignedInt64 rejects a number that does not fit") + func parseUnsignedInt64RejectsANumberThatDoesNotFit() { + TestUtilities.withParseInput(for: "18446744073709551616\r") { buffer in + #expect(errorThrown { try buffer.parseUnsignedInt64(tracker: .makeNewDefault) } is ParserError) + } + } +} + +// MARK: - decodeUTF8 + +extension ParseInputCombinatorTests { + @Test("decodeUTF8 with ASCII string") + func decodeUtf8WithAsciiString() throws { + let test1 = Array("hello, world".utf8) + #expect(try decodeUTF8(test1) == "hello, world") + } + + @Test("decodeUTF8 with multi-byte UTF-8 characters") + func decodeUtf8WithMultiByteUtf8Characters() throws { + let test2: [UInt8] = [0xE2, 0x9A, 0xA1, 0xE2, 0x9A, 0xA2, 0xE2, 0x9A, 0xA3, 0xE2, 0x9A, 0xA4] + #expect(try decodeUTF8(test2) == "⚡⚢⚣⚤") + } + + @Test("decodeUTF8 with incomplete UTF-8 sequence") + func decodeUtf8WithIncompleteUtf8Sequence() throws { + let test3: [UInt8] = [0xC2] + #expect(throws: (any Error).self) { + try decodeUTF8(test3) + } + } + + @Test("decodeUTF8 with truncated multi-byte sequence") + func decodeUtf8WithTruncatedMultiByteSequence() throws { + let test4: [UInt8] = [0xE1, 0x80] + #expect(throws: (any Error).self) { + try decodeUTF8(test4) + } + } +} + +// MARK: - matchNewline + +extension ParseInputCombinatorTests { + @Test( + "matchNewline handles various newline formats", + arguments: [ + "\r\n", + "\n", + "\r", + " \r\n", + " \n", + " \r", + " \r\n", + " \n", + " \r", + ] + ) + func matchNewlineHandlesVariousNewlineFormats(newline: String) throws { + try TestUtilities.withParseInput(for: newline + "hello, world") { buffer in + try buffer.matchNewline() + try buffer.matchFixed("hello, world") + } + } + + /// A long run of stray spaces used to cost one `composite` frame each, so more than a hundred of them + /// threw `TooMuchRecursion`. The cursor measures the whole match ahead of the read position and + /// advances once, so this now succeeds up to ``ParseInput/maximumStraySpaces``, and the stack no longer + /// grows at all. + @Test( + "matchNewline skips a long run of stray spaces without recursing", + arguments: [80, 200, ParseInput.maximumStraySpaces] + ) + func matchNewlineSkipsALongRunOfStraySpaces(spaces: Int) throws { + try TestUtilities.withParseInput(for: String(repeating: " ", count: spaces) + "\r\nhello, world") { buffer in + try buffer.matchNewline() + try buffer.matchFixed("hello, world") + } + } +} diff --git a/Tests/NIOIMAPCoreTests/Parser/ParseInputHarness.swift b/Tests/NIOIMAPCoreTests/Parser/ParseInputHarness.swift new file mode 100644 index 00000000..1a770610 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Parser/ParseInputHarness.swift @@ -0,0 +1,170 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@testable import NIOIMAPCore + +/// One region to hand to a ``ParseInput``, described the way a real staging type would produce it: a run +/// of owned bytes, plus the slice of them that is actually visible. +/// +/// The two are separate on purpose. An owner box spans a whole network read while a region may be the +/// *tail* of that read after a partial consume, so `visible.lowerBound` is the region's offset inside its +/// owner — the number that a zero-copy extraction gets wrong if it is ignored. +struct TestRegion { + /// Everything the owner keeps alive. + var owned: [UInt8] + /// The part of `owned` the cursor gets to see. + var visible: Range + /// Whether the region carries an owner, which is what lets an extraction retain rather than copy. + var vouching: Vouching + + enum Vouching { + /// Carries an owner: an extraction may retain the bytes. + case vouched + /// No owner: an extraction has to copy. + case unvouched + } + + init(owned: [UInt8], visible: Range? = nil, vouching: Vouching = .vouched) { + self.owned = owned + self.visible = visible ?? 0.. + var vouching: TestRegion.Vouching + } + + private var entries: [Entry] + + private(set) var count: Int + + init(_ regions: [TestRegion]) { + self.entries = regions.map { + Entry(storage: IMAPByteStorage($0.owned), visible: $0.visible, vouching: $0.vouching) + } + self.count = self.entries.reduce(0) { $0 + $1.visible.count } + } + + var byteRegions: [IMAPBuffer] { + entries.map { IMAPBuffer($0.storage, $0.visible) } + } + + var regionCount: Int { entries.count } + + borrowing func withStableRegions(into sink: inout RegionSink) { + for entry in entries { + let bytes = entry.storage.withUnsafeBytes { $0 } + let visible = UnsafeRawBufferPointer(rebasing: bytes[entry.visible]) + sink.append( + visible.bindMemory(to: UInt8.self), + owner: entry.vouching == .vouched ? entry.storage : nil, + offset: entry.visible.lowerBound + ) + } + } + + func withParseInput(limit: Int, _ body: (inout ParseInput) throws -> R) rethrows -> R { + try _stableWithParseInput(limit: limit, body) + } + + /// Moves the read head, slicing the first region rather than dropping its consumed prefix — the + /// shape that gets the offset arithmetic wrong if either term is missing. + mutating func discardFirst(_ k: Int) { + var remaining = k + while remaining > 0, let first = entries.first { + if remaining < first.visible.count { + entries[0].visible = (first.visible.lowerBound + remaining)..( + _ regions: [TestRegion], + limit: Int = .max, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + let buffer = TestInputBuffer(regions) + // `limit:` explicitly, so this binds the conformer's own witness — the one-pass gather. + return try buffer.withParseInput(limit: limit, body) + } + + /// Runs `body` with a single-region cursor built the way a caller with contiguous bytes would build + /// one: no table, and therefore no owner, so every extraction copies. + static func withSpan( + _ bytes: [UInt8], + limit: Int = .max, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + try bytes.withUnsafeBufferPointer { buffer in + var input = ParseInput(_span(buffer), limit: limit) + return try body(&input) + } + } + + static func withSpan( + _ text: String, + limit: Int = .max, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + try withSpan(Array(text.utf8), limit: limit, body) + } +} + +/// Runs `body` and returns the error it threw, or `nil` if it returned. +/// +/// `#expect(throws:)` cannot be used around a cursor: its closure would have to capture an `inout` value +/// of a non-escapable type. +func errorThrown(by body: () throws -> T) -> Error? { + do { + _ = try body() + return nil + } catch { + return error + } +} diff --git a/Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift b/Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift new file mode 100644 index 00000000..1f79d530 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Parser/ParseInputTests.swift @@ -0,0 +1,636 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@testable import NIOIMAPCore + +import Testing + +/// Boundary coverage for the parse cursor. +/// +/// Nearly every case here is about a *region boundary*, because that is where this type differs from the +/// single-buffer cursor it replaces, and because the failure mode is silent: a cursor parked on an +/// exhausted region reports end-of-input while bytes are still waiting, so a multi-region extraction +/// stops early and returns the wrong — but perfectly well-formed — answer. +@Suite("ParseInput") +struct ParseInputTests {} + +// MARK: - Layout + +extension ParseInputTests { + @Test("The cursor stays a small trivial value") + func layout() { + // Backtracking copies this value constantly, so its size and its triviality are the whole reason + // `composite` is cheap. `lastParsedNewline` shares a word with the region index to keep it here. + #expect(MemoryLayout.size == 56) + #expect(MemoryLayout.stride == 56) + #expect(MemoryLayout.size == 32) + } +} + +// MARK: - Walking + +extension ParseInputTests { + @Test("A single contiguous region reads back") + func singleRegion() { + ParseInputHarness.withSpan("A003 LOGOUT") { input in + #expect(input.remaining == 11) + #expect(input.isEmpty == false) + #expect(input.peek(at: 0) == UInt8(ascii: "A")) + #expect(input.peek(at: 10) == UInt8(ascii: "T")) + #expect(input.peek(at: 11) == nil) + input.advance(by: 5) + #expect(input.consumed == 5) + #expect(input.peek(at: 0) == UInt8(ascii: "L")) + #expect(input.remaining == 6) + } + } + + @Test("Peeking crosses region boundaries") + func peekAcrossRegions() { + ParseInputHarness.withInput([TestRegion("A00"), TestRegion("3 LOG"), TestRegion("OUT")]) { input in + #expect(input.remaining == 11) + #expect(input.peek(at: 2) == UInt8(ascii: "0")) + #expect(input.peek(at: 3) == UInt8(ascii: "3")) + #expect(input.peek(at: 8) == UInt8(ascii: "O")) + #expect(input.peek(at: 10) == UInt8(ascii: "T")) + #expect(input.peek(at: 11) == nil) + #expect(input.consumed == 0) + } + } + + @Test("Landing exactly on a region boundary refills the head") + func advanceOntoBoundary() { + // The bug this pins: guarding the refill with `if headIsEmpty && more > 0` leaves the cursor + // parked on an exhausted region, and every primitive then reports end-of-input. + ParseInputHarness.withInput([TestRegion("abc"), TestRegion("def")]) { input in + input.advance(by: 3) + #expect(input.isEmpty == false) + #expect(input.peek(at: 0) == UInt8(ascii: "d")) + #expect(input.remaining == 3) + #expect(input.consumed == 3) + } + } + + @Test("Leading empty regions are skipped when the cursor is built") + func leadingEmptyRegions() { + ParseInputHarness.withInput([TestRegion(""), TestRegion(""), TestRegion("ab")]) { input in + #expect(input.isEmpty == false) + #expect(input.peek(at: 0) == UInt8(ascii: "a")) + #expect(input.remaining == 2) + } + } + + @Test("Interior empty regions are skipped while advancing") + func interiorEmptyRegions() { + let regions = [TestRegion("ab"), TestRegion(""), TestRegion(""), TestRegion("cd")] + ParseInputHarness.withInput(regions) { input in + #expect(input.peek(at: 2) == UInt8(ascii: "c")) + input.advance(by: 2) + #expect(input.peek(at: 0) == UInt8(ascii: "c")) + input.advance(by: 2) + #expect(input.isEmpty == true) + #expect(input.consumed == 4) + } + } + + @Test("A trailing empty region still reads as exhausted") + func trailingEmptyRegion() { + ParseInputHarness.withInput([TestRegion("ab"), TestRegion("")]) { input in + input.advance(by: 2) + #expect(input.isEmpty == true) + #expect(input.peek(at: 0) == nil) + #expect(input.remaining == 0) + } + } + + @Test("Advancing past the end clamps, and advancing again is a no-op") + func advancePastTheEnd() { + ParseInputHarness.withInput([TestRegion("ab"), TestRegion("cd")]) { input in + input.advance(by: 999) + #expect(input.consumed == 4) + #expect(input.isEmpty == true) + input.advance(by: 999) + #expect(input.consumed == 4) + } + } + + @Test("Advancing by zero leaves the invariant true") + func advanceByZero() { + ParseInputHarness.withInput([TestRegion(""), TestRegion("ab")]) { input in + input.advance(by: 0) + #expect(input.consumed == 0) + #expect(input.peek(at: 0) == UInt8(ascii: "a")) + } + } + + @Test("Empty and all-empty inputs terminate") + func emptyInputs() { + ParseInputHarness.withInput([]) { input in + #expect(input.isEmpty == true) + #expect(input.remaining == 0) + #expect(input.peek(at: 0) == nil) + input.advance(by: 4) + #expect(input.consumed == 0) + } + ParseInputHarness.withInput([TestRegion(""), TestRegion(""), TestRegion("")]) { input in + #expect(input.isEmpty == true) + input.advance(by: 4) + #expect(input.consumed == 0) + } + } + + @Test("peek2 spans a boundary and reports the end") + func peek2() { + ParseInputHarness.withInput([TestRegion("a"), TestRegion("bc")]) { input in + #expect(input.peek2().map { [$0.0, $0.1] } == [UInt8(ascii: "a"), UInt8(ascii: "b")]) + input.advance(by: 1) + #expect(input.peek2().map { [$0.0, $0.1] } == [UInt8(ascii: "b"), UInt8(ascii: "c")]) + input.advance(by: 1) + #expect(input.peek2() == nil) + } + } + + @Test("withCurrentChunk hands out the current region only") + func currentChunk() { + ParseInputHarness.withInput([TestRegion("abc"), TestRegion("de")]) { input in + #expect(input.withCurrentChunk { $0.count } == 3) + input.advance(by: 3) + #expect(input.withCurrentChunk { $0.count } == 2) + input.advance(by: 2) + #expect(input.withCurrentChunk { $0.isEmpty } == true) + } + } +} + +// MARK: - The limit + +extension ParseInputTests { + @Test("The limit hides bytes from every primitive") + func limitHidesBytes() { + ParseInputHarness.withInput([TestRegion("abcd"), TestRegion("efgh")], limit: 6) { input in + #expect(input.remaining == 6) + #expect(input.peek(at: 5) == UInt8(ascii: "f")) + #expect(input.peek(at: 6) == nil) + #expect(input.withCurrentChunk { $0.count } == 4) + input.advance(by: 4) + #expect(input.withCurrentChunk { $0.count } == 2) + input.advance(by: 999) + #expect(input.consumed == 6) + #expect(input.isEmpty == true) + } + } + + @Test("A limit falling mid-region truncates the head") + func limitMidRegion() { + ParseInputHarness.withSpan("abcdef", limit: 3) { input in + #expect(input.remaining == 3) + #expect(input.withCurrentChunk { $0.count } == 3) + #expect(input.scanUntil(byte: UInt8(ascii: "e")) == nil) + #expect(errorThrown(by: { try input.extractBytes(length: 4) }) is IncompleteMessage) + #expect(try! input.extractBytes(length: 3) == Array("abc".utf8)) + #expect(errorThrown(by: { try input.extractBuffer(upTo: 1) }) is IncompleteMessage) + } + } +} + +// MARK: - Scans + +extension ParseInputTests { + @Test("scanUntil finds a byte in the current region") + func scanUntilInHead() { + ParseInputHarness.withSpan("abc def") { input in + #expect(input.scanUntil(byte: UInt8(ascii: " ")) == 3) + #expect(input.consumed == 0) + } + } + + @Test("scanUntil crosses regions") + func scanUntilAcrossRegions() { + ParseInputHarness.withInput([TestRegion("abc"), TestRegion(""), TestRegion("de f")]) { input in + #expect(input.scanUntil(byte: UInt8(ascii: " ")) == 5) + #expect(input.scanUntil(byte: UInt8(ascii: "f")) == 6) + #expect(input.scanUntil(byte: UInt8(ascii: "z")) == nil) + #expect(input.consumed == 0) + } + } + + @Test("scanWhile stops at the first byte that fails, in whichever region it is") + func scanWhileAcrossRegions() { + let isDigit: (UInt8) -> Bool = { $0 >= UInt8(ascii: "0") && $0 <= UInt8(ascii: "9") } + ParseInputHarness.withInput([TestRegion("12"), TestRegion("34"), TestRegion(" x")]) { input in + #expect(input.scanWhile(isDigit) == 4) + #expect(input.consumed == 0) + } + ParseInputHarness.withSpan("x123") { input in + #expect(input.scanWhile(isDigit) == 0) + } + } + + @Test("scanWhile reports nil when every visible byte matches") + func scanWhileRunsOut() { + let isDigit: (UInt8) -> Bool = { $0 >= UInt8(ascii: "0") && $0 <= UInt8(ascii: "9") } + // nil means "this run might continue in bytes that have not arrived", which is what both + // character-class parsers turn into `IncompleteMessage`. + ParseInputHarness.withInput([TestRegion("12"), TestRegion("34")]) { input in + #expect(input.scanWhile(isDigit) == nil) + } + // The same answer when the limit is what cut the run short, not the end of the input. + ParseInputHarness.withSpan("12 x", limit: 2) { input in + #expect(input.scanWhile(isDigit) == nil) + } + ParseInputHarness.withInput([]) { input in + #expect(input.scanWhile(isDigit) == nil) + } + } +} + +// MARK: - Extracting bytes + +extension ParseInputTests { + @Test("extractBytes copies across three regions") + func extractBytesAcrossRegions() throws { + let bytes = try ParseInputHarness.withInput([TestRegion("A0"), TestRegion("03 LO"), TestRegion("GOUT")]) { + input in + let bytes = try input.extractBytes(length: 11) + #expect(input.consumed == 11) + #expect(input.isEmpty == true) + return bytes + } + #expect(bytes == Array("A003 LOGOUT".utf8)) + } + + @Test("extractBytes asking for more than is there consumes nothing") + func extractBytesTooLong() { + ParseInputHarness.withInput([TestRegion("ab"), TestRegion("cd")]) { input in + #expect(errorThrown(by: { try input.extractBytes(length: 5) }) is IncompleteMessage) + #expect(input.consumed == 0) + #expect(try! input.extractBytes(length: 4) == Array("abcd".utf8)) + } + } + + @Test("extractBytes of nothing is nothing") + func extractNoBytes() { + ParseInputHarness.withInput([]) { input in + #expect(try! input.extractBytes(length: 0) == []) + } + } + + @Test("readByte consumes one byte, and reports the end") + func readByte() { + ParseInputHarness.withInput([TestRegion("a"), TestRegion("b")]) { input in + #expect(try! input.readByte() == UInt8(ascii: "a")) + #expect(try! input.readByte() == UInt8(ascii: "b")) + #expect(errorThrown(by: { try input.readByte() }) is IncompleteMessage) + } + } +} + +// MARK: - Extracting payloads + +extension ParseInputTests { + /// A payload big enough to be worth referring to rather than copying. + private static let payload = Array(repeating: UInt8(ascii: "p"), count: 2048) + + @Test("A large payload is handed out as a reference to the input") + func extractBufferRetains() throws { + let (isSameMemory, bytes) = try ParseInputHarness.withInput([TestRegion(owned: Self.payload)]) { input in + let head = input.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress!) } + } + let buffer = try input.extractBuffer(upTo: 2048) + let extracted = buffer.withUnsafeBytes { $0.baseAddress! } + #expect(input.consumed == 2048) + return (head == extracted, buffer.copiedBytes()) + } + #expect(isSameMemory, "a payload at or above the copy threshold must not be copied") + #expect(bytes == Self.payload) + } + + @Test("A small payload is copied") + func extractBufferCopiesBelowThreshold() throws { + let small = Array("small".utf8) + let isSameMemory = try ParseInputHarness.withInput([TestRegion(owned: small)]) { input in + let head = input.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress!) } + } + let buffer = try input.extractBuffer(upTo: small.count) + #expect(buffer.copiedBytes() == small) + return head == buffer.withUnsafeBytes { $0.baseAddress! } + } + #expect(isSameMemory == false, "below the threshold, pinning the whole region is not worth it") + } + + @Test("A payload with no owner is copied, however large") + func extractBufferCopiesWithoutAnOwner() throws { + // Two ways to have no owner: a region the gather could not vouch for, and the single-span entry + // point, which has no table at all. + for vouching in [TestRegion.Vouching.unvouched] { + let isSameMemory = try ParseInputHarness.withInput([ + TestRegion(owned: Self.payload, vouching: vouching) + ]) { input in + let head = input.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress!) } + } + let buffer = try input.extractBuffer(upTo: 2048) + return head == buffer.withUnsafeBytes { $0.baseAddress! } + } + #expect(isSameMemory == false) + } + let isSameMemory = try ParseInputHarness.withSpan(Self.payload) { input in + let head = input.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress!) } + } + let buffer = try input.extractBuffer(upTo: 2048) + #expect(buffer.copiedBytes() == Self.payload) + return head == buffer.withUnsafeBytes { $0.baseAddress! } + } + #expect(isSameMemory == false) + } + + @Test("A payload extracted from a partially consumed, head-sliced region is the right payload") + func extractBufferAfterPartialConsume() throws { + // The case that catches an offset bug, and the only case that does: the owner box spans a whole + // network read, the region is the tail of it after an earlier parse, and this parse has already + // consumed some of that tail. Both offsets have to be added, and a test where either one is zero + // passes with the wrong arithmetic. + let prefix = "A003 LOGOUT\r\n" + let payload = Array(repeating: UInt8(ascii: "z"), count: 2048) + let owned = Array(prefix.utf8) + payload + let region = TestRegion(owned: owned, visible: prefix.utf8.count.. Bool { + let head = input.withCurrentChunk { chunk in + chunk.withUnsafeBufferPointer { UnsafeRawPointer($0.baseAddress!) } + } + let buffer = try input.extractBuffer(upTo: count) + guard buffer.retainedRegion != nil else { return false } + return buffer.withUnsafeBytes { $0.baseAddress! } == head +} + +/// The call form that binds a witness from a generic context, with no limit — the one that a default +/// argument in the wrong place silently sends down the generic path. +private func extractThroughGenericContext(_ buffer: Buffer) throws -> Bool { + try buffer.withParseInput { try extractsWithoutCopying(&$0) } +} + +private func extractThroughGenericParse(_ buffer: inout Buffer) throws -> Bool { + try buffer.parse { try extractsWithoutCopying(&$0) } +} + +private func makeInputBuffer(_ regions: [[UInt8]]) -> IMAPInputBuffer { + var buffer = IMAPInputBuffer() + for region in regions { buffer.append(region) } + return buffer +} + +private func makeDispatchData(_ pieces: [[UInt8]]) -> DispatchData { + var data = DispatchData.empty + for piece in pieces { + piece.withUnsafeBufferPointer { data.append($0) } + } + return data +} + +/// A conformer with no fast path at all: several regions, no owners, so it takes the recursive gather. +private struct ManyRegions: ParserInputBuffer { + var byteRegions: [[UInt8]] + var count: Int { byteRegions.reduce(0) { $0 + $1.count } } +} + +/// A conformer whose `regionCount` is wrong on the low side, which is the one way a conformer can push +/// the gather past the end of the table it sized. +private struct UnderReportingRegionCount: ParserInputBuffer { + var byteRegions: [[UInt8]] + var count: Int { byteRegions.reduce(0) { $0 + $1.count } } + var regionCount: Int { 1 } +} + +// MARK: - Which gather ran + +extension ParserInputBufferTests { + @Test("A payload stays uncopied through every call form") + func onePassGatherThroughEveryCallForm() throws { + // A one-pass conformer has to win witness resolution from all of these. It did not, at one point, + // from the two that leave the limit out — which is most calls — and nothing failed as a result: + // the payload was simply copied every time. + var buffer = makeInputBuffer([payload]) + #expect(try buffer.withParseInput(limit: .max) { try extractsWithoutCopying(&$0) }) + #expect(try buffer.withParseInput { try extractsWithoutCopying(&$0) }) + #expect(try extractThroughGenericContext(buffer)) + + buffer = makeInputBuffer([payload]) + #expect(try buffer.parse(limit: .max) { try extractsWithoutCopying(&$0) }) + #expect(buffer.isEmpty == true) + + buffer = makeInputBuffer([payload]) + #expect(try buffer.parse { try extractsWithoutCopying(&$0) }) + + buffer = makeInputBuffer([payload]) + #expect(try extractThroughGenericParse(&buffer)) + } + + @Test("A conformer that cannot vouch for its bytes gets a copy") + func genericGatherCopies() throws { + // Not a defect: nobody is keeping these bytes alive past the call, so a payload that outlives it + // has to be copied. This is the honest answer for `Data`, `Array` and third-party conformers. + #expect(try payload.withParseInput { try extractsWithoutCopying(&$0) } == false) + #expect(try Data(payload).withParseInput { try extractsWithoutCopying(&$0) } == false) + #expect(try makeDispatchData([payload]).withParseInput { try extractsWithoutCopying(&$0) } == false) + } + + @Test("A payload extracted after an earlier parse is the right payload") + func extractionAfterPartialConsume() throws { + // The bytes handed out come from an owner that spans the whole appended run, while the region is + // the tail of that run — so the range has to account for what earlier parses consumed as well as + // for what this one has. Getting it wrong returns well-formed bytes from the wrong place. + var buffer = makeInputBuffer([Array("A003 LOGOUT\r\n".utf8) + payload]) + buffer.parse { $0.advance(by: 13) } + #expect(buffer.count == payload.count) + + let extracted = try buffer.parse { try $0.extractBuffer(upTo: 4096) } + #expect(extracted.retainedRegion != nil, "the payload should still be a reference to the input") + #expect(extracted.copiedBytes() == payload) + #expect(buffer.isEmpty == true) + } +} + +// MARK: - Trimming + +extension ParserInputBufferTests { + @Test("Parsing discards exactly what the parser consumed") + func parseTrims() throws { + var buffer = makeInputBuffer([Array("A001 NOOP\r\nA002 NOOP\r\n".utf8)]) + let first = try buffer.parse { try $0.extractBytes(length: 11) } + #expect(String(decoding: first, as: UTF8.self) == "A001 NOOP\r\n") + #expect(buffer.count == 11) + let second = try buffer.parse { try $0.extractBytes(length: 11) } + #expect(String(decoding: second, as: UTF8.self) == "A002 NOOP\r\n") + #expect(buffer.isEmpty == true) + } + + @Test("A buffer that slices its head region trims by the right amount") + func headSlicingConformerTrims() throws { + // The failure this pins produced `03 LOGOUT` from `A003 LOGOUT`: a buffer whose read head is an + // offset must present its regions from that head, so that what the parser reports having consumed + // means the same thing to both sides. + var buffer = TestInputBuffer([TestRegion("A003 LOGOUT\r\nHELLOWORLD")]) + let tag = try buffer.parse { try $0.extractBytes(length: 4) } + #expect(String(decoding: tag, as: UTF8.self) == "A003") + #expect(buffer.count == 19) + let rest = try buffer.parse { try $0.extractBytes(length: 19) } + #expect(String(decoding: rest, as: UTF8.self) == " LOGOUT\r\nHELLOWORLD") + } + + @Test("What the parser consumed is discarded even when it throws") + func parseTrimsOnThrow() { + // The streaming literal modes make progress and *then* report that they need more bytes, and a + // response parser skips a stray LF outside any backtracking frame. Both would re-parse bytes if + // trimming only happened on the way out of a successful parse. + var buffer = makeInputBuffer([Array("A003 LOGOUT\r\n".utf8)]) + let error = errorThrown { + try buffer.parse { input in + input.advance(by: 4) + throw IncompleteMessage() + } + } + #expect(error is IncompleteMessage) + #expect(buffer.count == 9) + } + + @Test("A parse that consumes nothing discards nothing") + func parseTrimsNothing() throws { + var buffer = makeInputBuffer([Array("A003 LOGOUT\r\n".utf8)]) + let peeked = buffer.parse { $0.peek(at: 0) } + #expect(peeked == UInt8(ascii: "A")) + #expect(buffer.count == 13) + } + + @Test("A limit hides the bytes past it, and they are not trimmed") + func parseWithLimit() throws { + var buffer = makeInputBuffer([Array("A003 LOGOUT\r\n".utf8)]) + let bytes = try buffer.parse(limit: 4) { input in + #expect(input.remaining == 4) + return try input.extractBytes(length: 4) + } + #expect(String(decoding: bytes, as: UTF8.self) == "A003") + #expect(buffer.count == 9) + } +} + +// MARK: - Region counts + +extension ParserInputBufferTests { + @Test("A DispatchData parses across its regions", arguments: [1, 2, 25, 5000]) + func dispatchDataRegions(pieceCount: Int) throws { + let pieces = (0.. ManyRegions.maximumGatherDepth) + let parsed = try buffer.withParseInput { input in + let head = try input.extractBytes(length: 3000) + let tail = try input.extractBytes(length: 2000) + #expect(input.isEmpty == true) + return head + tail + } + #expect(parsed == bytes, "the coalesced tail has to keep its order and its place") + } + + @Test("A conformer that under-reports its region count still parses") + func underReportedRegionCount() throws { + // The table is sized from `regionCount`, so this is the one conformance mistake that could write + // past it. The gather coalesces when the table is full for the same reason it coalesces at the + // depth cap, so the mistake costs a copy rather than memory corruption. + let buffer = UnderReportingRegionCount(byteRegions: [[1, 2], [3, 4], [5], [6, 7]]) + let parsed = try buffer.withParseInput { try $0.extractBytes(length: 7) } + #expect(parsed == [1, 2, 3, 4, 5, 6, 7]) + } + + @Test("An empty buffer hands over an exhausted cursor") + func emptyInput() throws { + var buffer = IMAPInputBuffer() + buffer.parse { input in + #expect(input.isEmpty == true) + #expect(input.remaining == 0) + } + ManyRegions(byteRegions: []).withParseInput { #expect($0.isEmpty == true) } + ManyRegions(byteRegions: [[], []]).withParseInput { #expect($0.isEmpty == true) } + [UInt8]().withParseInput { #expect($0.isEmpty == true) } + } +} + +// MARK: - Stdlib and Foundation conformers + +extension ParserInputBufferTests { + @Test("The stdlib byte containers and Foundation's can all be parsed from") + func shippedConformers() throws { + let text = "A001 NOOP\r\n" + let bytes = Array(text.utf8) + + let fromArray = try bytes.withParseInput { try $0.extractBytes(length: bytes.count) } + let fromSlice = try bytes[0...].withParseInput { try $0.extractBytes(length: bytes.count) } + let fromContiguous = try ContiguousArray(bytes).withParseInput { + try $0.extractBytes(length: bytes.count) + } + let fromData = try Data(bytes).withParseInput { try $0.extractBytes(length: bytes.count) } + let fromDispatch = try makeDispatchData([bytes]).withParseInput { + try $0.extractBytes(length: bytes.count) + } + + #expect(fromArray == bytes) + #expect(fromSlice == bytes) + #expect(fromContiguous == bytes) + #expect(fromData == bytes) + #expect(fromDispatch == bytes) + } + + @Test("A parsed prefix is discarded from a DispatchData without copying the rest") + func dispatchDataDiscardFirst() throws { + var data = makeDispatchData([Array("A001 NOOP\r\n".utf8), Array("A002 NOOP\r\n".utf8)]) + for tag in ["A001", "A002"] { + let line = try data.parse { try $0.extractBytes(length: 11) } + #expect(String(decoding: line, as: UTF8.self) == "\(tag) NOOP\r\n") + } + #expect(data.count == 0) + } + + @Test("Trimming a DispatchData repeatedly does not pile up wrappers") + func dispatchDataTrimmingStaysFlat() throws { + // `subdata(in:)` is the cheap way to consume a prefix, but a chain of subranges that the gather + // then had to walk would make each parse a little more expensive than the last. It does not: the + // region count only ever goes down, whether the trim lands on a boundary or inside a region. + var data = makeDispatchData((0..<20).map { Array(repeating: UInt8($0), count: 10) }) + #expect(data.regionCount == 20) + for step in 1...20 { + _ = try data.parse { try $0.extractBytes(length: 10) } + #expect(data.regionCount == 20 - step) + } + #expect(data.count == 0) + + var uneven = makeDispatchData((0..<4).map { Array(repeating: UInt8($0), count: 10) }) + _ = try uneven.parse { try $0.extractBytes(length: 5) } + #expect(uneven.regionCount == 4, "a trim inside a region leaves that region, shortened") + _ = try uneven.parse { try $0.extractBytes(length: 5) } + #expect(uneven.regionCount == 3) + } +} diff --git a/Tests/NIOIMAPCoreTests/TestUtilities.swift b/Tests/NIOIMAPCoreTests/TestUtilities.swift index 98a38390..446c3b2d 100644 --- a/Tests/NIOIMAPCoreTests/TestUtilities.swift +++ b/Tests/NIOIMAPCoreTests/TestUtilities.swift @@ -90,6 +90,58 @@ extension TestUtilities { } } +// MARK: - Parser input + +extension TestUtilities { + /// Runs `body` with a cursor over `text`. + /// + /// A cursor cannot be stored in a variable — it is non-escapable, which is what stops the parser + /// from keeping input bytes past the call — so every test that used to build one and then read + /// from it takes this closure form instead. + /// + /// The text is held in an array, which cannot vouch for its bytes, so a large extraction copies. + /// + /// - Parameters: + /// - text: The bytes to read. + /// - body: What to read with. + static func withParseInput( + for text: String, + _ body: (inout ParseInput) throws -> R + ) rethrows -> R { + try Array(text.utf8).withParseInput(limit: .max, body) + } + + /// Runs `body` with a cursor over `string + terminator`, then checks what it left unconsumed. + /// + /// The input is padded on both sides — bytes before the first visible byte and after the last — + /// so that a parser which reads outside the region it was given is caught rather than silently + /// right. An `ArraySlice` is how that padding is expressed: the bytes are there, in the same + /// allocation, and the region the parser sees is a slice that excludes them. + static func withParseInput( + _ string: String, + terminator: String = "", + shouldRemainUnchanged: Bool = false, + sourceLocation: SourceLocation = #_sourceLocation, + _ body: (inout ParseInput) throws -> Void + ) { + let padded = Array("hello\(string)\(terminator)hallo".utf8) + let inputBuffer = padded[5..<(padded.count - 5)] + + let expectedRemainder = shouldRemainUnchanged ? string + terminator : terminator + + inputBuffer.withParseInput(limit: .max) { input in + if let error = errorThrown(by: { try body(&input) }) { + Issue.record(error, "Parsing should not throw", sourceLocation: sourceLocation) + } + let remaining = (try? input.extractBytes(length: input.remaining)) ?? [] + #expect( + String(decoding: remaining, as: UTF8.self) == expectedRemainder, + sourceLocation: sourceLocation + ) + } + } +} + extension ByteBuffer: @retroactive ExpressibleByStringLiteral { public init(stringLiteral value: String) { let allocator = ByteBufferAllocator() diff --git a/Tests/NIOIMAPTests/Bytes/IMAPBufferByteBufferTests.swift b/Tests/NIOIMAPTests/Bytes/IMAPBufferByteBufferTests.swift index b8e39d40..899d9f62 100644 --- a/Tests/NIOIMAPTests/Bytes/IMAPBufferByteBufferTests.swift +++ b/Tests/NIOIMAPTests/Bytes/IMAPBufferByteBufferTests.swift @@ -85,6 +85,16 @@ struct IMAPBufferByteBufferTests { #expect(leaf == readableAddress(original)?.advanced(by: 5)) } + @Test("a large ByteBuffer appended to an IMAPInputBuffer is retained, not copied") + func inputBufferRetainsByteBuffer() { + // Well above `IMAPBuffer.copyThreshold` (1 KiB). + let largeReadByteCount = 4 * 1_024 + let read = ByteBuffer(repeating: UInt8(ascii: "r"), count: largeReadByteCount) + var input = IMAPInputBuffer() + input.append(read) + #expect(input.byteRegions[0].withUnsafeBytes { UnsafeRawPointer($0.baseAddress) } == readableAddress(read)) + } + @Test("an owned buffer converts to a ByteBuffer by copying, with the right bytes") func ownedBytesCopyOnConversion() { let owned = IMAPBuffer(Array("hello world".utf8))