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