mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-24 04:17:52 +00:00
This PR adds an experimental module for asynchronous streaming interfaces as a potential evolution to async sequence. These APIs are considered highly unstable and are mostly for experimentation purposes; hence, they are part of an underscored module and all APIs are hidden behind a trait. I expect significant changes to those APIs to offer more functionality such as gather scatter and more.
54 lines
1.7 KiB
Swift
54 lines
1.7 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift Async Algorithms open source project
|
|
//
|
|
// Copyright (c) 2026 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See https://swift.org/LICENSE.txt for license information
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#if UnstableAsyncStreaming && compiler(>=6.4)
|
|
import AsyncStreaming
|
|
import BasicContainers
|
|
import ContainersPreview
|
|
|
|
@available(macOS 26.2, iOS 26.2, watchOS 26.2, tvOS 26.2, visionOS 26.2, *)
|
|
struct UniqueArrayAsyncReader: ~Copyable, AsyncReader {
|
|
typealias ReadElement = Int
|
|
typealias ReadFailure = Never
|
|
|
|
var storage: UniqueArray<Int>
|
|
|
|
mutating func read<Return: ~Copyable, Failure: Error>(
|
|
maximumCount: Int,
|
|
body: (consuming InputSpan<Int>) async throws(Failure) -> Return
|
|
) async throws(EitherError<Never, Failure>) -> Return {
|
|
do {
|
|
guard storage.count > 0 else {
|
|
return try await body(InputSpan<Int>())
|
|
}
|
|
|
|
let count = min(maximumCount, storage.count)
|
|
|
|
// Use the callback-based consume which correctly updates storage's count.
|
|
var chunk = UniqueArray<Int>(minimumCapacity: count)
|
|
self.storage.consume(
|
|
0..<count,
|
|
consumingWith: { inputSpan in
|
|
chunk.append(moving: &inputSpan)
|
|
}
|
|
)
|
|
|
|
// Drain the local chunk to get InputSpan for the async body.
|
|
var consumer = chunk.consume(chunk.startIndex..<chunk.count)
|
|
let inputSpan = consumer.drainNext(maximumCount: .max)
|
|
return try await body(inputSpan)
|
|
} catch {
|
|
throw .second(error)
|
|
}
|
|
}
|
|
}
|
|
#endif
|