Compare commits

...
12 Commits
Author SHA1 Message Date
Joseph CursioandClaude Opus 5.5 963eecf5ee Skip the write in DuplexAsyncChannel.Writer.finish when the buffer is empty (#476)
* Skip the write in DuplexAsyncChannel.Writer.finish when the buffer is empty

A cloned writer's finish(buffer:finalElement:) always called
write(buffer:), even with an empty buffer. Once another clone had
finished the channel, that write threw
MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError, so a
second `try await finish()` failed although it had nothing to write.
This is why clonedWriterCanProduceConcurrently has failed since #459.

Only write when the buffer has elements. A clone that still has
buffered elements after the channel finished keeps throwing.

Resolves #470.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Test finishing a cloned writer through the protocol and the adapter

clonedWriterCanProduceConcurrently only covers a direct
`try await clone.finish()`. Also cover a generic CallerAsyncWriter and
asAsyncWriter(), where there is no concrete finish() overload, after
the other writer has finished. Both threw
MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError before the
previous commit.

A third test checks that finishing a clone with elements still throws
once the channel has finished, so those elements are never dropped
silently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:46:09 +01:00
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 490 additions and 171 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\"}]]" linux_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}, {\"swift_version\": \"5.10\"}]]"
windows_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}]" windows_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}]"
enable_wasm_sdk_build: true enable_wasm_sdk_build: true
swift_flags: "--enable-all-traits"
swift_nightly_flags: "--enable-all-traits"
soundness: soundness:
name: Soundness name: Soundness
+1 -1
View File
@@ -38,7 +38,7 @@ for await (first, second) in (1...5).async.adjacentPairs() {
// First: 4, Second: 5 // 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 ```swift
Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs()) Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs())
+2 -2
View File
@@ -3,8 +3,8 @@
* Author(s): [Philippe Hausler](https://github.com/phausler) * 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/Channels/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/AsyncThrowingChannel.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChannel.swift) [Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChannel.swift)
] ]
+1 -1
View File
@@ -5,7 +5,7 @@
* Implementation: [ * Implementation: [
[By group](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift), [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), [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) [Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChunk.swift)
] ]
[ [
+1 -1
View File
@@ -5,7 +5,7 @@
* Status: **Accepted** * Status: **Accepted**
* Implementation: * 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) [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 ## 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. 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 # 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) * Authors: [Clive Liu](https://github.com/clive819) [Philippe Hausler](https://github.com/phausler)
* Review Manager: TBD * Review Manager: TBD
* Status: **Awaiting review** * Status: **Awaiting review**
## Introduction ## 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 ## Motivation
+3 -2
View File
@@ -14,7 +14,7 @@ let AsyncAlgorithms_v1_3 =
#else #else
let AsyncAlgorithms_v1_1 = "AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0" 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_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 #endif
let availabilityMacros: [SwiftSetting] = [ let availabilityMacros: [SwiftSetting] = [
@@ -145,6 +145,7 @@ let package = Package(
"AsyncStreaming", "AsyncStreaming",
.product(name: "BasicContainers", package: "swift-collections"), .product(name: "BasicContainers", package: "swift-collections"),
.product(name: "ContainersPreview", package: "swift-collections"), .product(name: "ContainersPreview", package: "swift-collections"),
.product(name: "SpanPreview", package: "swift-collections"),
], ],
swiftSettings: [ swiftSettings: [
.enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), .enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"),
@@ -165,7 +166,7 @@ if Context.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [ package.dependencies += [
.package( .package(
url: "https://github.com/apple/swift-collections.git", url: "https://github.com/apple/swift-collections.git",
from: "1.5.1", from: "1.7.0",
traits: [.trait(name: "UnstableContainersPreview", condition: .when(traits: ["UnstableAsyncStreaming"]))] 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 // 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 ```swift
Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs()) 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 ## 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. 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 return .none
case .waitingForDemand(let task, .none, let clockContinuation, .none): case .waitingForDemand(let task, .none, let clockContinuation, .none):
// We don't have any buffered element so we can just go ahead // We don't have outstanding demand to deliver the error to, so store it
// and transition to finished and cancel everything // until the downstream calls next and cancel everything.
self.state = .finished self.state = .upstreamFailure(error: error)
return .cancelTaskAndClockContinuation( return .cancelTaskAndClockContinuation(
task: task, 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. /// 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, /// of: Int.self,
/// backpressureStrategy: .watermark(low: 2, high: 4) /// backpressureStrategy: .watermark(low: 2, high: 4)
/// ) /// )
/// ///
/// // The channel and source can be extracted from the returned type /// // 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 /// let source = consume channelAndSource.source
/// ``` /// ```
/// ///
@@ -127,11 +127,11 @@ public struct MultiProducerSingleConsumerAsyncChannel<Element, Failure: Error>:
/// components from it. /// components from it.
/// ///
/// ```swift /// ```swift
/// let channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel( /// var channelAndSource = MultiProducerSingleConsumerAsyncChannel.makeChannel(
/// of: Int.self, /// of: Int.self,
/// backpressureStrategy: .watermark(low: 5, high: 10) /// backpressureStrategy: .watermark(low: 5, high: 10)
/// ) /// )
/// var channel = consume channelAndSource.channel /// var channel = channelAndSource.takeChannel()
/// var source = consume channelAndSource.source /// var source = consume channelAndSource.source
/// ``` /// ```
@frozen @frozen
@@ -25,7 +25,7 @@ public struct AsyncReaderInsufficientElementsError: Error, Hashable {
public init() {} 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 { extension AsyncReader where Self: ~Copyable, Self: ~Escapable, ReadElement: ~Copyable {
/// Collects elements from the reader into the provided container, up to the /// Collects elements from the reader into the provided container, up to the
/// container's available space. /// container's available space.
@@ -11,10 +11,10 @@
#if UnstableAsyncStreaming && compiler(>=6.4) #if UnstableAsyncStreaming && compiler(>=6.4)
public import ContainersPreview import ContainersPreview
// swift-format-ignore: AmbiguousTrailingClosureOverload // 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 { extension AsyncReader where Self: ~Copyable, Self: ~Escapable {
/// Iterates over all chunks from the reader, executing the provided body for /// Iterates over all chunks from the reader, executing the provided body for
/// each buffer until the stream signals end-of-stream. /// 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 // writer across the read closure boundary) the constraint should be added
// back so `pipe` works for `~Escapable` writers too. // 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 { extension AsyncReader where Self: ~Copyable, Self: ~Escapable, Self.ReadElement: ~Copyable {
/// Pipes all elements from this reader into the given writer, fusing the /// Pipes all elements from this reader into the given writer, fusing the
/// terminal chunk with a `finish` on the writer. /// 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 /// After the reader has emitted a non-`nil` `finalElement`, calling
/// ``read(body:)`` again is a programmer error. /// ``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 { public protocol AsyncReader<ReadElement, ReadFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this reader reads. /// The type of elements this reader reads.
// TODO: Check if we should support ~Escapable elements // 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 /// type to carry data along with the end signal, or `Never` for endless
/// streams. When ``FinalElement`` is `Never`, ``finish(finalElement:)`` cannot /// streams. When ``FinalElement`` is `Never`, ``finish(finalElement:)`` cannot
/// be called and the writer can be written to indefinitely. /// 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 { public protocol AsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this writer writes. /// The type of elements this writer writes.
// TODO: Check if we should support ~Escapable elements // TODO: Check if we should support ~Escapable elements
@@ -91,7 +91,7 @@ public protocol AsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable
) async throws(WriteFailure) ) 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 { extension AsyncWriter where Self: ~Copyable, Self: ~Escapable, FinalElement == Void {
/// Concludes the writer with no payload. /// Concludes the writer with no payload.
/// ///
@@ -24,7 +24,7 @@ public import ContainersPreview
/// from the caller-supplied buffer into the underlying writer's /// from the caller-supplied buffer into the underlying writer's
/// closure-supplied buffer. The underlying writer's deferred-flush /// closure-supplied buffer. The underlying writer's deferred-flush
/// behavior, if any, is preserved. /// 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< public struct AsyncWriterCallerAsyncWriterAdapter<
Underlying: AsyncWriter & ~Copyable Underlying: AsyncWriter & ~Copyable
>: ~Copyable, CallerAsyncWriter { >: ~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 { extension AsyncWriter where Self: ~Copyable {
/// Adapts this ``AsyncWriter`` to a ``CallerAsyncWriter``. /// Adapts this ``AsyncWriter`` to a ``CallerAsyncWriter``.
/// ///
@@ -26,7 +26,7 @@ import BasicContainers
// capturing the writer across the closure boundary) the constraint should be // capturing the writer across the closure boundary) the constraint should be
// added back so `pipe` works for `~Escapable` writers too. // 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 { extension CallerAsyncReader where Self: ~Copyable, Self: ~Escapable, Self.ReadElement: ~Copyable {
/// Pipes all elements from this reader into the given writer, then signals /// Pipes all elements from this reader into the given writer, then signals
/// end-of-stream with a `finish` call on the writer. /// 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 /// After the reader has returned a non-`nil` `FinalElement`, calling
/// ``read(into:)`` again is a programmer error. /// ``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 { public protocol CallerAsyncReader<ReadElement, ReadFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this reader reads. /// The type of elements this reader reads.
// TODO: Check if we should support ~Escapable elements // 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 /// Conformers must accept zero, one, or many `write(buffer:)` calls, optionally
/// followed by a single `finish(buffer:finalElement:)` call. After `finish` /// followed by a single `finish(buffer:finalElement:)` call. After `finish`
/// returns, the writer is consumed and no further calls are valid. /// 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 { public protocol CallerAsyncWriter<WriteElement, WriteFailure, FinalElement>: ~Copyable, ~Escapable {
/// The type of elements this writer writes. /// The type of elements this writer writes.
// TODO: Check if we should support ~Escapable elements // 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 ) 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 { extension CallerAsyncWriter where Self: ~Copyable, Self: ~Escapable, FinalElement == Void {
/// Concludes the writer with no final buffer and no extra payload. /// 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 /// ``CallerAsyncWriter/finish(buffer:finalElement:)`` always receives an
/// empty buffer. Conformers that need fused close should implement /// empty buffer. Conformers that need fused close should implement
/// ``AsyncWriter`` directly rather than going through this adapter. /// ``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< public struct CallerAsyncWriterAsyncWriterAdapter<
Underlying: CallerAsyncWriter & ~Copyable, Underlying: CallerAsyncWriter & ~Copyable,
Buffer: DynamicContainer<Underlying.WriteElement> & ~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 { extension CallerAsyncWriter where Self: ~Copyable {
/// Adapts this ``CallerAsyncWriter`` to an ``AsyncWriter``, using /// Adapts this ``CallerAsyncWriter`` to an ``AsyncWriter``, using
/// ``UniqueArray`` as the buffer container. /// ``UniqueArray`` as the buffer container.
@@ -47,7 +47,7 @@ public import ContainersPreview
/// Each direction's writer terminates its half of the channel /// Each direction's writer terminates its half of the channel
/// independently by calling ``Writer/finish(finalElement:)`` or /// independently by calling ``Writer/finish(finalElement:)`` or
/// ``Writer/finish(throwing:)``. /// ``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< public struct DuplexAsyncChannel<
Element: Sendable, Element: Sendable,
FinalElement: 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 { extension DuplexAsyncChannel where FinalElement == Void {
/// Creates a new duplex channel with a `Void` end-of-stream payload and /// Creates a new duplex channel with a `Void` end-of-stream payload and
/// runs `body` with all four handles. /// runs `body` with all four handles.
@@ -164,7 +164,7 @@ extension DuplexAsyncChannel where FinalElement == Void {
// MARK: - Backpressure strategy // 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 { extension DuplexAsyncChannel {
/// A backpressure strategy applied independently to each direction of /// A backpressure strategy applied independently to each direction of
/// the duplex. /// the duplex.
@@ -228,7 +228,7 @@ extension DuplexAsyncChannel {
// MARK: - Writer // 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 { extension DuplexAsyncChannel {
/// The writer half of one side of a ``DuplexAsyncChannel``. /// The writer half of one side of a ``DuplexAsyncChannel``.
/// ///
@@ -386,13 +386,15 @@ extension DuplexAsyncChannel {
buffer: inout Buffer, buffer: inout Buffer,
finalElement: consuming FinalElement finalElement: consuming FinalElement
) async throws { ) async throws {
try await self.write(buffer: &buffer) if !buffer.isEmpty {
try await self.write(buffer: &buffer)
}
self._storage.finish(throwing: nil, finalElement: finalElement) self._storage.finish(throwing: nil, finalElement: finalElement)
} }
} }
} }
@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 { extension DuplexAsyncChannel.Writer where FinalElement == Void {
/// Finishes this direction with an empty `Void` end-of-stream payload. /// Finishes this direction with an empty `Void` end-of-stream payload.
/// ///
@@ -407,7 +409,7 @@ extension DuplexAsyncChannel.Writer where FinalElement == Void {
// MARK: - Reader // 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 { extension DuplexAsyncChannel {
/// The reader half of one side of a ``DuplexAsyncChannel``. /// The reader half of one side of a ``DuplexAsyncChannel``.
/// ///
@@ -446,8 +448,9 @@ extension DuplexAsyncChannel {
/// in `read`) — and whose outer `.second` arm carries the failure /// in `read`) — and whose outer `.second` arm carries the failure
/// thrown by `body`. /// thrown by `body`.
/// ///
/// - Important: After the reader observes a non-`nil` `finalElement`, /// - Important: After the reader observes a non-`nil` `finalElement` or
/// calling `read(body:)` again is a programmer error. /// `read(body:)` throws a read-side error, calling `read(body:)` again is
/// a programmer error.
@inlinable @inlinable
public mutating func read<Return: ~Copyable, BodyFailure: Error>( public mutating func read<Return: ~Copyable, BodyFailure: Error>(
body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return
@@ -513,13 +516,8 @@ extension DuplexAsyncChannel {
throw .second(error) throw .second(error)
} }
case .returnNil: case .throwCancellation:
var empty = UniqueDeque<Element>() throw .first(.second(CancellationError()))
do throws(BodyFailure) {
return try await body(&empty, nil)
} catch {
throw .second(error)
}
case .suspend: case .suspend:
do { do {
@@ -14,7 +14,7 @@ public import DequeModule
public import Synchronization public import Synchronization
public import ContainersPreview 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 { extension MultiProducerSingleConsumerAsyncChannel {
@usableFromInline @usableFromInline
enum _InternalBackpressureStrategy: Sendable, CustomStringConvertible { 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 { extension MultiProducerSingleConsumerAsyncChannel {
@usableFromInline @usableFromInline
final class _Storage: Sendable { final class _Storage: Sendable {
@@ -272,6 +272,8 @@ extension MultiProducerSingleConsumerAsyncChannel {
switch consume action { switch consume action {
case .resumeReader(let c): case .resumeReader(let c):
c.resume() c.resume()
case .resumeReaderWithCancellationError(let c):
c.resume(throwing: .second(CancellationError()))
case .none: case .none:
break 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 { extension MultiProducerSingleConsumerAsyncChannel._Storage {
@usableFromInline @usableFromInline
struct _StateMachine: ~Copyable, Sendable { struct _StateMachine: ~Copyable, Sendable {
@@ -410,12 +412,12 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
case .channeling(let s): case .channeling(let s):
let producers = Array(s.suspendedProducers.lazy.map { $0.1 }) let producers = Array(s.suspendedProducers.lazy.map { $0.1 })
let onTerminations = s.onTerminations let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: false))) self = .init(state: .finished(.consumed))
return .failProducersAndCallOnTerminations(producers, onTerminations) return .failProducersAndCallOnTerminations(producers, onTerminations)
case .sourceFinished(let s): case .sourceFinished(let s):
let onTerminations = s.onTerminations let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: true))) self = .init(state: .finished(.consumed))
return .callOnTerminations(onTerminations) return .callOnTerminations(onTerminations)
case .finished(let s): case .finished(let s):
@@ -679,16 +681,16 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
/// The channel was finished with a failure and the buffer is now drained; /// The channel was finished with a failure and the buffer is now drained;
/// throw the failure to the reader. /// throw the failure to the reader.
case throwFailure(Failure?, [(UInt64, @Sendable () -> Void)]) case throwFailure(Failure?, [(UInt64, @Sendable () -> Void)])
case returnNil /// Cancellation finished the channel before it could be delivered to the reader.
case throwCancellation
} }
@inlinable @inlinable
mutating func readAvailable() -> ReadAvailableAction { mutating func readAvailable() -> ReadAvailableAction {
switch consume self._state { switch consume self._state {
case .channeling(var s): case .channeling(var s):
let isProducerBufferEmpty = s.buffer.withValue { // Optional chaining borrows the deque; unwrap only the Boolean result.
$0.borrow()!.value.isEmpty let isProducerBufferEmpty = s.buffer.withValue { $0?.isEmpty }!
}
guard isProducerBufferEmpty else { guard isProducerBufferEmpty else {
// We are going to swap the two buffers around. The cached buffer // 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 // 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 fe = s.finalElement.swap(newValue: nil)
let onTerminations = s.onTerminations let onTerminations = s.onTerminations
let failure = s.failure let failure = s.failure
self = .init(state: .finished(.init(sourceFinished: true))) self = .init(state: .finished(.consumed))
if let failure { if let failure {
return .throwFailure(failure, onTerminations) return .throwFailure(failure, onTerminations)
@@ -745,8 +747,14 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
) )
case .finished(let s): case .finished(let s):
self = .init(state: .finished(s)) switch s {
return .returnNil 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 @usableFromInline
enum SuspendReadAction: ~Copyable, Sendable { enum SuspendReadAction: ~Copyable, Sendable {
case resumeReader(UnsafeContinuation<Void, EitherError<Failure, CancellationError>>) case resumeReader(UnsafeContinuation<Void, EitherError<Failure, CancellationError>>)
case resumeReaderWithCancellationError(
UnsafeContinuation<Void, EitherError<Failure, CancellationError>>
)
} }
@inlinable @inlinable
@@ -811,7 +822,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
guard s.readerContinuation == nil else { guard s.readerContinuation == nil else {
fatalError("MultiProducerSingleConsumerAsyncChannel internal inconsistency: concurrent readers") fatalError("MultiProducerSingleConsumerAsyncChannel internal inconsistency: concurrent readers")
} }
let isEmpty = s.buffer.withValue { $0.borrow()!.value.isEmpty } let isEmpty = s.buffer.withValue { $0?.isEmpty }!
if !isEmpty { if !isEmpty {
self = .init(state: .channeling(s)) self = .init(state: .channeling(s))
return .resumeReader(continuation) return .resumeReader(continuation)
@@ -825,8 +836,16 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage {
return .resumeReader(continuation) return .resumeReader(continuation)
case .finished(let s): case .finished(let s):
self = .init(state: .finished(s)) switch s {
return .resumeReader(continuation) 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 reader = s.readerContinuation.take()
let producers = Array(s.suspendedProducers.lazy.map { $0.1 }) let producers = Array(s.suspendedProducers.lazy.map { $0.1 })
let onTerminations = s.onTerminations let onTerminations = s.onTerminations
self = .init(state: .finished(.init(sourceFinished: false)))
if let reader { if let reader {
self = .init(state: .finished(.consumed))
return .resumeReaderWithCancellationError(reader, producers, onTerminations) return .resumeReaderWithCancellationError(reader, producers, onTerminations)
} }
self = .init(state: .finished(.cancelled))
return .failProducersAndCallOnTerminations(producers, onTerminations) return .failProducersAndCallOnTerminations(producers, onTerminations)
case .sourceFinished(let s): 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 { extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
@usableFromInline @usableFromInline
enum _State: ~Copyable, Sendable { enum _State: ~Copyable, Sendable {
@@ -980,12 +1000,9 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
} }
@usableFromInline @usableFromInline
struct Finished: ~Copyable, Sendable { enum Finished: Sendable {
@usableFromInline case cancelled
var sourceFinished: Bool case consumed
@inlinable
init(sourceFinished: Bool) { self.sourceFinished = sourceFinished }
} }
case channeling(Channeling) case channeling(Channeling)
@@ -995,7 +1012,7 @@ extension MultiProducerSingleConsumerAsyncChannel._Storage._StateMachine {
} }
/// A producer suspended waiting for backpressure to allow further sends. /// 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 @usableFromInline
enum _MultiProducerSingleConsumerSuspendedProducer: @unchecked Sendable { enum _MultiProducerSingleConsumerSuspendedProducer: @unchecked Sendable {
case closure((Result<Void, any Error>) -> Void) 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 /// Helper to move a non-Sendable value across isolation regions (mirror of
/// the helper in AsyncAlgorithms; kept private to AsyncStreaming to avoid /// the helper in AsyncAlgorithms; kept private to AsyncStreaming to avoid
/// reaching into another module's internals). /// 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 @usableFromInline
struct _Disconnected<Value: ~Copyable>: ~Copyable, Sendable { struct _Disconnected<Value: ~Copyable>: ~Copyable, Sendable {
private nonisolated(unsafe) var value: Value private nonisolated(unsafe) var value: Value
@@ -32,7 +32,7 @@ public import ContainersPreview
/// end-of-stream signal. A producer terminates the channel by calling /// end-of-stream signal. A producer terminates the channel by calling
/// either ``Source/finish(finalElement:)`` to signal end-of-stream /// either ``Source/finish(finalElement:)`` to signal end-of-stream
/// or ``Source/finish(throwing:)`` to terminate with a failure. /// 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< public struct MultiProducerSingleConsumerAsyncChannel<
Element, Element,
FinalElement, 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 { extension MultiProducerSingleConsumerAsyncChannel where FinalElement == Void {
/// Creates a new channel with a `Void` end-of-stream payload and runs /// Creates a new channel with a `Void` end-of-stream payload and runs
/// `body` with the channel and its initial source. /// `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 { extension MultiProducerSingleConsumerAsyncChannel {
/// A handle for sending elements to the channel. /// A handle for sending elements to the channel.
public struct Source: ~Copyable, Sendable { 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 { extension MultiProducerSingleConsumerAsyncChannel.Source where FinalElement == Void {
/// Finishes the channel with an empty `Void` end-of-stream payload. /// Finishes the channel with an empty `Void` end-of-stream payload.
/// ///
@@ -304,7 +304,7 @@ extension MultiProducerSingleConsumerAsyncChannel.Source where FinalElement == V
// MARK: - Reading // 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 { extension MultiProducerSingleConsumerAsyncChannel {
/// Reads the next chunk of elements from the channel. /// 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 /// the task is canceled while suspended in `read`) — and whose outer
/// `.second` arm carries the failure thrown by `body`. /// `.second` arm carries the failure thrown by `body`.
/// ///
/// - Important: After the reader observes a non-`nil` `finalElement`, /// - Important: After the reader observes a non-`nil` `finalElement` or
/// calling `read(body:)` again is a programmer error. /// `read(body:)` throws a read-side error, calling `read(body:)` again is
/// a programmer error.
@inlinable @inlinable
public mutating func read<Return: ~Copyable, BodyFailure: Error>( public mutating func read<Return: ~Copyable, BodyFailure: Error>(
body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return body: (inout UniqueDeque<Element>, consuming FinalElement?) async throws(BodyFailure) -> Return
@@ -391,13 +392,8 @@ extension MultiProducerSingleConsumerAsyncChannel {
throw .second(error) throw .second(error)
} }
case .returnNil: case .throwCancellation:
var empty = UniqueDeque<Element>() throw .first(.second(CancellationError()))
do throws(BodyFailure) {
return try await body(&empty, nil)
} catch {
throw .second(error)
}
case .suspend: case .suspend:
do { do {
@@ -413,7 +409,7 @@ extension MultiProducerSingleConsumerAsyncChannel {
/// An error that ``MultiProducerSingleConsumerAsyncChannel/Source/write(buffer:)`` /// An error that ``MultiProducerSingleConsumerAsyncChannel/Source/write(buffer:)``
/// throws when its source has already finished. /// 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 { public struct MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError: Error {
@usableFromInline @usableFromInline
init() {} init() {}
@@ -12,6 +12,10 @@
import XCTest import XCTest
import AsyncAlgorithms import AsyncAlgorithms
private struct DebounceTestError: Error, Equatable, Sendable {
let value: Int
}
final class TestDebounce: XCTestCase { final class TestDebounce: XCTestCase {
#if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread) #if canImport(Darwin) || canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
func test_delayingValues() throws { 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 { func test_noValues() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability") throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
@@ -18,6 +18,7 @@ import Testing
@Suite @Suite
struct AsyncReaderCollectIntoTests { struct AsyncReaderCollectIntoTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectFillsTargetWhenReaderHasFewerElements() async throws { func collectFillsTargetWhenReaderHasFewerElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -31,6 +32,7 @@ struct AsyncReaderCollectIntoTests {
#expect(collected == [1, 2, 3]) #expect(collected == [1, 2, 3])
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectFillsTargetWhenReaderHasExactlyFreeCapacityElements() async throws { func collectFillsTargetWhenReaderHasExactlyFreeCapacityElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -41,6 +43,7 @@ struct AsyncReaderCollectIntoTests {
#expect(target.count == 3) #expect(target.count == 3)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectThrowsWhenReaderProducesMoreThanFreeCapacity() async throws { func collectThrowsWhenReaderProducesMoreThanFreeCapacity() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5])) 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 @Test
func collectIntoEmptyReader() async throws { func collectIntoEmptyReader() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: [])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -68,6 +72,7 @@ struct AsyncReaderCollectIntoTests {
@Suite @Suite
struct AsyncReaderCollectExactlyTests { struct AsyncReaderCollectExactlyTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectExactlyFillsTargetWhenReaderProducesExactCount() async throws { func collectExactlyFillsTargetWhenReaderProducesExactCount() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -81,6 +86,7 @@ struct AsyncReaderCollectExactlyTests {
#expect(collected == [1, 2, 3]) #expect(collected == [1, 2, 3])
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectExactlyThrowsWhenReaderProducesFewer() async throws { func collectExactlyThrowsWhenReaderProducesFewer() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) 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 @Test
func collectExactlyThrowsWhenReaderProducesMore() async throws { func collectExactlyThrowsWhenReaderProducesMore() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -118,6 +125,7 @@ struct AsyncReaderCollectExactlyTests {
@Suite @Suite
struct AsyncReaderCollectIntoMaximumSizeTests { struct AsyncReaderCollectIntoMaximumSizeTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectGrowsContainerWhenReaderHasFewerThanMaximum() async throws { func collectGrowsContainerWhenReaderHasFewerThanMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -131,6 +139,7 @@ struct AsyncReaderCollectIntoMaximumSizeTests {
#expect(collected == [1, 2, 3]) #expect(collected == [1, 2, 3])
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectFillsContainerExactlyAtMaximum() async throws { func collectFillsContainerExactlyAtMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30]))
@@ -141,6 +150,7 @@ struct AsyncReaderCollectIntoMaximumSizeTests {
#expect(target.count == 3) #expect(target.count == 3)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func collectThrowsWhenReaderProducesMoreThanMaximum() async throws { func collectThrowsWhenReaderProducesMoreThanMaximum() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5])) 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 @Test
func collectAppendsToExistingContents() async throws { func collectAppendsToExistingContents() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 2, copying: [3, 4])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 2, copying: [3, 4]))
@@ -18,6 +18,7 @@ import Testing
@Suite @Suite
struct AsyncReaderforEachBufferTests { struct AsyncReaderforEachBufferTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferIteratesAllSpans() async throws { func forEachBufferIteratesAllSpans() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 5, copying: [1, 2, 3, 4, 5]))
@@ -30,6 +31,7 @@ struct AsyncReaderforEachBufferTests {
#expect(elementCount == 5) #expect(elementCount == 5)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferProcessesElements() async throws { func forEachBufferProcessesElements() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [10, 20, 30]))
@@ -44,6 +46,7 @@ struct AsyncReaderforEachBufferTests {
#expect(sum == 60) #expect(sum == 60)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferWithEmptyReader() async throws { func forEachBufferWithEmptyReader() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: [])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -57,6 +60,7 @@ struct AsyncReaderforEachBufferTests {
#expect(callCount == 0) #expect(callCount == 0)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws { func forEachBufferDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: [])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 0, copying: []))
@@ -69,6 +73,7 @@ struct AsyncReaderforEachBufferTests {
#expect(observedCounts.allSatisfy { $0 > 0 }) #expect(observedCounts.allSatisfy { $0 > 0 })
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferThrowingDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws { func forEachBufferThrowingDoesNotInvokeBodyWithEmptyTerminalBuffer() async throws {
enum TestError: Error {} enum TestError: Error {}
@@ -83,6 +88,7 @@ struct AsyncReaderforEachBufferTests {
#expect(observedCounts.allSatisfy { $0 > 0 }) #expect(observedCounts.allSatisfy { $0 > 0 })
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferWithThrowingBody() async { func forEachBufferWithThrowingBody() async {
enum TestError: Error { 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 @Test
func forEachBufferWithNeverFailingReader() async { func forEachBufferWithNeverFailingReader() async {
enum TestError: Error { enum TestError: Error {
@@ -121,6 +128,7 @@ struct AsyncReaderforEachBufferTests {
#expect(count == 3) #expect(count == 3)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func forEachBufferWithAsyncWork() async throws { func forEachBufferWithAsyncWork() async throws {
let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3])) let reader = UniqueArrayAsyncReader(storage: UniqueArray(capacity: 3, copying: [1, 2, 3]))
@@ -19,7 +19,7 @@ import Testing
struct AsyncReaderPipeTests { struct AsyncReaderPipeTests {
// MARK: - pipe(into:) — into a CallerAsyncWriter // 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 @Test
func pipeIntoCopiesAllElements() async throws { func pipeIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -33,7 +33,7 @@ struct AsyncReaderPipeTests {
var array = UniqueArray(copying: [1, 2, 3, 4, 5]) var array = UniqueArray(copying: [1, 2, 3, 4, 5])
try await writerA.write(buffer: &array) try await writerA.write(buffer: &array)
writerA.finish() try await writerA.finish()
try await readerB.pipe(into: writerB) try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 5) 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 @Test
func pipeIntoWithEmptyReader() async throws { func pipeIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -54,7 +54,7 @@ struct AsyncReaderPipeTests {
let writerB = writerB let writerB = writerB
let readerB = readerB let readerB = readerB
writerA.finish() try await writerA.finish()
try await readerB.pipe(into: writerB) try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 5) 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 @Test
func pipeIntoPreservesElementOrder() async throws { func pipeIntoPreservesElementOrder() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -78,7 +78,7 @@ struct AsyncReaderPipeTests {
let elements = Array(1...50) let elements = Array(1...50)
var array = UniqueArray(copying: elements) var array = UniqueArray(copying: elements)
try await writerA.write(buffer: &array) try await writerA.write(buffer: &array)
writerA.finish() try await writerA.finish()
try await readerB.pipe(into: writerB) try await readerB.pipe(into: writerB)
var target = RigidArray<Int>(capacity: 50) var target = RigidArray<Int>(capacity: 50)
@@ -89,7 +89,7 @@ struct AsyncReaderPipeTests {
// MARK: - pipe(copyingInto:) — into an AsyncWriter via the adapter // 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 @Test
func pipeCopyingIntoCopiesAllElements() async throws { func pipeCopyingIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -103,7 +103,7 @@ struct AsyncReaderPipeTests {
var array = UniqueArray(copying: [1, 2, 3, 4, 5]) var array = UniqueArray(copying: [1, 2, 3, 4, 5])
try await writerA.write(buffer: &array) try await writerA.write(buffer: &array)
writerA.finish() try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter()) try await readerB.pipe(copyingInto: writerB.asAsyncWriter())
var target = RigidArray<Int>(capacity: 5) 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 @Test
func pipeCopyingIntoWithEmptyReader() async throws { func pipeCopyingIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -124,7 +124,7 @@ struct AsyncReaderPipeTests {
let writerB = writerB let writerB = writerB
let readerB = readerB let readerB = readerB
writerA.finish() try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter()) try await readerB.pipe(copyingInto: writerB.asAsyncWriter())
var target = RigidArray<Int>(capacity: 5) 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 @Test
func pipeCopyingIntoChunksTerminalChunkAcrossMultipleWrites() async throws { func pipeCopyingIntoChunksTerminalChunkAcrossMultipleWrites() async throws {
// 200 elements through a small (16-element) AsyncWriter buffer // 200 elements through a small (16-element) AsyncWriter buffer
@@ -150,7 +150,7 @@ struct AsyncReaderPipeTests {
let elements = Array(1...200) let elements = Array(1...200)
var array = UniqueArray(copying: elements) var array = UniqueArray(copying: elements)
try await writerA.write(buffer: &array) try await writerA.write(buffer: &array)
writerA.finish() try await writerA.finish()
try await readerB.pipe(copyingInto: writerB.asAsyncWriter(initialCapacity: 16)) try await readerB.pipe(copyingInto: writerB.asAsyncWriter(initialCapacity: 16))
var target = RigidArray<Int>(capacity: 200) var target = RigidArray<Int>(capacity: 200)
@@ -23,7 +23,7 @@ struct AsyncWriterCallerAsyncWriterAdapterTests {
// asAsyncWriter() to get an AsyncWriter, then wrap THAT via // asAsyncWriter() to get an AsyncWriter, then wrap THAT via
// asCallerAsyncWriter() to exercise this adapter end-to-end. // 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 @Test
func writeAndFinishRoundTrip() async throws { func writeAndFinishRoundTrip() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func writeLoopsAcrossMultipleUnderlyingBuffers() async throws { func writeLoopsAcrossMultipleUnderlyingBuffers() async throws {
// The CallerAsyncWriterAsyncWriterAdapter underneath uses a // 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 @Test
func finishWithoutWriteDeliversEmptyTerminator() async throws { func finishWithoutWriteDeliversEmptyTerminator() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func finishDeliversTrailingBufferAndPayload() async throws { func finishDeliversTrailingBufferAndPayload() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -17,6 +17,7 @@ import Testing
@Suite @Suite
struct AsyncWriterTests { struct AsyncWriterTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeElements() async { func writeElements() async {
var writer = UniqueArrayAsyncWriter() var writer = UniqueArrayAsyncWriter()
@@ -33,6 +34,7 @@ struct AsyncWriterTests {
#expect(writer.storage[2] == 3) #expect(writer.storage[2] == 3)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeEmptyBuffer() async { func writeEmptyBuffer() async {
var writer = UniqueArrayAsyncWriter() var writer = UniqueArrayAsyncWriter()
@@ -42,6 +44,7 @@ struct AsyncWriterTests {
#expect(writer.storage.count == 0) #expect(writer.storage.count == 0)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeReturnsValue() async { func writeReturnsValue() async {
var writer = UniqueArrayAsyncWriter() var writer = UniqueArrayAsyncWriter()
@@ -56,6 +59,7 @@ struct AsyncWriterTests {
#expect(writer.storage.count == 2) #expect(writer.storage.count == 2)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeWithThrowingBody() async { func writeWithThrowingBody() async {
enum TestError: Error, Equatable { 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 @Test
func writeMultipleTimes() async { func writeMultipleTimes() async {
var writer = UniqueArrayAsyncWriter() var writer = UniqueArrayAsyncWriter()
@@ -95,12 +100,14 @@ struct AsyncWriterTests {
#expect(writer.storage[3] == 4) #expect(writer.storage[3] == 4)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func finishVoidConvenience() async { func finishVoidConvenience() async {
let writer = UniqueArrayAsyncWriter() let writer = UniqueArrayAsyncWriter()
await writer.finish() await writer.finish()
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func finishDeliversFinalElement() async { func finishDeliversFinalElement() async {
let writer = UniqueArrayAsyncWriter() let writer = UniqueArrayAsyncWriter()
@@ -19,7 +19,7 @@ import Testing
struct CallerAsyncReaderPipeTests { struct CallerAsyncReaderPipeTests {
// MARK: - pipe(into:) — into an AsyncWriter via the adapter // 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 @Test
func pipeIntoCopiesAllElements() async throws { func pipeIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func pipeIntoWithEmptyReader() async throws { func pipeIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func pipeIntoLoopsAcrossMultipleBuffers() async throws { func pipeIntoLoopsAcrossMultipleBuffers() async throws {
// 200 elements through a small AsyncWriter buffer forces the pipe // 200 elements through a small AsyncWriter buffer forces the pipe
@@ -85,7 +85,7 @@ struct CallerAsyncReaderPipeTests {
// MARK: - pipe(bufferingInto:) — into a CallerAsyncWriter // 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 @Test
func pipeBufferingIntoCopiesAllElements() async throws { func pipeBufferingIntoCopiesAllElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func pipeBufferingIntoWithEmptyReader() async throws { func pipeBufferingIntoWithEmptyReader() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func pipeBufferingIntoReusesIntermediateBufferAcrossMultipleIterations() async throws { func pipeBufferingIntoReusesIntermediateBufferAcrossMultipleIterations() async throws {
// 100 elements through a 16-element intermediate buffer forces the // 100 elements through a 16-element intermediate buffer forces the
@@ -17,6 +17,7 @@ import Testing
@Suite @Suite
struct CallerAsyncReaderTests { struct CallerAsyncReaderTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func readIntoBuffer() async { func readIntoBuffer() async {
var reader = UniqueArrayCallerAsyncReader( var reader = UniqueArrayCallerAsyncReader(
@@ -34,6 +35,7 @@ struct CallerAsyncReaderTests {
#expect(buffer[4] == 5) #expect(buffer[4] == 5)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func readIntoBufferAtEnd() async { func readIntoBufferAtEnd() async {
var reader = UniqueArrayCallerAsyncReader( var reader = UniqueArrayCallerAsyncReader(
@@ -46,6 +48,7 @@ struct CallerAsyncReaderTests {
#expect(buffer.count == 0) #expect(buffer.count == 0)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func readIntoBufferRespectsCapacity() async { func readIntoBufferRespectsCapacity() async {
var reader = UniqueArrayCallerAsyncReader( var reader = UniqueArrayCallerAsyncReader(
@@ -61,6 +64,7 @@ struct CallerAsyncReaderTests {
#expect(buffer[2] == 3) #expect(buffer[2] == 3)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func readMultipleTimes() async { func readMultipleTimes() async {
var reader = UniqueArrayCallerAsyncReader( var reader = UniqueArrayCallerAsyncReader(
@@ -21,7 +21,7 @@ struct CallerAsyncWriterAsyncWriterAdapterTests {
// we drive it through the duplex's CallerAsyncWriter side and verify // we drive it through the duplex's CallerAsyncWriter side and verify
// the elements arrive on the peer reader. // 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 @Test
func writeAndFinishRoundTrip() async throws { func writeAndFinishRoundTrip() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func multipleWritesAreFlushedEagerly() async throws { func multipleWritesAreFlushedEagerly() async throws {
// The adapter must NOT defer the most recent write — each write call // 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 @Test
func finishWithoutWriteDeliversEmptyTerminator() async throws { func finishWithoutWriteDeliversEmptyTerminator() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func customBufferTypePreservesElements() async throws { func customBufferTypePreservesElements() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -17,6 +17,7 @@ import Testing
@Suite @Suite
struct CallerAsyncWriterTests { struct CallerAsyncWriterTests {
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeBuffer() async { func writeBuffer() async {
var writer = UniqueArrayCallerAsyncWriter() var writer = UniqueArrayCallerAsyncWriter()
@@ -27,6 +28,7 @@ struct CallerAsyncWriterTests {
#expect(writer.storage.count == 5) #expect(writer.storage.count == 5)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeEmptyBuffer() async { func writeEmptyBuffer() async {
var writer = UniqueArrayCallerAsyncWriter() var writer = UniqueArrayCallerAsyncWriter()
@@ -37,6 +39,7 @@ struct CallerAsyncWriterTests {
#expect(writer.storage.count == 0) #expect(writer.storage.count == 0)
} }
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test @Test
func writeLargeBuffer() async { func writeLargeBuffer() async {
var writer = UniqueArrayCallerAsyncWriter(capacity: 100) var writer = UniqueArrayCallerAsyncWriter(capacity: 100)
@@ -21,7 +21,7 @@ import Testing
struct DuplexAsyncChannelTests { struct DuplexAsyncChannelTests {
// MARK: - Round-trip // 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 @Test
func roundTripForwardDirection() async throws { func roundTripForwardDirection() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func roundTripReverseDirection() async throws { func roundTripReverseDirection() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( 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 @Test
func directionsAreIndependent() async throws { func directionsAreIndependent() async throws {
// Bytes sent on the forward direction must NOT appear on the side that // 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 @Test
func concurrentReadsOnBothDirections() async throws { func concurrentReadsOnBothDirections() async throws {
try await withThrowingTaskGroup(of: [Int].self) { group in try await withThrowingTaskGroup(of: [Int].self) { group in
@@ -137,13 +137,13 @@ struct DuplexAsyncChannelTests {
var fwd = UniqueArray<Int>(minimumCapacity: 10) var fwd = UniqueArray<Int>(minimumCapacity: 10)
for i in 0..<10 { fwd.append(i) } for i in 0..<10 { fwd.append(i) }
try await writerA.write(buffer: &fwd) try await writerA.write(buffer: &fwd)
writerA.finish() try await writerA.finish()
// Reverse: write 100..<110 from main scope. // Reverse: write 100..<110 from main scope.
var rev = UniqueArray<Int>(minimumCapacity: 10) var rev = UniqueArray<Int>(minimumCapacity: 10)
for i in 100..<110 { rev.append(i) } for i in 100..<110 { rev.append(i) }
try await writerB.write(buffer: &rev) try await writerB.write(buffer: &rev)
writerB.finish() try await writerB.finish()
// Drain forward from the main scope. // Drain forward from the main scope.
var forwardCollected: [Int] = [] var forwardCollected: [Int] = []
@@ -165,7 +165,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Half-close // 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 @Test
func finishingOneDirectionLeavesTheOtherOpen() async throws { func finishingOneDirectionLeavesTheOtherOpen() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex( try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
@@ -181,7 +181,7 @@ struct DuplexAsyncChannelTests {
var fwdBuf = UniqueArray<Int>(minimumCapacity: 1) var fwdBuf = UniqueArray<Int>(minimumCapacity: 1)
fwdBuf.append(7) fwdBuf.append(7)
try await writerA.write(buffer: &fwdBuf) try await writerA.write(buffer: &fwdBuf)
writerA.finish() try await writerA.finish()
// Reverse direction still works. // Reverse direction still works.
var revBuf = UniqueArray<Int>(minimumCapacity: 1) var revBuf = UniqueArray<Int>(minimumCapacity: 1)
@@ -208,7 +208,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Final element // 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 @Test
func finalElementDeliveredOnFinish() async throws { func finalElementDeliveredOnFinish() async throws {
try await DuplexAsyncChannel<Int, String, Never>.withDuplex( try await DuplexAsyncChannel<Int, String, Never>.withDuplex(
@@ -244,7 +244,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Failure isolation // 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 @Test
func failureOnOneDirectionDoesNotPoisonTheOther() async throws { func failureOnOneDirectionDoesNotPoisonTheOther() async throws {
struct TestError: Error, Equatable {} struct TestError: Error, Equatable {}
@@ -254,7 +254,7 @@ struct DuplexAsyncChannelTests {
throwing: TestError.self, throwing: TestError.self,
backpressureStrategy: .watermark(low: 2, high: 4) backpressureStrategy: .watermark(low: 2, high: 4)
) { writerA, readerA, writerB, readerB in ) { writerA, readerA, writerB, readerB in
var writerA = writerA let writerA = writerA
var readerA = readerA var readerA = readerA
var writerB = writerB var writerB = writerB
var readerB = readerB var readerB = readerB
@@ -263,7 +263,7 @@ struct DuplexAsyncChannelTests {
var revBuf = UniqueArray<Int>(minimumCapacity: 1) var revBuf = UniqueArray<Int>(minimumCapacity: 1)
revBuf.append(42) revBuf.append(42)
try await writerB.write(buffer: &revBuf) try await writerB.write(buffer: &revBuf)
writerB.finish() try await writerB.finish()
// Fail forward direction. // Fail forward direction.
writerA.finish(throwing: TestError()) writerA.finish(throwing: TestError())
@@ -293,7 +293,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Backpressure isolation // 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 @Test
func backpressureOnOneDirectionDoesNotBlockTheOther() async throws { func backpressureOnOneDirectionDoesNotBlockTheOther() async throws {
// Forward writer is suspended on backpressure (writes more than the // Forward writer is suspended on backpressure (writes more than the
@@ -343,7 +343,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Multi-producer per direction // 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 @Test
func clonedWriterCanProduceConcurrently() async throws { func clonedWriterCanProduceConcurrently() async throws {
// Two writes happen sequentially through the original writer and its // 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 // Either writer can close the direction independently. The other
// writer is still alive but the channel is now finishing. // writer is still alive but the channel is now finishing.
writerA.finish() try await writerA.finish()
clone.finish() try await clone.finish()
nonisolated(unsafe) var collected = Set<Int>() nonisolated(unsafe) var collected = Set<Int>()
var done = false var done = false
@@ -387,9 +387,96 @@ struct DuplexAsyncChannelTests {
} }
} }
/// Finishes `writer` through the `CallerAsyncWriter` protocol, where there is
/// no concrete `finish()` overload to pick instead.
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
private static func finishThroughProtocol<Writer: CallerAsyncWriter & ~Copyable>(
_ writer: consuming Writer
) async throws(Writer.WriteFailure) where Writer.FinalElement == Void {
try await writer.finish()
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func cloneFinishesThroughGenericCallerAsyncWriterAfterOtherWriterFinished() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
of: Int.self,
backpressureStrategy: .watermark(low: 5, high: 50)
) { writerA, readerA, writerB, readerB in
var writerA = writerA
var readerB = readerB
_ = readerA
_ = writerB
let clone = writerA.clone()
var buffer = UniqueArray<Int>(minimumCapacity: 3)
for value in 0..<3 { buffer.append(value) }
try await writerA.write(buffer: &buffer)
try await writerA.finish()
try await Self.finishThroughProtocol(clone)
var collected: [Int] = []
var done = false
while !done {
try await readerB.read { buffer, finalElement in
var consumer = buffer.consumeAll()
while let value = consumer.next() { collected.append(value) }
if finalElement != nil { done = true }
}
}
#expect(collected == [0, 1, 2])
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func cloneFinishesThroughAsyncWriterAdapterAfterOtherWriterFinished() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
of: Int.self,
backpressureStrategy: .watermark(low: 5, high: 50)
) { writerA, readerA, writerB, readerB in
var writerA = writerA
_ = readerA
_ = writerB
_ = readerB
let clone = writerA.clone()
try await writerA.finish()
try await clone.asAsyncWriter().finish()
}
}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
@Test
func cloneFinishWithElementsAfterOtherWriterFinishedStillThrows() async throws {
try await DuplexAsyncChannel<Int, Void, Never>.withDuplex(
of: Int.self,
backpressureStrategy: .watermark(low: 5, high: 50)
) { writerA, readerA, writerB, readerB in
var writerA = writerA
_ = readerA
_ = writerB
_ = readerB
let clone = writerA.clone()
try await writerA.finish()
// Elements that can no longer be delivered must not be dropped silently.
var buffer = UniqueArray<Int>(minimumCapacity: 1)
buffer.append(1)
do {
try await clone.finish(buffer: &buffer, finalElement: ())
Issue.record("Expected error")
} catch {
#expect(error is MultiProducerSingleConsumerAsyncChannelAlreadyFinishedError)
}
}
}
// MARK: - Body-error wrapping // 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 @Test
func readBodyErrorsWrappedInSecond() async throws { func readBodyErrorsWrappedInSecond() async throws {
struct BodyError: Error, Equatable {} struct BodyError: Error, Equatable {}
@@ -422,7 +509,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Scope cleanup // 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 @Test
func scopeFinalizesBothDirectionsOnReturn() async throws { func scopeFinalizesBothDirectionsOnReturn() async throws {
nonisolated(unsafe) var aTerminated = false nonisolated(unsafe) var aTerminated = false
@@ -442,7 +529,7 @@ struct DuplexAsyncChannelTests {
// MARK: - Protocol conformance // 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 @Test
func writerConformsToCallerAsyncWriter() async throws { func writerConformsToCallerAsyncWriter() async throws {
// Exercise CallerAsyncWriter.finish(buffer:finalElement:) by calling // Exercise CallerAsyncWriter.finish(buffer:finalElement:) by calling
@@ -486,7 +573,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 @Test
func readerConformsToAsyncReader() async throws { func readerConformsToAsyncReader() async throws {
// Exercise AsyncReader.read through a generic function that only // Exercise AsyncReader.read through a generic function that only
@@ -12,6 +12,7 @@
#if UnstableAsyncStreaming && compiler(>=6.4) #if UnstableAsyncStreaming && compiler(>=6.4)
import BasicContainers import BasicContainers
import ContainersPreview import ContainersPreview
import SpanPreview
extension Array { extension Array {
init(_ span: Span<Element>) { 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) { init<C: RangeReplaceableContainer<Element> & ~Copyable & ~Escapable>(draining container: inout C) {
self.init() self.init()
var consumer = container.consumeAll() var consumer = container.consumeAll()
@@ -14,6 +14,7 @@ import AsyncStreaming
import BasicContainers import BasicContainers
import ContainersPreview import ContainersPreview
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayAsyncWriter: ~Copyable, AsyncWriter { struct UniqueArrayAsyncWriter: ~Copyable, AsyncWriter {
typealias WriteElement = Int typealias WriteElement = Int
typealias Buffer = UniqueArray<Int> typealias Buffer = UniqueArray<Int>
@@ -14,6 +14,7 @@ import AsyncStreaming
import BasicContainers import BasicContainers
import ContainersPreview import ContainersPreview
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayCallerAsyncReader: ~Copyable, CallerAsyncReader { struct UniqueArrayCallerAsyncReader: ~Copyable, CallerAsyncReader {
typealias ReadElement = Int typealias ReadElement = Int
typealias ReadFailure = Never typealias ReadFailure = Never
@@ -16,6 +16,7 @@ import ContainersPreview
struct WriterCapacityError: Error {} struct WriterCapacityError: Error {}
@available(macOS 27.0, iOS 27.0, watchOS 27.0, tvOS 27.0, visionOS 27.0, *)
struct UniqueArrayCallerAsyncWriter: ~Copyable, CallerAsyncWriter { struct UniqueArrayCallerAsyncWriter: ~Copyable, CallerAsyncWriter {
typealias WriteElement = Int typealias WriteElement = Int
typealias WriteFailure = Never typealias WriteFailure = Never
@@ -17,11 +17,13 @@ import ContainersPreview
import DequeModule import DequeModule
import Testing import Testing
private struct MultiProducerSingleConsumerAsyncChannelTestError: Error {}
@Suite(.serialized) @Suite(.serialized)
struct MultiProducerSingleConsumerAsyncChannelTests { struct MultiProducerSingleConsumerAsyncChannelTests {
// MARK: - AsyncReader.read // 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 @Test
func readReturnsAllBufferedElementsInOrder() async throws { func readReturnsAllBufferedElementsInOrder() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel( 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 @Test
func readSuspendsUntilElementArrives() async throws { func readSuspendsUntilElementArrives() async throws {
try await withThrowingTaskGroup(of: [Int].self) { group in 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 @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( try await MultiProducerSingleConsumerAsyncChannel.withChannel(
of: Int.self, of: Int.self,
backpressureStrategy: .watermark(low: 2, high: 4) backpressureStrategy: .watermark(low: 2, high: 4)
@@ -86,21 +201,22 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
var writeBuffer = UniqueArray<Int>(minimumCapacity: 1) var writeBuffer = UniqueArray<Int>(minimumCapacity: 1)
writeBuffer.append(1) writeBuffer.append(1)
try await source.write(buffer: &writeBuffer) 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(buffer.count == 1)
#expect(finalElement == nil)
buffer.removeAll() buffer.removeAll()
} }
var sawEmpty = false source.finish()
try await channel.read { buffer, _ in
sawEmpty = buffer.count == 0 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 @Test
func readThrowsFailureAfterFinishWithError() async throws { func readThrowsFailureAfterFinishWithError() async throws {
struct TestError: Error, Equatable {} 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 @Test
func readBodyErrorsWrappedInSecond() async throws { func readBodyErrorsWrappedInSecond() async throws {
struct BodyError: Error, Equatable {} 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 @Test
func readPartialConsumptionRemainsVisibleOnNextRead() async throws { func readPartialConsumptionRemainsVisibleOnNextRead() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel( 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 @Test
func readResumesSuspendedProducersWhenWaterLevelDrops() async throws { func readResumesSuspendedProducersWhenWaterLevelDrops() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in 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 @Test
func readWaterLevelForElementCalledPerElementInBatch() async throws { func readWaterLevelForElementCalledPerElementInBatch() async throws {
nonisolated(unsafe) var callCount = 0 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 @Test
func readBufferIsReusedAcrossReads() async throws { func readBufferIsReusedAcrossReads() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel( 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 @Test
func readDeliversFinalElementOnFinish() async throws { func readDeliversFinalElementOnFinish() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel( try await MultiProducerSingleConsumerAsyncChannel.withChannel(
@@ -354,7 +470,7 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
// MARK: - CallerAsyncWriter.write // 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 @Test
func writeAppendsAllElementsAndClearsBuffer() async throws { func writeAppendsAllElementsAndClearsBuffer() async throws {
try await MultiProducerSingleConsumerAsyncChannel.withChannel( 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 @Test
func writeAfterFinishThrows() async throws { func writeAfterFinishThrows() async throws {
await MultiProducerSingleConsumerAsyncChannel.withChannel( 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 @Test
func writeSuspendsOnBackpressureAndResumesAfterRead() async throws { func writeSuspendsOnBackpressureAndResumesAfterRead() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in try await withThrowingTaskGroup(of: Void.self) { group in
@@ -426,15 +542,12 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
var source = source var source = source
group.addTask { group.addTask {
// Reader drains until EOS. // Reader drains until it observes the final element.
while true { while true {
var done = false var done = false
try await channel.read { buffer, _ in try await channel.read { buffer, finalElement in
if buffer.count == 0 { buffer.removeAll()
done = true done = finalElement != nil
} else {
buffer.removeAll()
}
} }
if done { break } 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 @Test
func writeReadRoundtripPreservesOrder() async throws { func writeReadRoundtripPreservesOrder() async throws {
let total = 100 let total = 100
@@ -465,13 +578,10 @@ struct MultiProducerSingleConsumerAsyncChannelTests {
nonisolated(unsafe) var collected: [Int] = [] nonisolated(unsafe) var collected: [Int] = []
var done = false var done = false
while !done { while !done {
try await channel.read { buffer, _ in try await channel.read { buffer, finalElement in
if buffer.count == 0 { var c = buffer.consumeAll()
done = true while let v = c.next() { collected.append(v) }
} else { done = finalElement != nil
var c = buffer.consumeAll()
while let v = c.next() { collected.append(v) }
}
} }
} }
#expect(collected == Array(0..<total)) #expect(collected == Array(0..<total))