Files
swift-nio-imap/Sources/NIOIMAPCore/Bytes/ByteRegion.swift
T
Daniel Eggert ab79acbdc5 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.
2026-11-24 09:47:33 +09:00

93 lines
4.7 KiB
Swift

//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A contiguous run of bytes.
///
/// 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 `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 `Data`.
///
/// ## Immutability
///
/// ``IMAPByteStorage`` keeps a `ByteRegion` alive so that ``IMAPBuffer`` can hand out its bytes
/// without copying them. That only works if the bytes do not move or change underneath it, so a
/// conformer that is used that way carries an extra requirement described on
/// ``IMAPByteStorage``. Conforming on its own does not commit a type to anything beyond yielding
/// its bytes for the duration of the call.
public protocol ByteRegion {
/// Calls the given closure with a pointer to the region's bytes.
///
/// The pointer is valid only for the duration of the call. Do not let it escape.
///
/// - Parameter body: A closure that receives the region's bytes.
/// - Returns: Whatever `body` returns.
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
}
// The stdlib byte containers already have the required accessor.
extension Array: ByteRegion where Element == UInt8 {}
extension ArraySlice: ByteRegion where Element == UInt8 {}
extension ContiguousArray: ByteRegion where Element == UInt8 {}
/// A ``ByteRegion`` whose bytes stay at one address, unchanged, for as long as any copy of it is alive.
///
/// ``ByteRegion`` promises only that its bytes exist for the duration of a
/// ``ByteRegion/withUnsafeBytes(_:)`` call. A region that flattens or decodes on demand satisfies that
/// with a temporary buffer, and a pointer into one of those must not outlive the call.
///
/// 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, 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 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 {
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 {
public var pinnedByteCount: Int { capacity }
}