|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftNIO open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 16 | +extension AsyncSequence where Element == ByteBuffer { |
| 17 | + /// Decode the `AsyncSequence<ByteBuffer>` into a sequence of `Element`s, |
| 18 | + /// using the `Decoder`, where `Decoder.InboundOut` matches `Element`. |
| 19 | + /// |
| 20 | + /// Usage: |
| 21 | + /// ```swift |
| 22 | + /// let myDecoder = MyNIOSingleStepByteToMessageDecoder() |
| 23 | + /// let baseSequence = MyAsyncSequence<ByteBuffer>(...) |
| 24 | + /// let decodedSequence = baseSequence.decode(using: myDecoder) |
| 25 | + /// |
| 26 | + /// for try await element in decodedSequence { |
| 27 | + /// print("Decoded an element!", element) |
| 28 | + /// } |
| 29 | + /// ``` |
| 30 | + /// |
| 31 | + /// - Parameters: |
| 32 | + /// - decoder: The `Decoder` to use to decode the ``ByteBuffer``s. |
| 33 | + /// - maximumBufferSize: The maximum number of bytes to aggregate in-memory. |
| 34 | + /// An error will be thrown if after decoding an element there is more aggregated data than this amount. |
| 35 | + /// - Returns: A ``NIODecodedAsyncSequence`` that decodes the ``ByteBuffer``s into a sequence of `Element`s. |
| 36 | + @inlinable |
| 37 | + public func decode<Decoder: NIOSingleStepByteToMessageDecoder>( |
| 38 | + using decoder: Decoder, |
| 39 | + maximumBufferSize: Int? = nil |
| 40 | + ) -> NIODecodedAsyncSequence<Self, Decoder> { |
| 41 | + NIODecodedAsyncSequence( |
| 42 | + asyncSequence: self, |
| 43 | + decoder: decoder, |
| 44 | + maximumBufferSize: maximumBufferSize |
| 45 | + ) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/// A type that decodes an `AsyncSequence<ByteBuffer>` into a sequence of ``Element``s, |
| 50 | +/// using the `Decoder`, where `Decoder.InboundOut` matches ``Element``. |
| 51 | +/// |
| 52 | +/// Use `AsyncSequence/decode(using:maximumBufferSize:)` to create a ``NIODecodedAsyncSequence``. |
| 53 | +/// |
| 54 | +/// Usage: |
| 55 | +/// ```swift |
| 56 | +/// let myDecoder = MyNIOSingleStepByteToMessageDecoder() |
| 57 | +/// let baseSequence = MyAsyncSequence<ByteBuffer>(...) |
| 58 | +/// let decodedSequence = baseSequence.decode(using: myDecoder) |
| 59 | +/// |
| 60 | +/// for try await element in decodedSequence { |
| 61 | +/// print("Decoded an element!", element) |
| 62 | +/// } |
| 63 | +/// ``` |
| 64 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 65 | +public struct NIODecodedAsyncSequence< |
| 66 | + Base: AsyncSequence, |
| 67 | + Decoder: NIOSingleStepByteToMessageDecoder |
| 68 | +> where Base.Element == ByteBuffer { |
| 69 | + @usableFromInline |
| 70 | + var asyncSequence: Base |
| 71 | + @usableFromInline |
| 72 | + var decoder: Decoder |
| 73 | + @usableFromInline |
| 74 | + var maximumBufferSize: Int? |
| 75 | + |
| 76 | + @inlinable |
| 77 | + init(asyncSequence: Base, decoder: Decoder, maximumBufferSize: Int? = nil) { |
| 78 | + self.asyncSequence = asyncSequence |
| 79 | + self.decoder = decoder |
| 80 | + self.maximumBufferSize = maximumBufferSize |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 85 | +extension NIODecodedAsyncSequence: AsyncSequence { |
| 86 | + public typealias Element = Decoder.InboundOut |
| 87 | + |
| 88 | + /// Create an ``AsyncIterator`` for this ``NIODecodedAsyncSequence``. |
| 89 | + @inlinable |
| 90 | + public func makeAsyncIterator() -> AsyncIterator { |
| 91 | + AsyncIterator(base: self) |
| 92 | + } |
| 93 | + |
| 94 | + /// An ``AsyncIterator`` over a ``NIODecodedAsyncSequence``. |
| 95 | + public struct AsyncIterator: AsyncIteratorProtocol { |
| 96 | + @usableFromInline |
| 97 | + enum State: Sendable { |
| 98 | + case readingFromBuffer |
| 99 | + case readLastChunkFromBuffer |
| 100 | + case finishedDecoding |
| 101 | + } |
| 102 | + |
| 103 | + @usableFromInline |
| 104 | + var baseIterator: Base.AsyncIterator |
| 105 | + @usableFromInline |
| 106 | + var processor: NIOSingleStepByteToMessageProcessor<Decoder> |
| 107 | + @usableFromInline |
| 108 | + var state: State |
| 109 | + |
| 110 | + @inlinable |
| 111 | + init(base: NIODecodedAsyncSequence) { |
| 112 | + self.baseIterator = base.asyncSequence.makeAsyncIterator() |
| 113 | + self.processor = NIOSingleStepByteToMessageProcessor( |
| 114 | + base.decoder, |
| 115 | + maximumBufferSize: base.maximumBufferSize |
| 116 | + ) |
| 117 | + self.state = .readingFromBuffer |
| 118 | + } |
| 119 | + |
| 120 | + /// Retrieve the next element from the ``NIODecodedAsyncSequence``. |
| 121 | + /// |
| 122 | + /// The same as `next(isolation:)` but not isolated to an actor, which allows |
| 123 | + /// for less availability restrictions. |
| 124 | + @inlinable |
| 125 | + public mutating func next() async throws -> Element? { |
| 126 | + while true { |
| 127 | + switch self.state { |
| 128 | + case .finishedDecoding: |
| 129 | + return nil |
| 130 | + case .readingFromBuffer: |
| 131 | + let (decoded, ended) = try self.processor.decodeNext( |
| 132 | + decodeMode: .normal, |
| 133 | + seenEOF: false |
| 134 | + ) |
| 135 | + |
| 136 | + // We expect `decodeNext()` to only return `ended == true` only if we've notified it |
| 137 | + // that we've read the last chunk from the buffer, using `decodeMode: .last`. |
| 138 | + assert(!ended) |
| 139 | + |
| 140 | + if let decoded { |
| 141 | + return decoded |
| 142 | + } |
| 143 | + |
| 144 | + // Read more data into the buffer so we can decode more messages |
| 145 | + guard let nextBuffer = try await self.baseIterator.next() else { |
| 146 | + // Ran out of data to read. |
| 147 | + self.state = .readLastChunkFromBuffer |
| 148 | + continue |
| 149 | + } |
| 150 | + self.processor.append(nextBuffer) |
| 151 | + case .readLastChunkFromBuffer: |
| 152 | + let (decoded, ended) = try self.processor.decodeNext( |
| 153 | + decodeMode: .last, |
| 154 | + seenEOF: true |
| 155 | + ) |
| 156 | + |
| 157 | + if ended { |
| 158 | + self.state = .finishedDecoding |
| 159 | + } |
| 160 | + |
| 161 | + return decoded |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + fatalError("Unreachable code") |
| 166 | + } |
| 167 | + |
| 168 | + /// Retrieve the next element from the ``NIODecodedAsyncSequence``. |
| 169 | + /// |
| 170 | + /// The same as `next()` but isolated to an actor. |
| 171 | + @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) |
| 172 | + @inlinable |
| 173 | + public mutating func next(isolation actor: isolated (any Actor)? = #isolation) async throws -> Element? { |
| 174 | + while true { |
| 175 | + switch self.state { |
| 176 | + case .finishedDecoding: |
| 177 | + return nil |
| 178 | + case .readingFromBuffer: |
| 179 | + let (decoded, ended) = try self.processor.decodeNext( |
| 180 | + decodeMode: .normal, |
| 181 | + seenEOF: false |
| 182 | + ) |
| 183 | + |
| 184 | + // We expect `decodeNext()` to only return `ended == true` only if we've notified it |
| 185 | + // that we've read the last chunk from the buffer, using `decodeMode: .last`. |
| 186 | + assert(!ended) |
| 187 | + |
| 188 | + if let decoded { |
| 189 | + return decoded |
| 190 | + } |
| 191 | + |
| 192 | + // Read more data into the buffer so we can decode more messages |
| 193 | + guard let nextBuffer = try await self.baseIterator.next(isolation: actor) else { |
| 194 | + // Ran out of data to read. |
| 195 | + self.state = .readLastChunkFromBuffer |
| 196 | + continue |
| 197 | + } |
| 198 | + self.processor.append(nextBuffer) |
| 199 | + case .readLastChunkFromBuffer: |
| 200 | + let (decoded, ended) = try self.processor.decodeNext( |
| 201 | + decodeMode: .last, |
| 202 | + seenEOF: true |
| 203 | + ) |
| 204 | + |
| 205 | + if ended { |
| 206 | + self.state = .finishedDecoding |
| 207 | + } |
| 208 | + |
| 209 | + return decoded |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + fatalError("Unreachable code") |
| 214 | + } |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 219 | +extension NIODecodedAsyncSequence: Sendable where Base: Sendable, Decoder: Sendable {} |
| 220 | + |
| 221 | +@available(*, unavailable) |
| 222 | +extension NIODecodedAsyncSequence.AsyncIterator: Sendable {} |
0 commit comments