Skip to content

Commit b79cc28

Browse files
committed
Conform DuplexStreamEndpoint to AsyncSequence
1 parent e64232a commit b79cc28

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

Sources/ATCommonTools/Swift-bound/DuplexStream.swift

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ public protocol DuplexStream: Sendable {
3333
///
3434
/// Each endpoint manages its own incoming buffer and pending read handlers. Data written from one
3535
/// endpoint is delivered to its peer's `receive` method.
36-
public actor DuplexStreamEndpoint: DuplexStream {
36+
public actor DuplexStreamEndpoint: AsyncSequence, DuplexStream {
37+
38+
public typealias Element = Data
3739

3840
/// A FIFO buffer storing incoming data that has not yet been read.
3941
private var buffer: [Data] = []
@@ -48,6 +50,10 @@ public actor DuplexStreamEndpoint: DuplexStream {
4850
/// This ensures there is no strong reference cycle between endpoints.
4951
private weak var peer: DuplexStreamEndpoint?
5052

53+
public nonisolated func makeAsyncIterator() -> AsyncIterator {
54+
AsyncIterator(endpoint: self)
55+
}
56+
5157
/// Sets the paired endpoint for this duplex stream endpoint.
5258
///
5359
/// - Parameter other: The peer endpoint to pair with.
@@ -122,6 +128,16 @@ public actor DuplexStreamEndpoint: DuplexStream {
122128
}
123129
}
124130
}
131+
132+
public struct AsyncIterator: AsyncIteratorProtocol {
133+
134+
/// The duplex stream endpoint that this async iterator reads data from.
135+
let endpoint: DuplexStreamEndpoint
136+
137+
public mutating func next() async -> Data? {
138+
await endpoint.read()
139+
}
140+
}
125141
}
126142

127143
/// Creates a pair of interconnected duplex stream endpoints.

0 commit comments

Comments
 (0)