Compare commits

...
11 Commits
Author SHA1 Message Date
Faris Basha TM 088f92a30c Fix dead links to moved source files and the Collections guide (#469)
The channel and debounce sources moved into Channels/ and Debounce/,
AsyncChunksOfCountAndSignalSequence.swift is now
AsyncChunksOfCountOrSignalSequence.swift, and the Collections guide
lives in the DocC catalog, so these links return 404.
2026-11-18 06:44:13 -08:00
Rick Newton-Rogers 74a48bddc6 Revert "Bump swiftlang/github-workflows to 0.0.18 (#467)" (#468)
This reverts commit ba5872bfcb.
2026-11-16 19:27:54 -05:00
Rick Newton-Rogers ba5872bfcb Bump swiftlang/github-workflows to 0.0.18 (#467)
The new workflows use macOS Golden Gate rather than macOS Tahoe by default.
2026-11-16 19:22:41 -05:00
Hokila Jan cbde9aed74 Preserve debounce upstream failure without outstanding demand (#451)
* Preserve debounce upstream failure without demand

* Add debounce upstream failure regression tests
2026-10-05 16:11:40 +02:00
Tessaro d9c26817af Fix AsyncAlgorithms 1.3 availability macro typo (#453)
The `#else` branch declared `AsyncAlgorithms_v1_3` with the macro name
`AsyncAlgorithms 1.2`, so that branch defined `AsyncAlgorithms 1.2` twice
and never defined `AsyncAlgorithms 1.3`.

Issue: https://github.com/apple/swift-async-algorithms/issues/452
2026-10-02 14:35:24 +02:00
Aniket 822cfb8331 Fix MultiProducerSingleConsumerAsyncChannel doc examples to use takeChannel() (#460)
The stored channel property of ChannelAndStream is intentionally
internal, so the documented consume channelAndSource.channel snippet
fails to compile for clients. The supported API is takeChannel(); use
it in both doc examples.

Signed-off-by: Aniket <aniketkomailkro@gmail.com>
2026-10-02 14:04:26 +02:00
Francesco Paolo Severino 13713a4ffd Fix compilation errors in AsyncStreaming (#459)
* Fix compilation errors

* Enable traits in CI
2026-09-29 13:33:55 +02:00
Tim Condon 789dcf1f3d fix for Swift Collections 1.7.0 (#456) 2026-09-23 19:56:14 +02:00
Tianhao Liu 11645b8feb [AsyncStreaming] Propagate cancellation to late readers (#449)
* [AsyncStreaming] Propagate cancellation to late readers

Distinguish cancellation from normal source completion when a reader continuation is installed after the channel has already finished.

* [AsyncStreaming] Distinguish terminal read states

Track cancellation separately from an already-consumed terminal result so normal source completion does not throw CancellationError. Precondition on repeated reads after cancellation, a final element, or a source failure, with coverage for each terminal path.

* [AsyncStreaming] Handle pending reader cancellation

Deliver cancellation exactly once when it races with a resumed reader, preserve fused final-element completion, and align terminal-read tests and documentation with the reader contract.

* [AsyncStreaming] Test cancellation through public API

Remove the internal-only state-machine test so the regression suite exercises the supported AsyncStreaming interface without @testable import.
2026-09-03 10:53:07 +02:00
da-hye0 a5195afbd5 Fix typos in Evolution and DocC docs (#446) 2026-08-09 14:23:18 +02:00
Zayan KhanandClaude Fable 5 46b3cc3a4e Fix filename typo and template placeholder in Evolution docs (#445)
Rename 0016-mutli-producer-single-consumer-channel.md to the
correctly spelled 0016-multi-...; the document's own proposal link
already uses the correct spelling and currently 404s. Fill in the
NNNN template placeholder in 0017-map-error.md's proposal link.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:17:02 +02:00
42 changed files with 400 additions and 170 deletions

No files matched your search

+2
View File
@@ -15,6 +15,8 @@ jobs:
linux_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}, {\"swift_version\": \"5.10\"}]]"
windows_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}]"
enable_wasm_sdk_build: true
swift_flags: "--enable-all-traits"
swift_nightly_flags: "--enable-all-traits"
soundness:
name: Soundness
+1 -1
View File
@@ -38,7 +38,7 @@ for await (first, second) in (1...5).async.adjacentPairs() {
// First: 4, Second: 5
```
It composes well with the [Dictionary.init(_:uniquingKeysWith:)](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md) API that deals with `AsyncSequence` of tuples.
It composes well with the [Dictionary.init(_:uniquingKeysWith:)](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md) API that deals with `AsyncSequence` of tuples.
```swift
Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs())
+2 -2
View File
@@ -3,8 +3,8 @@
* Author(s): [Philippe Hausler](https://github.com/phausler)
[
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChannel.swift),
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncThrowingChannel.swift) |
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Channels/AsyncChannel.swift),
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Channels/AsyncThrowingChannel.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChannel.swift)
]
+1 -1
View File
@@ -5,7 +5,7 @@
* Implementation: [
[By group](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift),
[On projection](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift),
[Count and signal](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift)
[Count and signal](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunksOfCountOrSignalSequence.swift)
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChunk.swift)
]
[
+1 -1
View File
@@ -5,7 +5,7 @@
* Status: **Accepted**
* Implementation:
[
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncDebounceSequence.swift) |
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Debounce/AsyncDebounceSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestDebounce.swift)
]
[
+1 -1
View File
@@ -48,7 +48,7 @@ The buffer internally to the share algorithm will only extend back to the furthe
## Runtime Behavior
The runtime behaviors fall into a few categories; ordering, iteration isolation, cancellation, and lifetimes. To understand the beahviors there are a terms useful to define. Each creation of the AsyncIterator of the sequence and invocation of next will be referred to a side of the share iteration. The back pressure to the system to fetch a new element or termination is refered to as demand. The limit which is the pending gate for awaiting until the buffer has been serviced used for the `AsyncBufferSequencePolicy.bounded(_ : Int)` policy. The last special definition is that of the extent which is specifically in this case the lifetime of the asynchronous sequence itself.
The runtime behaviors fall into a few categories; ordering, iteration isolation, cancellation, and lifetimes. To understand the behaviors there are a terms useful to define. Each creation of the AsyncIterator of the sequence and invocation of next will be referred to a side of the share iteration. The back pressure to the system to fetch a new element or termination is referred to as demand. The limit which is the pending gate for awaiting until the buffer has been serviced used for the `AsyncBufferSequencePolicy.bounded(_ : Int)` policy. The last special definition is that of the extent which is specifically in this case the lifetime of the asynchronous sequence itself.
When the underlying type backing the share algorithm is constructed a new extent is created; this is used for tracking the reference lifetime under the hood and is used to both house the iteration but also to identify the point at which no more sides can be constructed. When no more sides can be constructed and no sides are left to iterate then the backing iteration is canceled. This prevents any un-referenced task backing the iteration to not be leaked by the algorith itself.
+2 -2
View File
@@ -1,13 +1,13 @@
# Map Error
* Proposal: [SAA-NNNN](NNNN-map-error.md)
* Proposal: [SAA-0017](0017-map-error.md)
* Authors: [Clive Liu](https://github.com/clive819) [Philippe Hausler](https://github.com/phausler)
* Review Manager: TBD
* Status: **Awaiting review**
## Introduction
Asynchronous sequences often particpate in carefully crafted systems of algorithms spliced together. Some of those algorithms require that both the element type and the failure type are the same as each-other. In order to line those types up for the element we have the map algorithm today, however there are other times at which when using more specific APIs that transforming the Failure type is needed.
Asynchronous sequences often participate in carefully crafted systems of algorithms spliced together. Some of those algorithms require that both the element type and the failure type are the same as each-other. In order to line those types up for the element we have the map algorithm today, however there are other times at which when using more specific APIs that transforming the Failure type is needed.
## Motivation
+3 -2
View File
@@ -14,7 +14,7 @@ let AsyncAlgorithms_v1_3 =
#else
let AsyncAlgorithms_v1_1 = "AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
let AsyncAlgorithms_v1_2 = "AvailabilityMacro=AsyncAlgorithms 1.2:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
let AsyncAlgorithms_v1_3 = "AvailabilityMacro=AsyncAlgorithms 1.2:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
let AsyncAlgorithms_v1_3 = "AvailabilityMacro=AsyncAlgorithms 1.3:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
#endif
let availabilityMacros: [SwiftSetting] = [
@@ -145,6 +145,7 @@ let package = Package(
"AsyncStreaming",
.product(name: "BasicContainers", package: "swift-collections"),
.product(name: "ContainersPreview", package: "swift-collections"),
.product(name: "SpanPreview", package: "swift-collections"),
],
swiftSettings: [
.enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"),
@@ -165,7 +166,7 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [
.package(
url: "https://github.com/apple/swift-collections.git",
from: "1.5.1",
from: "1.7.0",
traits: [.trait(name: "UnstableContainersPreview", condition: .when(traits: ["UnstableAsyncStreaming"]))]
)
]
@@ -32,7 +32,7 @@ for await (first, second) in (1...5).async.adjacentPairs() {
// First: 4, Second: 5
```
It composes well with the [Dictionary.init(_:uniquingKeysWith:)](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md) API that deals with `AsyncSequence` of tuples.
It composes well with the [Dictionary.init(_:uniquingKeysWith:)](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md) API that deals with `AsyncSequence` of tuples.
```swift
Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs())
@@ -45,7 +45,7 @@ The buffer internally to the share algorithm will only extend back to the furthe
## Runtime Behavior
The runtime behaviors fall into a few categories; ordering, iteration isolation, cancellation, and lifetimes. To understand the beahviors there are a terms useful to define. Each creation of the AsyncIterator of the sequence and invocation of next will be referred to a side of the share iteration. The back pressure to the system to fetch a new element or termination is refered to as demand. The limit which is the pending gate for awaiting until the buffer has been serviced used for the `AsyncBufferSequencePolicy.bounded(_ : Int)` policy. The last special definition is that of the extent which is specifically in this case the lifetime of the asynchronous sequence itself.
The runtime behaviors fall into a few categories; ordering, iteration isolation, cancellation, and lifetimes. To understand the behaviors there are a terms useful to define. Each creation of the AsyncIterator of the sequence and invocation of next will be referred to a side of the share iteration. The back pressure to the system to fetch a new element or termination is referred to as demand. The limit which is the pending gate for awaiting until the buffer has been serviced used for the `AsyncBufferSequencePolicy.bounded(_ : Int)` policy. The last special definition is that of the extent which is specifically in this case the lifetime of the asynchronous sequence itself.
When the underlying type backing the share algorithm is constructed a new extent is created; this is used for tracking the reference lifetime under the hood and is used to both house the iteration but also to identify the point at which no more sides can be constructed. When no more sides can be constructed and no sides are left to iterate then the backing iteration is canceled. This prevents any un-referenced task backing the iteration to not be leaked by the algorith itself.
@@ -399,9 +399,9 @@ struct DebounceStateMachine<Base: AsyncSequence & Sendable, C: Clock>: Sendable
return .none
case .waitingForDemand(let task, .none, let clockContinuation, .none):
// We don't have any buffered element so we can just go ahead
// and transition to finished and cancel everything
self.state = .finished
// We don't have outstanding demand to deliver the error to, so store it
// until the downstream calls next and cancel everything.
self.state = .upstreamFailure(error: error)
return .cancelTaskAndClockContinuation(
task: task,
@@ -37,13 +37,13 @@ public struct MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError: Error
/// Afterwards, you can pass the source to the producer and the channel to the consumer.
///
/// ```
/// let channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel(
/// var channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel(
/// of: Int.self,
/// backpressureStrategy: .watermark(low: 2, high: 4)
/// )
///
/// // The channel and source can be extracted from the returned type
/// let channel = consume channelAndSource.channel
/// let channel = channelAndSource.takeChannel()
/// let source = consume channelAndSource.source
/// ```
///
@@ -127,11 +127,11 @@ public struct MultiProducerSingleConsumerAsyncChannel<Element, Failure: Error>:
/// components from it.
///
/// ```swift
/// let channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel(
/// var channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel(
/// of: Int.self,
/// backpressureStrategy: .watermark(low: 5, high: 10)
/// )
/// var channel = consume channelAndSource.channel
/// var channel = channelAndSource.takeChannel()
/// var source = consume channelAndSource.source
/// ```
@frozen
@@ -25,7 +25,7 @@ public struct AsyncReaderInsufficientElementsError: Error, Hashable {
public init() {}
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension AsyncReader where Self: ~Copyable, Self: ~Escapable, ReadElement: ~Copyable {
/// Collects elements from the reader into the provided container, up to the
/// container's available space.
@@ -11,10 +11,10 @@
#if UnstableAsyncStreaming && compiler(>=6.4)
public import ContainersPreview
import ContainersPreview
// swift-format-ignore: AmbiguousTrailingClosureOverload
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension AsyncReader where Self: ~Copyable, Self: ~Escapable {
/// Iterates over all chunks from the reader, executing the provided body for
/// each buffer until the stream signals end-of-stream.
@@ -25,7 +25,7 @@ import ContainersPreview
// writer across the read closure boundary) the constraint should be added
// back so `pipe` works for `~Escapable` writers too.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension AsyncReader where Self: ~Copyable, Self: ~Escapable, Self.ReadElement: ~Copyable {
/// Pipes all elements from this reader into the given writer, fusing the
/// terminal chunk with a `finish` on the writer.
@@ -33,7 +33,7 @@ public import ContainersPreview
///
/// After the reader has emitted a non-`nil` `finalElement`, calling
/// ``read(body:)`` again is a programmer error.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public protocol AsyncReader<ReadElement, ReadFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this reader reads.
// TODO: Check if we should support ~Escapable elements
@@ -29,7 +29,7 @@ public import ContainersPreview
/// type to carry data along with the end signal, or `Never` for endless
/// streams. When ``FinalElement`` is `Never`, ``finish(finalElement:)`` cannot
/// be called and the writer can be written to indefinitely.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public protocol AsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this writer writes.
// TODO: Check if we should support ~Escapable elements
@@ -91,7 +91,7 @@ public protocol AsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable
) async throws(WriteFailure)
}
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension AsyncWriter where Self: ~Copyable, Self: ~Escapable, FinalElement == Void {
/// Concludes the writer with no payload.
///
@@ -24,7 +24,7 @@ public import ContainersPreview
/// from the caller-supplied buffer into the underlying writer's
/// closure-supplied buffer. The underlying writer's deferred-flush
/// behavior, if any, is preserved.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct AsyncWriterCallerAsyncWriterAdapter<
Underlying: AsyncWriter & ~Copyable
>: ~Copyable, CallerAsyncWriter {
@@ -77,7 +77,7 @@ public struct AsyncWriterCallerAsyncWriterAdapter<
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension AsyncWriter where Self: ~Copyable {
/// Adapts this ``AsyncWriter`` to a ``CallerAsyncWriter``.
///
@@ -26,7 +26,7 @@ import BasicContainers
// capturing the writer across the closure boundary) the constraint should be
// added back so `pipe` works for `~Escapable` writers too.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension CallerAsyncReader where Self: ~Copyable, Self: ~Escapable, Self.ReadElement: ~Copyable {
/// Pipes all elements from this reader into the given writer, then signals
/// end-of-stream with a `finish` call on the writer.
@@ -32,7 +32,7 @@ public import ContainersPreview
///
/// After the reader has returned a non-`nil` `FinalElement`, calling
/// ``read(into:)`` again is a programmer error.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public protocol CallerAsyncReader<ReadElement, ReadFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this reader reads.
// TODO: Check if we should support ~Escapable elements
@@ -35,7 +35,7 @@ import BasicContainers
/// Conformers must accept zero, one, or many `write(buffer:)` calls, optionally
/// followed by a single `finish(buffer:finalElement:)` call. After `finish`
/// returns, the writer is consumed and no further calls are valid.
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public protocol CallerAsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this writer writes.
// TODO: Check if we should support ~Escapable elements
@@ -90,7 +90,7 @@ public protocol CallerAsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Co
) async throws(WriteFailure) where Buffer.Element: ~Copyable
}
@available(macOS 26.2, iOS 26.2, watchOS 26.2, tvOS 26.2, visionOS 26.2, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension CallerAsyncWriter where Self: ~Copyable, Self: ~Escapable, FinalElement == Void {
/// Concludes the writer with no final buffer and no extra payload.
///
@@ -27,7 +27,7 @@ public import BasicContainers
/// ``CallerAsyncWriter/finish(buffer:finalElement:)`` always receives an
/// empty buffer. Conformers that need fused close should implement
/// ``AsyncWriter`` directly rather than going through this adapter.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct CallerAsyncWriterAsyncWriterAdapter<
Underlying: CallerAsyncWriter & ~Copyable,
Buffer: DynamicContainer<Underlying.WriteElement> & ~Copyable
@@ -76,7 +76,7 @@ public struct CallerAsyncWriterAsyncWriterAdapter<
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension CallerAsyncWriter where Self: ~Copyable {
/// Adapts this ``CallerAsyncWriter`` to an ``AsyncWriter``, using
/// ``UniqueArray`` as the buffer container.
@@ -47,7 +47,7 @@ public import ContainersPreview
/// Each direction's writer terminates its half of the channel
/// independently by calling ``Writer/finish(finalElement:)`` or
/// ``Writer/finish(throwing:)``.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct DuplexAsyncChannel<
Element: Sendable,
FinalElement: Sendable,
@@ -129,7 +129,7 @@ public struct DuplexAsyncChannel<
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension DuplexAsyncChannel where FinalElement == Void {
/// Creates a new duplex channel with a `Void` end-of-stream payload and
/// runs `body` with all four handles.
@@ -164,7 +164,7 @@ extension DuplexAsyncChannel where FinalElement == Void {
// MARK: - Backpressure strategy
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension DuplexAsyncChannel {
/// A backpressure strategy applied independently to each direction of
/// the duplex.
@@ -228,7 +228,7 @@ extension DuplexAsyncChannel {
// MARK: - Writer
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension DuplexAsyncChannel {
/// The writer half of one side of a ``DuplexAsyncChannel``.
///
@@ -392,7 +392,7 @@ extension DuplexAsyncChannel {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension DuplexAsyncChannel.Writer where FinalElement == Void {
/// Finishes this direction with an empty `Void` end-of-stream payload.
///
@@ -407,7 +407,7 @@ extension DuplexAsyncChannel.Writer where FinalElement == Void {
// MARK: - Reader
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension DuplexAsyncChannel {
/// The reader half of one side of a ``DuplexAsyncChannel``.
///
@@ -446,8 +446,9 @@ extension DuplexAsyncChannel {
/// in `read`) — and whose outer `.second` arm carries the failure
/// thrown by `body`.
///
/// - Important: After the reader observes a non-`nil` `finalElement`,
/// calling `read(body:)` again is a programmer error.
/// - Important: After the reader observes a non-`nil` `finalElement` or
/// `read(body:)` throws a read-side error, calling `read(body:)` again is
/// a programmer error.
@inlinable
public mutating func read<Return: ~Copyable, BodyFailure: Error>(
body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return
@@ -513,13 +514,8 @@ extension DuplexAsyncChannel {
throw .second(error)
}
case .returnNil:
var empty = UniqueDeque<Element>()
do throws(BodyFailure) {
return try await body(&empty, nil)
} catch {
throw .second(error)
}
case .throwCancellation:
throw .first(.second(CancellationError()))
case .suspend:
do {
@@ -14,7 +14,7 @@ public import DequeModule
public import Synchronization
public import ContainersPreview
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel {
@usableFromInline
enum _InternalBackpressureStrategy: Sendable, CustomStringConvertible {
@@ -105,7 +105,7 @@ extension MultiProducerSingleConsumerAsyncChannel {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel {
@usableFromInline
final class _Storage: Sendable {
@@ -272,6 +272,8 @@ extension MultiProducerSingleConsumerAsyncChannel {
switch consume action {
case .resumeReader(let c):
c.resume()
case .resumeReaderWithCancellationError(let c):
c.resume(throwing: .second(CancellationError()))
case .none:
break
}
@@ -306,7 +308,7 @@ extension MultiProducerSingleConsumerAsyncChannel {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel._Storage {
@usableFromInline
struct _StateMachine: ~Copyable, Sendable {
@@ -410,12 +412,12 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
case .channeling(let s):
let producers = Array(s.suspendedProducers.lazy.map { $0.1 })
let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: false)))
self = .init(state: .finished(.consumed))
return .failProducersAndCallOnTerminations(producers, onTerminations)
case .sourceFinished(let s):
let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: true)))
self = .init(state: .finished(.consumed))
return .callOnTerminations(onTerminations)
case .finished(let s):
@@ -679,16 +681,16 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
/// The channel was finished with a failure and the buffer is now drained;
/// throw the failure to the reader.
case throwFailure(Failure?, [(UInt64, @Sendable () -> Void)])
case returnNil
/// Cancellation finished the channel before it could be delivered to the reader.
case throwCancellation
}
@inlinable
mutating func readAvailable() -> ReadAvailableAction {
switch consume self._state {
case .channeling(var s):
let isProducerBufferEmpty = s.buffer.withValue {
$0.borrow()!.value.isEmpty
}
// Optional chaining borrows the deque; unwrap only the Boolean result.
let isProducerBufferEmpty = s.buffer.withValue { $0?.isEmpty }!
guard isProducerBufferEmpty else {
// We are going to swap the two buffers around. The cached buffer
// may not exist yet on the first read; fall back to a fresh empty
@@ -731,7 +733,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
let fe = s.finalElement.swap(newValue: nil)
let onTerminations = s.onTerminations
let failure = s.failure
self = .init(state: .finished(.init(sourceFinished: true)))
self = .init(state: .finished(.consumed))
if let failure {
return .throwFailure(failure, onTerminations)
@@ -745,8 +747,14 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
)
case .finished(let s):
self = .init(state: .finished(s))
return .returnNil
switch s {
case .cancelled:
self = .init(state: .finished(.consumed))
return .throwCancellation
case .consumed:
self = .init(state: .finished(.consumed))
preconditionFailure("MultiProducerSingleConsumerAsyncChannel.read called after termination")
}
}
}
@@ -800,6 +808,9 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
@usableFromInline
enum SuspendReadAction: ~Copyable, Sendable {
case resumeReader(UnsafeContinuation<Void, EitherError<Failure, CancellationError>>)
case resumeReaderWithCancellationError(
UnsafeContinuation<Void, EitherError<Failure, CancellationError>>
)
}
@inlinable
@@ -811,7 +822,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
guard s.readerContinuation == nil else {
fatalError("MultiProducerSingleConsumerAsyncChannel internal inconsistency: concurrent readers")
}
let isEmpty = s.buffer.withValue { $0.borrow()!.value.isEmpty }
let isEmpty = s.buffer.withValue { $0?.isEmpty }!
if !isEmpty {
self = .init(state: .channeling(s))
return .resumeReader(continuation)
@@ -825,8 +836,16 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
return .resumeReader(continuation)
case .finished(let s):
self = .init(state: .finished(s))
return .resumeReader(continuation)
switch s {
case .cancelled:
// Cancellation may finish the channel before this continuation is installed.
// Consume that pending cancellation exactly once.
self = .init(state: .finished(.consumed))
return .resumeReaderWithCancellationError(continuation)
case .consumed:
self = .init(state: .finished(.consumed))
preconditionFailure("MultiProducerSingleConsumerAsyncChannel.read called after termination")
}
}
}
@@ -850,10 +869,11 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
let reader = s.readerContinuation.take()
let producers = Array(s.suspendedProducers.lazy.map { $0.1 })
let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: false)))
if let reader {
self = .init(state: .finished(.consumed))
return .resumeReaderWithCancellationError(reader, producers, onTerminations)
}
self = .init(state: .finished(.cancelled))
return .failProducersAndCallOnTerminations(producers, onTerminations)
case .sourceFinished(let s):
@@ -868,7 +888,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
@usableFromInline
enum _State: ~Copyable, Sendable {
@@ -980,12 +1000,9 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
}
@usableFromInline
struct Finished: ~Copyable, Sendable {
@usableFromInline
var sourceFinished: Bool
@inlinable
init(sourceFinished: Bool) { self.sourceFinished = sourceFinished }
enum Finished: Sendable {
case cancelled
case consumed
}
case channeling(Channeling)
@@ -995,7 +1012,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
}
/// A producer suspended waiting for backpressure to allow further sends.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@usableFromInline
enum _MultiProducerSingleConsumerSuspendedProducer: @unchecked Sendable {
case closure((Result<Void, any Error>) -> Void)
@@ -1005,7 +1022,7 @@ enum _MultiProducerSingleConsumerSuspendedProducer: @unchecked Sendable {
/// Helper to move a non-Sendable value across isolation regions (mirror of
/// the helper in AsyncAlgorithms; kept private to AsyncStreaming to avoid
/// reaching into another module's internals).
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@usableFromInline
struct _Disconnected<Value: ~Copyable>: ~Copyable, Sendable {
private nonisolated(unsafe) var value: Value
@@ -32,7 +32,7 @@ public import ContainersPreview
/// end-of-stream signal. A producer terminates the channel by calling
/// either ``Source/finish(finalElement:)`` to signal end-of-stream
/// or ``Source/finish(throwing:)`` to terminate with a failure.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct MultiProducerSingleConsumerAsyncChannel<
Element,
FinalElement,
@@ -95,7 +95,7 @@ public struct MultiProducerSingleConsumerAsyncChannel<
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel where FinalElement == Void {
/// Creates a new channel with a `Void` end-of-stream payload and runs
/// `body` with the channel and its initial source.
@@ -125,7 +125,7 @@ extension MultiProducerSingleConsumerAsyncChannel where FinalElement == Void {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel {
/// A handle for sending elements to the channel.
public struct Source: ~Copyable, Sendable {
@@ -289,7 +289,7 @@ extension MultiProducerSingleConsumerAsyncChannel {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel.Source where FinalElement == Void {
/// Finishes the channel with an empty `Void` end-of-stream payload.
///
@@ -304,7 +304,7 @@ extension MultiProducerSingleConsumerAsyncChannel.Source where FinalElement == V
// MARK: - Reading
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
extension MultiProducerSingleConsumerAsyncChannel {
/// Reads the next chunk of elements from the channel.
///
@@ -320,8 +320,9 @@ extension MultiProducerSingleConsumerAsyncChannel {
/// the task is canceled while suspended in `read`) — and whose outer
/// `.second` arm carries the failure thrown by `body`.
///
/// - Important: After the reader observes a non-`nil` `finalElement`,
/// calling `read(body:)` again is a programmer error.
/// - Important: After the reader observes a non-`nil` `finalElement` or
/// `read(body:)` throws a read-side error, calling `read(body:)` again is
/// a programmer error.
@inlinable
public mutating func read<Return: ~Copyable, BodyFailure: Error>(
body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return
@@ -391,13 +392,8 @@ extension MultiProducerSingleConsumerAsyncChannel {
throw .second(error)
}
case .returnNil:
var empty = UniqueDeque<Element>()
do throws(BodyFailure) {
return try await body(&empty, nil)
} catch {
throw .second(error)
}
case .throwCancellation:
throw .first(.second(CancellationError()))
case .suspend:
do {
@@ -413,7 +409,7 @@ extension MultiProducerSingleConsumerAsyncChannel {
/// An error that ``MultiProducerSingleConsumerAsyncChannel/Source/write(buffer:)``
/// throws when its source has already finished.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
public struct MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError: Error {
@usableFromInline
init() {}
@@ -12,6 +12,10 @@
import XCTest
import AsyncAlgorithms
private struct DebounceTestError: Error, Equatable, Sendable {
let value: Int
}
final class TestDebounce: XCTestCase {
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
func test_delayingValues() throws {
@@ -58,6 +62,72 @@ final class TestDebounce: XCTestCase {
}
}
func test_upstreamFailureWithoutOutstandingDemand() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"a^"
$0.inputs[0].debounce(for: .steps(0), clock: $0.clock)
"a,,,^"
}
}
func test_upstreamFailureWithoutElementsPreservesError() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
let expectedError = DebounceTestError(value: 1)
let (stream, source) = AsyncThrowingStream<Int, Error>.makeStream()
source.finish(throwing: expectedError)
var iterator = stream.debounce(for: .milliseconds(10), clock: .continuous).makeAsyncIterator()
do {
_ = try await iterator.next()
XCTFail("Expected the upstream error")
} catch let error as DebounceTestError {
XCTAssertEqual(error, expectedError)
}
let result = try await iterator.next()
XCTAssertNil(result)
}
func test_upstreamFailureAfterElementAndWithoutDemandPreservesError() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
let expectedError = DebounceTestError(value: 2)
let (stream, source) = AsyncThrowingStream<Int, Error>.makeStream()
source.yield(1)
let finisher = Task {
try? await Task.sleep(for: .milliseconds(100))
source.finish(throwing: expectedError)
}
defer { finisher.cancel() }
var iterator = stream.debounce(for: .milliseconds(10), clock: .continuous).makeAsyncIterator()
let first = try await iterator.next()
XCTAssertEqual(first, 1)
// The upstream fails while the consumer has no outstanding demand.
try await Task.sleep(for: .milliseconds(300))
do {
_ = try await iterator.next()
XCTFail("Expected the upstream error")
} catch let error as DebounceTestError {
XCTAssertEqual(error, expectedError)
}
// Consuming the failure completes the iterator; it must not produce another value
// or resume completion more than once.
let result = try await iterator.next()
XCTAssertNil(result)
}
func test_noValues() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
@@ -18,6 +18,7 @@ import Testing
@Suite
struct AsyncReaderCollectIntoTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectFillsTargetWhenReaderHasFewerElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -31,6 +32,7 @@ struct AsyncReaderCollectIntoTests {
#expect(collected == [1, 2, 3])
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectFillsTargetWhenReaderHasExactlyFreeCapacityElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -41,6 +43,7 @@ struct AsyncReaderCollectIntoTests {
#expect(target.count == 3)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectThrowsWhenReaderProducesMoreThanFreeCapacity() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -55,6 +58,7 @@ struct AsyncReaderCollectIntoTests {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectIntoEmptyReader() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -68,6 +72,7 @@ struct AsyncReaderCollectIntoTests {
@Suite
struct AsyncReaderCollectExactlyTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectExactlyFillsTargetWhenReaderProducesExactCount() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -81,6 +86,7 @@ struct AsyncReaderCollectExactlyTests {
#expect(collected == [1, 2, 3])
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectExactlyThrowsWhenReaderProducesFewer() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -98,6 +104,7 @@ struct AsyncReaderCollectExactlyTests {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectExactlyThrowsWhenReaderProducesMore() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -118,6 +125,7 @@ struct AsyncReaderCollectExactlyTests {
@Suite
struct AsyncReaderCollectIntoMaximumSizeTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectGrowsContainerWhenReaderHasFewerThanMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -131,6 +139,7 @@ struct AsyncReaderCollectIntoMaximumSizeTests {
#expect(collected == [1, 2, 3])
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectFillsContainerExactlyAtMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30]))
@@ -141,6 +150,7 @@ struct AsyncReaderCollectIntoMaximumSizeTests {
#expect(target.count == 3)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectThrowsWhenReaderProducesMoreThanMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -155,6 +165,7 @@ struct AsyncReaderCollectIntoMaximumSizeTests {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func collectAppendsToExistingContents() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 2, copying: [3, 4]))
@@ -18,6 +18,7 @@ import Testing
@Suite
struct AsyncReaderforEachBufferTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferIteratesAllSpans() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -30,6 +31,7 @@ struct AsyncReaderforEachBufferTests {
#expect(elementCount == 5)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferProcessesElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30]))
@@ -44,6 +46,7 @@ struct AsyncReaderforEachBufferTests {
#expect(sum == 60)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferWithEmptyReader() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -57,6 +60,7 @@ struct AsyncReaderforEachBufferTests {
#expect(callCount == 0)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -69,6 +73,7 @@ struct AsyncReaderforEachBufferTests {
#expect(observedCounts.allSatisfy { $0 > 0 })
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferThrowingDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws {
enum TestError: Error {}
@@ -83,6 +88,7 @@ struct AsyncReaderforEachBufferTests {
#expect(observedCounts.allSatisfy { $0 > 0 })
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferWithThrowingBody() async {
enum TestError: Error {
@@ -101,6 +107,7 @@ struct AsyncReaderforEachBufferTests {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferWithNeverFailingReader() async {
enum TestError: Error {
@@ -121,6 +128,7 @@ struct AsyncReaderforEachBufferTests {
#expect(count == 3)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func forEachBufferWithAsyncWork() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -19,7 +19,7 @@ import Testing
struct AsyncReaderPipeTests {
// MARK: - pipe(into:) — into a CallerAsyncWriter
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -33,7 +33,7 @@ struct AsyncReaderPipeTests {
var array = UniqueArray(copying: [1, 2, 3, 4, 5])
try await writerA.write(buffer: &array)
writerA.finish()
try await writerA.finish()
try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 5)
@@ -42,7 +42,7 @@ struct AsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -54,7 +54,7 @@ struct AsyncReaderPipeTests {
let writerB = writerB
let readerB = readerB
writerA.finish()
try await writerA.finish()
try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 5)
@@ -63,7 +63,7 @@ struct AsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoPreservesElementOrder() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -78,7 +78,7 @@ struct AsyncReaderPipeTests {
let elements = Array(1...50)
var array = UniqueArray(copying: elements)
try await writerA.write(buffer: &array)
writerA.finish()
try await writerA.finish()
try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 50)
@@ -89,7 +89,7 @@ struct AsyncReaderPipeTests {
// MARK: - pipe(copyingInto:) — into an AsyncWriter via the adapter
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeCopyingIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -103,7 +103,7 @@ struct AsyncReaderPipeTests {
var array = UniqueArray(copying: [1, 2, 3, 4, 5])
try await writerA.write(buffer: &array)
writerA.finish()
try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter())
var target = RigidArray<Int>(capacity: 5)
@@ -112,7 +112,7 @@ struct AsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeCopyingIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -124,7 +124,7 @@ struct AsyncReaderPipeTests {
let writerB = writerB
let readerB = readerB
writerA.finish()
try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter())
var target = RigidArray<Int>(capacity: 5)
@@ -133,7 +133,7 @@ struct AsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeCopyingIntoChunksTerminalChunkAcrossMultipleWrites() async throws {
// 200 elements through a small (16-element) AsyncWriter buffer
@@ -150,7 +150,7 @@ struct AsyncReaderPipeTests {
let elements = Array(1...200)
var array = UniqueArray(copying: elements)
try await writerA.write(buffer: &array)
writerA.finish()
try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter(initialCapacity: 16))
var target = RigidArray<Int>(capacity: 200)
@@ -23,7 +23,7 @@ struct AsyncWriterCallerAsyncWriterAdapterTests {
// asAsyncWriter() to get an AsyncWriter, then wrap THAT via
// asCallerAsyncWriter() to exercise this adapter end-to-end.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeAndFinishRoundTrip() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -45,7 +45,7 @@ struct AsyncWriterCallerAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeLoopsAcrossMultipleUnderlyingBuffers() async throws {
// The CallerAsyncWriterAsyncWriterAdapter underneath uses a
@@ -75,7 +75,7 @@ struct AsyncWriterCallerAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishWithoutWriteDeliversEmptyTerminator() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -95,7 +95,7 @@ struct AsyncWriterCallerAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishDeliversTrailingBufferAndPayload() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -17,6 +17,7 @@ import Testing
@Suite
struct AsyncWriterTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeElements() async {
var writer = UniqueArrayAsyncWriter()
@@ -33,6 +34,7 @@ struct AsyncWriterTests {
#expect(writer.storage[2] == 3)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeEmptyBuffer() async {
var writer = UniqueArrayAsyncWriter()
@@ -42,6 +44,7 @@ struct AsyncWriterTests {
#expect(writer.storage.count == 0)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeReturnsValue() async {
var writer = UniqueArrayAsyncWriter()
@@ -56,6 +59,7 @@ struct AsyncWriterTests {
#expect(writer.storage.count == 2)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeWithThrowingBody() async {
enum TestError: Error, Equatable {
@@ -74,6 +78,7 @@ struct AsyncWriterTests {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeMultipleTimes() async {
var writer = UniqueArrayAsyncWriter()
@@ -95,12 +100,14 @@ struct AsyncWriterTests {
#expect(writer.storage[3] == 4)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishVoidConvenience() async {
let writer = UniqueArrayAsyncWriter()
await writer.finish()
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishDeliversFinalElement() async {
let writer = UniqueArrayAsyncWriter()
@@ -19,7 +19,7 @@ import Testing
struct CallerAsyncReaderPipeTests {
// MARK: - pipe(into:) — into an AsyncWriter via the adapter
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -40,7 +40,7 @@ struct CallerAsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -59,7 +59,7 @@ struct CallerAsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeIntoLoopsAcrossMultipleBuffers() async throws {
// 200 elements through a small AsyncWriter buffer forces the pipe
@@ -85,7 +85,7 @@ struct CallerAsyncReaderPipeTests {
// MARK: - pipe(bufferingInto:) — into a CallerAsyncWriter
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeBufferingIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -106,7 +106,7 @@ struct CallerAsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeBufferingIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -125,7 +125,7 @@ struct CallerAsyncReaderPipeTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func pipeBufferingIntoReusesIntermediateBufferAcrossMultipleIterations() async throws {
// 100 elements through a 16-element intermediate buffer forces the
@@ -17,6 +17,7 @@ import Testing
@Suite
struct CallerAsyncReaderTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readIntoBuffer() async {
var reader = UniqueArrayCallerAsyncReader(
@@ -34,6 +35,7 @@ struct CallerAsyncReaderTests {
#expect(buffer[4] == 5)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readIntoBufferAtEnd() async {
var reader = UniqueArrayCallerAsyncReader(
@@ -46,6 +48,7 @@ struct CallerAsyncReaderTests {
#expect(buffer.count == 0)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readIntoBufferRespectsCapacity() async {
var reader = UniqueArrayCallerAsyncReader(
@@ -61,6 +64,7 @@ struct CallerAsyncReaderTests {
#expect(buffer[2] == 3)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readMultipleTimes() async {
var reader = UniqueArrayCallerAsyncReader(
@@ -21,7 +21,7 @@ struct CallerAsyncWriterAsyncWriterAdapterTests {
// we drive it through the duplex's CallerAsyncWriter side and verify
// the elements arrive on the peer reader.
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeAndFinishRoundTrip() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -45,7 +45,7 @@ struct CallerAsyncWriterAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func multipleWritesAreFlushedEagerly() async throws {
// The adapter must NOT defer the most recent write — each write call
@@ -83,7 +83,7 @@ struct CallerAsyncWriterAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishWithoutWriteDeliversEmptyTerminator() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -102,7 +102,7 @@ struct CallerAsyncWriterAsyncWriterAdapterTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func customBufferTypePreservesElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -17,6 +17,7 @@ import Testing
@Suite
struct CallerAsyncWriterTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeBuffer() async {
var writer = UniqueArrayCallerAsyncWriter()
@@ -27,6 +28,7 @@ struct CallerAsyncWriterTests {
#expect(writer.storage.count == 5)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeEmptyBuffer() async {
var writer = UniqueArrayCallerAsyncWriter()
@@ -37,6 +39,7 @@ struct CallerAsyncWriterTests {
#expect(writer.storage.count == 0)
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeLargeBuffer() async {
var writer = UniqueArrayCallerAsyncWriter(capacity: 100)
@@ -21,7 +21,7 @@ import Testing
struct DuplexAsyncChannelTests {
// MARK: - Round-trip
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func roundTripForwardDirection() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -45,7 +45,7 @@ struct DuplexAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func roundTripReverseDirection() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -69,7 +69,7 @@ struct DuplexAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func directionsAreIndependent() async throws {
// Bytes sent on the forward direction must NOT appear on the side that
@@ -107,7 +107,7 @@ struct DuplexAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func concurrentReadsOnBothDirections() async throws {
try await withThrowingTaskGroup(of: [Int].self) { group in
@@ -137,13 +137,13 @@ struct DuplexAsyncChannelTests {
var fwd = UniqueArray<Int>(minimumCapacity: 10)
for i in 0..<10 { fwd.append(i) }
try await writerA.write(buffer: &fwd)
writerA.finish()
try await writerA.finish()
// Reverse: write 100..<110 from main scope.
var rev = UniqueArray<Int>(minimumCapacity: 10)
for i in 100..<110 { rev.append(i) }
try await writerB.write(buffer: &rev)
writerB.finish()
try await writerB.finish()
// Drain forward from the main scope.
var forwardCollected: [Int] = []
@@ -165,7 +165,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Half-close
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finishingOneDirectionLeavesTheOtherOpen() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -181,7 +181,7 @@ struct DuplexAsyncChannelTests {
var fwdBuf = UniqueArray<Int>(minimumCapacity: 1)
fwdBuf.append(7)
try await writerA.write(buffer: &fwdBuf)
writerA.finish()
try await writerA.finish()
// Reverse direction still works.
var revBuf = UniqueArray<Int>(minimumCapacity: 1)
@@ -208,7 +208,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Final element
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func finalElementDeliveredOnFinish() async throws {
try await DuplexAsyncChannel<Int, String, Never>.withDuplex(
@@ -244,7 +244,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Failure isolation
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func failureOnOneDirectionDoesNotPoisonTheOther() async throws {
struct TestError: Error, Equatable {}
@@ -254,7 +254,7 @@ struct DuplexAsyncChannelTests {
throwing: TestError.self,
backpressureStrategy: .watermark(low: 2, high: 4)
) { writerA, readerA, writerB, readerB in
var writerA = writerA
let writerA = writerA
var readerA = readerA
var writerB = writerB
var readerB = readerB
@@ -263,7 +263,7 @@ struct DuplexAsyncChannelTests {
var revBuf = UniqueArray<Int>(minimumCapacity: 1)
revBuf.append(42)
try await writerB.write(buffer: &revBuf)
writerB.finish()
try await writerB.finish()
// Fail forward direction.
writerA.finish(throwing: TestError())
@@ -293,7 +293,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Backpressure isolation
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func backpressureOnOneDirectionDoesNotBlockTheOther() async throws {
// Forward writer is suspended on backpressure (writes more than the
@@ -343,7 +343,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Multi-producer per direction
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func clonedWriterCanProduceConcurrently() async throws {
// Two writes happen sequentially through the original writer and its
@@ -371,8 +371,8 @@ struct DuplexAsyncChannelTests {
// Either writer can close the direction independently. The other
// writer is still alive but the channel is now finishing.
writerA.finish()
clone.finish()
try await writerA.finish()
try await clone.finish()
nonisolated(unsafe) var collected = Set<Int>()
var done = false
@@ -389,7 +389,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Body-error wrapping
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readBodyErrorsWrappedInSecond() async throws {
struct BodyError: Error, Equatable {}
@@ -422,7 +422,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Scope cleanup
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func scopeFinalizesBothDirectionsOnReturn() async throws {
nonisolated(unsafe) var aTerminated = false
@@ -442,7 +442,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Protocol conformance
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writerConformsToCallerAsyncWriter() async throws {
// Exercise CallerAsyncWriter.finish(buffer:finalElement:) by calling
@@ -486,7 +486,7 @@ struct DuplexAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readerConformsToAsyncReader() async throws {
// Exercise AsyncReader.read through a generic function that only
@@ -12,6 +12,7 @@
#if UnstableAsyncStreaming && compiler(>=6.4)
import BasicContainers
import ContainersPreview
import SpanPreview
extension Array {
init(_ span: Span<Element>) {
@@ -28,6 +29,7 @@ extension Array {
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
init<C: RangeReplaceableContainer<Element> & ~Copyable & ~Escapable>(draining container: inout C) {
self.init()
var consumer = container.consumeAll()
@@ -14,6 +14,7 @@ import AsyncStreaming
import BasicContainers
import ContainersPreview
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayAsyncWriter: ~Copyable, AsyncWriter {
typealias WriteElement = Int
typealias Buffer = UniqueArray<Int>
@@ -14,6 +14,7 @@ import AsyncStreaming
import BasicContainers
import ContainersPreview
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayCallerAsyncReader: ~Copyable, CallerAsyncReader {
typealias ReadElement = Int
typealias ReadFailure = Never
@@ -16,6 +16,7 @@ import ContainersPreview
struct WriterCapacityError: Error {}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayCallerAsyncWriter: ~Copyable, CallerAsyncWriter {
typealias WriteElement = Int
typealias WriteFailure = Never
@@ -17,11 +17,13 @@ import ContainersPreview
import DequeModule
import Testing
private struct MultiProducerSingleConsumerAsyncChannelTestError: Error {}
@Suite(.serialized)
struct MultiProducerSingleConsumerAsyncChannelTests {
// MARK: - AsyncReader.read
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readReturnsAllBufferedElementsInOrder() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -45,7 +47,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readSuspendsUntilElementArrives() async throws {
try await withThrowingTaskGroup(of: [Int].self) { group in
@@ -73,9 +75,122 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readReturnsEmptyBufferOnEOSAfterFinish() async throws {
func readThrowsCancellationWhenTaskStartsCancelled() async {
await withTaskGroup(of: Void.self) { group in
group.cancelAll()
// A child added to an already-cancelled group starts cancelled, so the
// cancellation handler runs before the reader continuation is installed.
group.addTask {
await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
backpressureStrategy: .watermark(low: 1, high: 2)
) { channel, source in
var channel = channel
_ = consume source
do {
_ = try await channel.read { _, _ in
Issue.record("read body must not run after cancellation")
}
Issue.record("expected CancellationError")
} catch let EitherError<EitherError<Never, CancellationError>, Never>.first(.second(error)) {
_ = error
} catch {
Issue.record("unexpected error: \(error)")
}
}
}
await group.waitForAll()
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readDoesNotThrowCancellationWhenSourceFinishes() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
backpressureStrategy: .watermark(low: 1, high: 2)
) { channel, source in
var channel = channel
let source = source
source.finish()
var sawFinalElement = false
try await channel.read { buffer, finalElement in
#expect(buffer.count == 0)
sawFinalElement = finalElement != nil
}
#expect(sawFinalElement)
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readAfterCancellationPreconditions() async {
await #expect(processExitsWith: .failure) {
await withTaskGroup(of: Void.self) { group in
group.cancelAll()
group.addTask {
await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
backpressureStrategy: .watermark(low: 1, high: 2)
) { channel, source in
var channel = channel
_ = consume source
try? await channel.read { _, _ in }
try? await channel.read { _, _ in }
}
}
await group.waitForAll()
}
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readAfterFinalElementPreconditions() async {
await #expect(processExitsWith: .failure) {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
backpressureStrategy: .watermark(low: 1, high: 2)
) { channel, source in
var channel = channel
let source = source
source.finish()
try await channel.read { _, finalElement in
#expect(finalElement != nil)
}
try await channel.read { _, _ in }
}
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readAfterFailurePreconditions() async {
await #expect(processExitsWith: .failure) {
await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
throwing: MultiProducerSingleConsumerAsyncChannelTestError.self,
backpressureStrategy: .watermark(low: 1, high: 2)
) { channel, source in
var channel = channel
let source = source
source.finish(throwing: MultiProducerSingleConsumerAsyncChannelTestError())
try? await channel.read { _, _ in }
try? await channel.read { _, _ in }
}
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readReturnsEmptyBufferAndFinalElementOnEOSAfterFinish() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self,
backpressureStrategy: .watermark(low: 2, high: 4)
@@ -86,21 +201,22 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
var writeBuffer = UniqueArray<Int>(minimumCapacity: 1)
writeBuffer.append(1)
try await source.write(buffer: &writeBuffer)
source.finish()
try await channel.read { buffer, _ in
try await channel.read { buffer, finalElement in
#expect(buffer.count == 1)
#expect(finalElement == nil)
buffer.removeAll()
}
var sawEmpty = false
try await channel.read { buffer, _ in
sawEmpty = buffer.count == 0
source.finish()
try await channel.read { buffer, finalElement in
#expect(buffer.count == 0)
#expect(finalElement != nil)
}
#expect(sawEmpty)
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readThrowsFailureAfterFinishWithError() async throws {
struct TestError: Error, Equatable {}
@@ -135,7 +251,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readBodyErrorsWrappedInSecond() async throws {
struct BodyError: Error, Equatable {}
@@ -164,7 +280,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readPartialConsumptionRemainsVisibleOnNextRead() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -194,7 +310,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readResumesSuspendedProducersWhenWaterLevelDrops() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
@@ -234,7 +350,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readWaterLevelForElementCalledPerElementInBatch() async throws {
nonisolated(unsafe) var callCount = 0
@@ -267,7 +383,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readBufferIsReusedAcrossReads() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -319,7 +435,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func readDeliversFinalElementOnFinish() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -354,7 +470,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
// MARK: - CallerAsyncWriter.write
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeAppendsAllElementsAndClearsBuffer() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -382,7 +498,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeAfterFinishThrows() async throws {
await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -414,7 +530,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeSuspendsOnBackpressureAndResumesAfterRead() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
@@ -426,15 +542,12 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
var source = source
group.addTask {
// Reader drains until EOS.
// Reader drains until it observes the final element.
while true {
var done = false
try await channel.read { buffer, _ in
if buffer.count == 0 {
done = true
} else {
buffer.removeAll()
}
try await channel.read { buffer, finalElement in
buffer.removeAll()
done = finalElement != nil
}
if done { break }
}
@@ -449,7 +562,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func writeReadRoundtripPreservesOrder() async throws {
let total = 100
@@ -465,13 +578,10 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
nonisolated(unsafe) var collected: [Int] = []
var done = false
while !done {
try await channel.read { buffer, _ in
if buffer.count == 0 {
done = true
} else {
var c = buffer.consumeAll()
while let v = c.next() { collected.append(v) }
}
try await channel.read { buffer, finalElement in
var c = buffer.consumeAll()
while let v = c.next() { collected.append(v) }
done = finalElement != nil
}
}
#expect(collected == Array(0..<total))