Compare commits

...
20 Commits
Author SHA1 Message Date
Philippe Hausler 4a1fb99f00 Rework availability for executor to avoid warnings (#288) 2023-08-22 16:09:28 -07:00
Franz Busch b0ec4694d2 Remove the validation packages from public products (#287)
# Motivation
The current validation testing library has a bunch of warnings and we haven't put it through a proper API review yet. Since we are preparing for a 1.0.0, I think it is best if we remove the products for the validation targets for now and take some time to make sure the interfaces are taken through an API review.

# Modification
Remove products for the validation targets.
2023-08-18 11:19:58 -07:00
Philippe Hausler e639e5c889 Ensure tests work in deployments that host as swift 5.7 (#285) 2023-08-15 15:40:57 -07:00
Franz Busch 7ac31f979f Fix more Sendable warnings and flaky test (#281)
# Motivation
We still had some `Sendable` warnings left under strict Concurrency checking.

# Modification
This PR fixes a bunch of `Sendable` warnings but we still have some left in the validation tests. Additionally, I fixed a flaky test.
2023-08-01 16:09:34 +01:00
Franz Busch f5d5fb6483 Mark all iterators as non-Sendable (#280) 2023-07-27 22:16:37 +01:00
Freya Alminde df46b4c235 Fix typo in Guides/Chunked.md (#277) 2023-07-24 16:42:27 +01:00
Fabian Fett 07a0c1ee08 Remove copy and paste within MergeStorage (#275) 2023-07-11 14:18:10 +01:00
0xpablo adb12bfccc Add WebAssembly support (#273) 2023-06-23 15:54:35 -07:00
Franz Busch 2ace7010e9 Add docker files for CI (#270) 2023-06-23 14:21:48 -07:00
Philippe Hausler a42b72ad84 Audit pass on Sendable conformances and requirements (#272)
* Audit pass on Sendable conformances and requirements

* A slightly cleaner mark for Sendability of OrderedSet

* Remove flags for strict mode
2023-06-23 14:21:34 -07:00
Philippe Hausler 156bb4bf49 Reduce the overall warnings from tests (#274)
* Migrate from semaphore style testing waits to async test fulfillment

* Reduce warnings for missing hashable and comparable conformances per availability

* Reduce warnings for executor (still one known warning)
2023-06-23 12:22:23 -07:00
Franz Busch 936a68d012 [AsyncInterspersedSequence] Integrate review feedback (#267)
* Integrate review feedback

This integrates all of the feedback from the review thread. Here is a quick summary:

- Change the trailing separator behaviour. We are no longer returning a separator before we are forwarding the error
- Add a synchronous and asynchronous closure based `interspersed` method.
- Support interspersing every n elements

* Add AsyncThrowingInterspersedSequence

* Update examples
2023-06-23 15:47:25 +02:00
Philippe Hausler 92747901e0 Audit pass on inline and initialization (#271) 2023-06-23 15:40:09 +02:00
Kazumasa Shimomura ac9309b2ac Rename downStream to downstream (#263) 2023-06-22 12:54:24 -07:00
Franz Busch b3394663fd Add Interspersed proposal (#259)
* Clean up old evolution proposals

# Motivation

Our old proposals had a couple of stale links and were not all aligned. This cleans them up.

* Add Interspersed proposal

# Motivation
Add a new evolution proposal for the interspersed algorithm.
2023-05-10 15:18:41 +01:00
Franz Busch 0c00af2372 Clean up old evolution proposals (#258)
# Motivation

Our old proposals had a couple of stale links and were not all aligned. This cleans them up.
2023-05-10 13:10:31 +01:00
elmetal 9d83fff5b8 [Channel] Fix Source links in documentation (#264) 2023-05-10 13:05:56 +01:00
Max Desiatov e6b21d2a6d Package.swift: make package name consistent (#255)
Rest of SwiftPM packages provided by Apple follow a dash-case naming scheme with `swift-` prefix.
2023-03-09 10:40:27 +00:00
Franz Busch 7e45005473 Switch from group.waitForAll() to group.next() (#254)
# Motivation
Swift 5.8 is including a change to how `group.waitForAll()` is working. It now properly waits for all tasks to finish even if one of the tasks throws. We have used `group.waitForAll()` in multiple places and need to change this code accordingly.

# Modification
Switch code from `group.waitForAll()` to `group.next()`.

# Result
This fixes a few stuck tests that we have seen when running against development snapshots.
2023-02-28 08:35:03 +00:00
Thibault Wittemberg ffa6ee9f0b evolution: add buffer (#252) 2023-02-15 22:32:12 +00:00
89 changed files with 1854 additions and 792 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# file options
--swiftversion 5.7
--exclude .build
# format options
--self insert
--patternlet inline
--ranges nospace
--stripunusedargs unnamed-only
--ifdef no-indent
--extensionacl on-declarations
--disable typeSugar # https://github.com/nicklockwood/SwiftFormat/issues/636
--disable andOperator
--disable wrapMultilineStatementBraces
--disable enumNamespaces
--disable redundantExtensionACL
--disable redundantReturn
--disable preferKeyPath
--disable sortedSwitchCases
--disable hoistAwait
--disable hoistTry
# rules
+4 -6
View File
@@ -2,9 +2,9 @@
* Proposal: [SAA-0001](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0001-zip.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncZip2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncZip3Sequence.swift) |
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Zip/AsyncZip2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Zip/AsyncZip3Sequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestZip.swift)]
* Decision Notes:
* Bugs:
@@ -45,8 +45,7 @@ public func zip<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence
public struct AsyncZip2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable, Base2.Element: Sendable,
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable {
public typealias Element = (Base1.Element, Base2.Element)
public struct Iterator: AsyncIteratorProtocol {
@@ -59,8 +58,7 @@ public struct AsyncZip2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Sen
public struct AsyncZip3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable, Base3: Sendable
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base3.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable {
public typealias Element = (Base1.Element, Base2.Element, Base3.Element)
public struct Iterator: AsyncIteratorProtocol {
+4 -6
View File
@@ -2,9 +2,9 @@
* Proposal: [SAA-0002](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0002-merge.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Asyncmerge2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncMerge3Sequence.swift) |
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Merge/AsyncMerge2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Merge/AsyncMerge3Sequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestMerge.swift)]
* Decision Notes:
* Bugs:
@@ -46,8 +46,7 @@ public struct AsyncMerge2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: S
where
Base1.Element == Base2.Element,
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable, Base2.Element: Sendable,
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable {
public typealias Element = Base1.Element
public struct Iterator: AsyncIteratorProtocol {
@@ -61,8 +60,7 @@ public struct AsyncMerge3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Ba
where
Base1.Element == Base2.Element, Base1.Element == Base3.Element,
Base1: Sendable, Base2: Sendable, Base3: Sendable
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base3.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable {
public typealias Element = Base1.Element
public struct Iterator: AsyncIteratorProtocol {
+2 -2
View File
@@ -1,8 +1,8 @@
# Compacted
* Proposal: [0003](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0003-compacted.md)
* Proposal: [SAA-0003](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0003-compacted.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncCompactedSequence.swift)
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestCompacted.swift)
+1 -1
View File
@@ -3,7 +3,7 @@
* Proposal: [SAA-0004](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0004-joined.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Review Manager: [Franz Busch](https://github.com/FranzBusch)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncJoinedSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestJoin.swift)]
+1 -1
View File
@@ -3,7 +3,7 @@
* Proposal: [SAA-0005](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0005-adjacent-pairs.md)
* Author(s): [László Teveli](https://github.com/tevelee)
* Review Manager: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAdjacentPairsSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestAdjacentPairs.swift)]
* Decision Notes:
+4 -6
View File
@@ -2,10 +2,10 @@
* Proposal: [SAA-0006](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0006-combineLatest.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncCombineLatest2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncCombineLatest3Sequence.swift) |
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/CombineLatest/AsyncCombineLatest2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/CombineLatest/AsyncCombineLatest3Sequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestCombineLatest.swift)]
* Decision Notes:
@@ -47,8 +47,7 @@ public func combineLatest<Base1: AsyncSequence, Base2: AsyncSequence, Base3: Asy
public struct AsyncCombineLatest2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable, Base2.Element: Sendable,
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable {
public typealias Element = (Base1.Element, Base2.Element)
public struct Iterator: AsyncIteratorProtocol {
@@ -61,8 +60,7 @@ public struct AsyncCombineLatest2Sequence<Base1: AsyncSequence, Base2: AsyncSequ
public struct AsyncCombineLatest3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable, Base3: Sendable
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base3.AsyncIterator: Sendable {
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable {
public typealias Element = (Base1.Element, Base2.Element, Base3.Element)
public struct Iterator: AsyncIteratorProtocol {
+1 -1
View File
@@ -2,7 +2,7 @@
* Proposal: [SAA-0007](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0007-chain.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChain2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChain3Sequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChain.swift)]
+2 -2
View File
@@ -2,7 +2,7 @@
* Proposal: [SAA-0008](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0008-bytes.md)
* Authors: [David Smith](https://github.com/Catfish-Man), [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Status: **Accepted**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncBufferedByteIterator.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestBufferedByteIterator.swift)]
@@ -33,7 +33,7 @@ struct AsyncBytes: AsyncSequence {
## Detailed Design
```swift
public struct AsyncBufferedByteIterator: AsyncIteratorProtocol, Sendable {
public struct AsyncBufferedByteIterator: AsyncIteratorProtocol {
public typealias Element = UInt8
public init(
+1 -1
View File
@@ -1,6 +1,6 @@
# AsyncSyncSequence
* Proposal: [NNNN](NNNN-lazy.md)
* Proposal: [SAA-0009](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0009-async.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
+114
View File
@@ -0,0 +1,114 @@
# Buffer
* Proposal: [SAA-0010](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0010-buffer.md)
* Author(s): [Thibault Wittemberg](https://github.com/twittemb)
* Status: **Accepted**
* Implementation: [
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Buffer/AsyncBufferSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestBuffer.swift)
]
* Decision Notes:
* Bugs:
## Introduction
Buffering is a technique that balances supply and demand by temporarily storing elements to even out fluctuations in production and consumption rates. `AsyncStream` facilitates this process by allowing you to control the size of the buffer and the strategy for handling elements that exceed that size. However, this approach may not be suitable for all situations, and it doesn't provide a way to adapt other `AsyncSequence` types to incorporate buffering.
This proposal presents a new type that addresses these more advanced requirements and offers a comprehensive solution for buffering in asynchronous sequences.
## Motivation
As an `AsyncSequence` operates as a pull system, the production of elements is directly tied to the demand expressed by the consumer. The slower the consumer is in requesting elements, the slower the production of these elements will be. This can negatively impact the software that produces the elements, as demonstrated in the following example.
Consider an `AsyncSequence` that reads and returns a line from a file every time a new element is requested. To ensure exclusive access to the file, a lock is maintained while reading. Ideally, the lock should be held for as short a duration as possible to allow other processes to access the file. However, if the consumer is slow in processing received lines or has a fluctuating pace, the lock will be maintained for an extended period, reducing the performance of the system.
To mitigate this issue, a buffer operator can be employed to streamline the consumption of the `AsyncSequence`. This operator allows an internal iteration of the `AsyncSequence` independently from the consumer. Each element would then be made available for consumption by using a queuing mechanism.
By applying the buffer operator to the previous example, the file can be read as efficiently as possible, allowing the lock to be released in a timely manner. This results in improved performance, as the consumer can consume elements at its own pace without negatively affecting the system. The buffer operator ensures that the production of elements is not limited by the pace of the consumer, allowing both the producer and consumer to operate at optimal levels.
## Proposed Solution
We propose to extend `AsyncSequence` with a `buffer()` operator. This operator will return an `AsyncBuffereSequence` that wraps the source `AsyncSequence` and handle the buffering mechanism.
This operator will accept an `AsyncBufferSequencePolicy`. The policy will dictate the behaviour in case of a buffer overflow.
As of now we propose 4 different behaviours:
```swift
public struct AsyncBufferSequencePolicy: Sendable {
public static func bounded(_ limit: Int)
public static var unbounded
public static func bufferingLatest(_ limit: Int)
public static func bufferingOldest(_ limit: Int)
}
```
And the public API of `AsyncBuffereSequence` will be:
```swift
extension AsyncSequence where Self: Sendable {
public func buffer(
policy: AsyncBufferSequencePolicy
) -> AsyncBufferSequence<Self> {
AsyncBufferSequence<Self>(base: self, policy: policy)
}
}
public struct AsyncBufferSequence<Base: AsyncSequence & Sendable>: AsyncSequence {
public typealias Element = Base.Element
public func makeAsyncIterator() -> Iterator
public struct Iterator: AsyncIteratorProtocol {
public mutating func next() async rethrows -> Element?
}
}
extension AsyncBufferSequence: Sendable where Base: Sendable { }
```
## Notes on Sendable
Since all buffering means that the base asynchronous sequence must be iterated independently of the consumption (to resolve the production versus consumption issue) the base `AsyncSequence` needs to be able to be sent across task boundaries (the iterator does not need this requirement).
## Detailed Design
The choice of the buffering policy is made through an enumeration whose values are related to a storage type. To date, two types of storage are implemented:
- `BoundedBufferStorage` backing the `AsyncBufferSequencePolicy.bounded(_:)` policy,
- `UnboundedBufferStorage` backing the `AsyncBufferSequencePolicy.unbounded`, `AsyncBufferSequencePolicy.bufferingNewest(_:)` and `AsyncBufferSequencePolicy.bufferingLatest(_:)` policies.
Both storage types rely on a Mealy state machine stored in a `ManagedCriticalState`. They drive the mutations of the internal buffer, while ensuring that concurrent access to the state are safe.
### BoundedBufferStorage
`BoundedBufferStorage` is instantiated with the upstream `AsyncSequence` and a buffer maximum size. Upon the first call to the `next()` method, a task is spawned to support the iteration over this `AsyncSequence`. The iteration retrieves elements and adds them to an internal buffer as long as the buffer limit has not been reached. Meanwhile, the downstream `AsyncSequence` can access and consume these elements from the buffer. If the rate of consumption is slower than the rate of production, the buffer will eventually become full. In this case, the iteration is temporarily suspended until additional space becomes available.
### UnboundedBufferStorage
`UnboundedBufferStorage` is instantiated with the upstream `AsyncSequence` and a buffering policy. Upon the first call to the `next()` method, a task is spawned to support the iteration over this `AsyncSequence`.
From there the behaviour will depend on the buffering policy.
#### Unbounded
If the policy is `unbounded`, the iteration retrieves elements and adds them to an internal buffer until the upstream `AsyncSequence` finishes or fails. Meanwhile, the downstream `AsyncSequence` can access and consume these elements from the buffer.
#### BufferingLatest
If the policy is `bufferingLatest(_:)`, the iteration retrieves elements and adds them to an internal buffer. Meanwhile, the downstream `AsyncSequence` can access and consume these elements from the buffer. If the rate of consumption is slower than the rate of production, the buffer will eventually become full. In this case the oldest buffered elements will be removed from the buffer and the latest ones will be added.
#### BufferingOldest
If the policy is `bufferingOldest(_:)`, the iteration retrieves elements and adds them to an internal buffer. Meanwhile, the downstream `AsyncSequence` can access and consume these elements from the buffer. If the rate of consumption is slower than the rate of production, the buffer will eventually become full. In this case the latest element will be discarded and never added to the buffer.
### Terminal events and cancellation
Terminal events from the upstream `AsyncSequence`, such as normal completion or failure, are delayed, ensuring that the consumer will receive all the elements before receiving the termination.
If the consuming `Task` is cancelled, so will be the `Task` supporting the iteration of the upstream `AsyncSequence`.
## Alternatives Considered
The buffering mechanism was originally thought to rely on an open implementation of an `AsyncBuffer` protocol, which would be constrained to an `Actor` conformance. It was meant for developers to be able to provide their own implementation of a buffering algorithm. This buffer was designed to control the behavior of elements when pushed and popped, in an isolated manner.
A default implementation was provided to offers a queuing strategy for buffering elements, with options for unbounded, oldest-first, or newest-first buffering.
This implementation was eventually discarded due to the potentially higher cost of calling isolated functions on an `Actor`, compared to using a low-level locking mechanism like the one employed in other operators through the use of the `ManagedCriticalState`.
+319
View File
@@ -0,0 +1,319 @@
# Feature name
* Proposal: [SAA-0011](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0011-interspersed.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Review Manager: [Franz Busch](https://github.com/FranzBusch)
* Status: **Implemented**
* Implementation:
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Interspersed/AsyncInterspersedSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestLazy.swift)
## Motivation
A common transformation that is applied to async sequences is to intersperse the elements with
a separator element.
## Proposed solution
We propose to add a new method on `AsyncSequence` that allows to intersperse
a separator between every n emitted element. This proposed API looks like this
```swift
public extension AsyncSequence {
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: The value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
func interspersed(every: Int = 1, with separator: Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
func interspersed(every: Int = 1, with separator: @Sendable @escaping () -> Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
func interspersed(every: Int = 1, with separator: @Sendable @escaping () async -> Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () throws -> Element) -> AsyncThrowingInterspersedSequence<Self> {
AsyncThrowingInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () async throws -> Element) -> AsyncThrowingInterspersedSequence<Self> {
AsyncThrowingInterspersedSequence(self, every: every, separator: separator)
}
}
```
## Detailed design
The bulk of the implementation of the new `interspersed` method is inside the new
`AsyncInterspersedSequence` struct. It constructs an iterator to the base async sequence
inside its own iterator. The `AsyncInterspersedSequence.Iterator.next()` is forwarding the demand
to the base iterator.
Below is the implementation of the `AsyncInterspersedSequence`.
```swift
/// An asynchronous sequence that presents the elements of a base asynchronous sequence of
/// elements with a separator between each of those elements.
public struct AsyncInterspersedSequence<Base: AsyncSequence> {
@usableFromInline
internal enum Separator {
case element(Element)
case syncClosure(@Sendable () -> Element)
case asyncClosure(@Sendable () async -> Element)
}
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal init(_ base: Base, every: Int, separator: Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .element(separator)
self.every = every
}
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .syncClosure(separator)
self.every = every
}
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () async -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .asyncClosure(separator)
self.every = every
}
}
extension AsyncInterspersedSequence: AsyncSequence {
public typealias Element = Base.Element
/// The iterator for an `AsyncInterspersedSequence` asynchronous sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
internal enum State {
case start(Element?)
case element(Int)
case separator
case finished
}
@usableFromInline
internal var iterator: Base.AsyncIterator
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal var state = State.start(nil)
@usableFromInline
internal init(_ iterator: Base.AsyncIterator, every: Int, separator: Separator) {
self.iterator = iterator
self.separator = separator
self.every = every
}
public mutating func next() async rethrows -> Base.Element? {
// After the start, the state flips between element and separator. Before
// returning a separator, a check is made for the next element as a
// separator is only returned between two elements. The next element is
// stored to allow it to be returned in the next iteration. However, if
// the checking the next element throws, the separator is emitted before
// rethrowing that error.
switch state {
case var .start(element):
do {
if element == nil {
element = try await self.iterator.next()
}
if let element = element {
if every == 1 {
state = .separator
} else {
state = .element(1)
}
return element
} else {
state = .finished
return nil
}
} catch {
state = .finished
throw error
}
case .separator:
do {
if let element = try await iterator.next() {
state = .start(element)
switch separator {
case let .element(element):
return element
case let .syncClosure(closure):
return closure()
case let .asyncClosure(closure):
return await closure()
}
} else {
state = .finished
return nil
}
} catch {
state = .finished
throw error
}
case let .element(count):
do {
if let element = try await iterator.next() {
let newCount = count + 1
if every == newCount {
state = .separator
} else {
state = .element(newCount)
}
return element
} else {
state = .finished
return nil
}
} catch {
state = .finished
throw error
}
case .finished:
return nil
}
}
}
@inlinable
public func makeAsyncIterator() -> AsyncInterspersedSequence<Base>.Iterator {
Iterator(base.makeAsyncIterator(), every: every, separator: separator)
}
}
```
+22 -10
View File
@@ -1,9 +1,9 @@
// swift-tools-version: 5.6
// swift-tools-version: 5.8
import PackageDescription
let package = Package(
name: "AsyncAlgorithms",
name: "swift-async-algorithms",
platforms: [
.macOS("10.15"),
.iOS("13.0"),
@@ -12,26 +12,38 @@ let package = Package(
],
products: [
.library(name: "AsyncAlgorithms", targets: ["AsyncAlgorithms"]),
.library(name: "AsyncSequenceValidation", targets: ["AsyncSequenceValidation"]),
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"]),
.library(name: "AsyncAlgorithms_XCTest", targets: ["AsyncAlgorithms_XCTest"]),
],
dependencies: [.package(url: "https://github.com/apple/swift-collections.git", .upToNextMajor(from: "1.0.3"))],
dependencies: [.package(url: "https://github.com/apple/swift-collections.git", .upToNextMajor(from: "1.0.4"))],
targets: [
.target(
name: "AsyncAlgorithms",
dependencies: [.product(name: "Collections", package: "swift-collections")]
dependencies: [.product(name: "Collections", package: "swift-collections")],
swiftSettings: [
.enableExperimentalFeature("StrictConcurrency=complete"),
]
),
.target(
name: "AsyncSequenceValidation",
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"]),
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"],
swiftSettings: [
.enableExperimentalFeature("StrictConcurrency=complete"),
]
),
.systemLibrary(name: "_CAsyncSequenceValidationSupport"),
.target(
name: "AsyncAlgorithms_XCTest",
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"]),
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"],
swiftSettings: [
.enableExperimentalFeature("StrictConcurrency=complete"),
]
),
.testTarget(
name: "AsyncAlgorithmsTests",
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation", "AsyncAlgorithms_XCTest"]),
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation", "AsyncAlgorithms_XCTest"],
swiftSettings: [
.enableExperimentalFeature("StrictConcurrency=complete"),
]
),
]
)
+51
View File
@@ -0,0 +1,51 @@
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "swift-async-algorithms",
platforms: [
.macOS("10.15"),
.iOS("13.0"),
.tvOS("13.0"),
.watchOS("6.0")
],
products: [
.library(name: "AsyncAlgorithms", targets: ["AsyncAlgorithms"]),
.library(name: "AsyncSequenceValidation", targets: ["AsyncSequenceValidation"]),
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"]),
.library(name: "AsyncAlgorithms_XCTest", targets: ["AsyncAlgorithms_XCTest"]),
],
dependencies: [.package(url: "https://github.com/apple/swift-collections.git", .upToNextMajor(from: "1.0.4"))],
targets: [
.target(
name: "AsyncAlgorithms",
dependencies: [.product(name: "Collections", package: "swift-collections")]
),
.target(
name: "AsyncSequenceValidation",
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"]),
.systemLibrary(name: "_CAsyncSequenceValidationSupport"),
.target(
name: "AsyncAlgorithms_XCTest",
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"]),
.testTarget(
name: "AsyncAlgorithmsTests",
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation", "AsyncAlgorithms_XCTest"]),
]
)
#if canImport(Darwin)
import Darwin
let buildingDocs = getenv("BUILDING_FOR_DOCUMENTATION_GENERATION") != nil
#elseif canImport(Glibc)
import Glibc
let buildingDocs = getenv("BUILDING_FOR_DOCUMENTATION_GENERATION") != nil
#else
let buildingDocs = false
#endif
// Only require the docc plugin when building documentation
package.dependencies += buildingDocs ? [
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
] : []
@@ -9,6 +9,29 @@
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// An `AsyncSequence` that iterates over the adjacent pairs of the original
/// original `AsyncSequence`.
///
/// ```
/// for await (first, second) in (1...5).async.adjacentPairs() {
/// print("First: \(first), Second: \(second)")
/// }
///
/// // First: 1, Second: 2
/// // First: 2, Second: 3
/// // First: 3, Second: 4
/// // First: 4, Second: 5
/// ```
///
/// - Returns: An `AsyncSequence` where the element is a tuple of two adjacent elements
/// or the original `AsyncSequence`.
@inlinable
public func adjacentPairs() -> AsyncAdjacentPairsSequence<Self> {
AsyncAdjacentPairsSequence(self)
}
}
/// An `AsyncSequence` that iterates over the adjacent pairs of the original
/// `AsyncSequence`.
@frozen
@@ -60,29 +83,6 @@ public struct AsyncAdjacentPairsSequence<Base: AsyncSequence>: AsyncSequence {
}
}
extension AsyncSequence {
/// An `AsyncSequence` that iterates over the adjacent pairs of the original
/// original `AsyncSequence`.
///
/// ```
/// for await (first, second) in (1...5).async.adjacentPairs() {
/// print("First: \(first), Second: \(second)")
/// }
///
/// // First: 1, Second: 2
/// // First: 2, Second: 3
/// // First: 3, Second: 4
/// // First: 4, Second: 5
/// ```
///
/// - Returns: An `AsyncSequence` where the element is a tuple of two adjacent elements
/// or the original `AsyncSequence`.
@inlinable
public func adjacentPairs() -> AsyncAdjacentPairsSequence<Self> {
AsyncAdjacentPairsSequence(self)
}
}
extension AsyncAdjacentPairsSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
@available(*, unavailable)
@@ -3,8 +3,8 @@
* Author(s): [Philippe Hausler](https://github.com/phausler)
[
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncChannel.swift),
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncThrowingChannel.swift) |
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Channels/AsyncChannel.swift),
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/Channels/AsyncThrowingChannel.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestChannel.swift)
]
@@ -213,7 +213,7 @@ If both count and signal are specified, the chunking asynchronous sequence emits
Like the example above, this code emits up to 1024-byte `Data` instances, but a chunk will also be emitted every second.
```swift
let packets = bytes.chunks(ofCount: 1024 or: .repeating(every: .seconds(1)), into: Data.self)
let packets = bytes.chunks(ofCount: 1024, or: .repeating(every: .seconds(1)), into: Data.self)
for try await packet in packets {
write(packet)
}
@@ -42,7 +42,7 @@ extension AsyncTimerSequence: Sendable { }
extension AsyncTimerSequence.Iterator: Sendable { }
```
Since all the types comprising `AsyncTimerSequence` and it's `Iterator` are `Sendable` these types are also `Sendable`.
Since all the types comprising `AsyncTimerSequence` are `Sendable` these types are also `Sendable`.
## Credits/Inspiration
@@ -95,3 +95,6 @@ extension AsyncChain3Sequence: AsyncSequence {
}
extension AsyncChain3Sequence: Sendable where Base1: Sendable, Base2: Sendable, Base3: Sendable { }
@available(*, unavailable)
extension AsyncChain3Sequence.Iterator: Sendable { }
@@ -117,4 +117,6 @@ public struct AsyncChunkedByGroupSequence<Base: AsyncSequence, Collected: RangeR
}
extension AsyncChunkedByGroupSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
extension AsyncChunkedByGroupSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable { }
@available(*, unavailable)
extension AsyncChunkedByGroupSequence.Iterator: Sendable { }
@@ -97,4 +97,6 @@ public struct AsyncChunkedOnProjectionSequence<Base: AsyncSequence, Subject: Equ
}
extension AsyncChunkedOnProjectionSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
extension AsyncChunkedOnProjectionSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable, Subject : Sendable { }
@available(*, unavailable)
extension AsyncChunkedOnProjectionSequence.Iterator: Sendable { }
@@ -128,3 +128,6 @@ public struct AsyncChunksOfCountOrSignalSequence<Base: AsyncSequence, Collected:
return Iterator(iterator: merge(chain(base.map { Either.element($0) }, [.terminal].async), signal.map { _ in Either.signal }).makeAsyncIterator(), count: count)
}
}
@available(*, unavailable)
extension AsyncChunksOfCountOrSignalSequence.Iterator: Sendable { }
@@ -83,3 +83,6 @@ public struct AsyncChunksOfCountSequence<Base: AsyncSequence, Collected: RangeRe
extension AsyncChunksOfCountSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
extension AsyncChunksOfCountSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable { }
@available(*, unavailable)
extension AsyncChunksOfCountSequence.Iterator: Sendable { }
@@ -9,6 +9,22 @@
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns a new `AsyncSequence` that iterates over every non-nil element from the
/// original `AsyncSequence`.
///
/// Produces the same result as `c.compactMap { $0 }`.
///
/// - Returns: An `AsyncSequence` where the element is the unwrapped original
/// element and iterates over every non-nil element from the original
/// `AsyncSequence`.
@inlinable
public func compacted<Unwrapped>() -> AsyncCompactedSequence<Self, Unwrapped>
where Element == Unwrapped? {
AsyncCompactedSequence(self)
}
}
/// An `AsyncSequence` that iterates over every non-nil element from the original
/// `AsyncSequence`.
@frozen
@@ -50,22 +66,7 @@ public struct AsyncCompactedSequence<Base: AsyncSequence, Element>: AsyncSequenc
}
}
extension AsyncSequence {
/// Returns a new `AsyncSequence` that iterates over every non-nil element from the
/// original `AsyncSequence`.
///
/// Produces the same result as `c.compactMap { $0 }`.
///
/// - Returns: An `AsyncSequence` where the element is the unwrapped original
/// element and iterates over every non-nil element from the original
/// `AsyncSequence`.
///
/// Complexity: O(1)
@inlinable
public func compacted<Unwrapped>() -> AsyncCompactedSequence<Self, Unwrapped>
where Element == Unwrapped? {
AsyncCompactedSequence(self)
}
}
extension AsyncCompactedSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
@available(*, unavailable)
extension AsyncCompactedSequence.Iterator: Sendable { }
@@ -112,3 +112,6 @@ extension AsyncExclusiveReductionsSequence: AsyncSequence {
}
extension AsyncExclusiveReductionsSequence: Sendable where Base: Sendable, Element: Sendable { }
@available(*, unavailable)
extension AsyncExclusiveReductionsSequence.Iterator: Sendable { }
@@ -58,7 +58,7 @@ extension AsyncInclusiveReductionsSequence: AsyncSequence {
internal let transform: @Sendable (Base.Element, Base.Element) async -> Base.Element
@inlinable
internal init(
init(
_ iterator: Base.AsyncIterator,
transform: @Sendable @escaping (Base.Element, Base.Element) async -> Base.Element
) {
@@ -85,3 +85,6 @@ extension AsyncInclusiveReductionsSequence: AsyncSequence {
}
extension AsyncInclusiveReductionsSequence: Sendable where Base: Sendable { }
@available(*, unavailable)
extension AsyncInclusiveReductionsSequence.Iterator: Sendable { }
@@ -1,102 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns an asynchronous sequence containing elements of this asynchronous sequence with
/// the given separator inserted in between each element.
///
/// Any value of the asynchronous sequence's element type can be used as the separator.
///
/// - Parameter separator: The value to insert in between each of this async
/// sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(with separator: Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, separator: separator)
}
}
/// An asynchronous sequence that presents the elements of a base asynchronous sequence of
/// elements with a separator between each of those elements.
public struct AsyncInterspersedSequence<Base: AsyncSequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Base.Element
@usableFromInline
internal init(_ base: Base, separator: Base.Element) {
self.base = base
self.separator = separator
}
}
extension AsyncInterspersedSequence: AsyncSequence {
public typealias Element = Base.Element
/// The iterator for an `AsyncInterspersedSequence` asynchronous sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
internal enum State {
case start
case element(Result<Base.Element, Error>)
case separator
}
@usableFromInline
internal var iterator: Base.AsyncIterator
@usableFromInline
internal let separator: Base.Element
@usableFromInline
internal var state = State.start
@usableFromInline
internal init(_ iterator: Base.AsyncIterator, separator: Base.Element) {
self.iterator = iterator
self.separator = separator
}
public mutating func next() async rethrows -> Base.Element? {
// After the start, the state flips between element and separator. Before
// returning a separator, a check is made for the next element as a
// separator is only returned between two elements. The next element is
// stored to allow it to be returned in the next iteration. However, if
// the checking the next element throws, the separator is emitted before
// rethrowing that error.
switch state {
case .start:
state = .separator
return try await iterator.next()
case .separator:
do {
guard let next = try await iterator.next() else { return nil }
state = .element(.success(next))
} catch {
state = .element(.failure(error))
}
return separator
case .element(let result):
state = .separator
return try result._rethrowGet()
}
}
}
@inlinable
public func makeAsyncIterator() -> AsyncInterspersedSequence<Base>.Iterator {
Iterator(base.makeAsyncIterator(), separator: separator)
}
}
extension AsyncInterspersedSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
@@ -142,3 +142,6 @@ public struct AsyncJoinedBySeparatorSequence<Base: AsyncSequence, Separator: Asy
extension AsyncJoinedBySeparatorSequence: Sendable
where Base: Sendable, Base.Element: Sendable, Base.Element.Element: Sendable, Separator: Sendable { }
@available(*, unavailable)
extension AsyncJoinedBySeparatorSequence.Iterator: Sendable { }
@@ -92,3 +92,6 @@ public struct AsyncJoinedSequence<Base: AsyncSequence>: AsyncSequence where Base
extension AsyncJoinedSequence: Sendable
where Base: Sendable, Base.Element: Sendable, Base.Element.Element: Sendable { }
@available(*, unavailable)
extension AsyncJoinedSequence.Iterator: Sendable { }
@@ -143,3 +143,9 @@ public struct AsyncThrowingRemoveDuplicatesSequence<Base: AsyncSequence>: AsyncS
extension AsyncRemoveDuplicatesSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
extension AsyncThrowingRemoveDuplicatesSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
@available(*, unavailable)
extension AsyncRemoveDuplicatesSequence.Iterator: Sendable { }
@available(*, unavailable)
extension AsyncThrowingRemoveDuplicatesSequence.Iterator: Sendable { }
@@ -67,3 +67,6 @@ public struct AsyncSyncSequence<Base: Sequence>: AsyncSequence {
}
extension AsyncSyncSequence: Sendable where Base: Sendable { }
@available(*, unavailable)
extension AsyncSyncSequence.Iterator: Sendable { }
@@ -102,3 +102,6 @@ extension AsyncThrottleSequence: AsyncSequence {
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncThrottleSequence: Sendable where Base: Sendable, Element: Sendable { }
@available(*, unavailable)
extension AsyncThrottleSequence.Iterator: Sendable { }
@@ -119,3 +119,6 @@ extension AsyncThrowingExclusiveReductionsSequence: AsyncSequence {
}
extension AsyncThrowingExclusiveReductionsSequence: Sendable where Base: Sendable, Element: Sendable { }
@available(*, unavailable)
extension AsyncThrowingExclusiveReductionsSequence.Iterator: Sendable { }
@@ -1,3 +1,14 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given error-throwing closure.
@@ -57,7 +68,7 @@ extension AsyncThrowingInclusiveReductionsSequence: AsyncSequence {
internal let transform: @Sendable (Base.Element, Base.Element) async throws -> Base.Element
@inlinable
internal init(
init(
_ iterator: Base.AsyncIterator,
transform: @Sendable @escaping (Base.Element, Base.Element) async throws -> Base.Element
) {
@@ -89,3 +100,6 @@ extension AsyncThrowingInclusiveReductionsSequence: AsyncSequence {
}
extension AsyncThrowingInclusiveReductionsSequence: Sendable where Base: Sendable { }
@available(*, unavailable)
extension AsyncThrowingInclusiveReductionsSequence.Iterator: Sendable { }
@@ -89,3 +89,6 @@ extension AsyncTimerSequence where C == SuspendingClock {
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncTimerSequence: Sendable { }
@available(*, unavailable)
extension AsyncTimerSequence.Iterator: Sendable { }
@@ -70,7 +70,7 @@ public struct AsyncBufferSequencePolicy: Sendable {
/// An `AsyncSequence` that buffers elements in regard to a policy.
public struct AsyncBufferSequence<Base: AsyncSequence & Sendable>: AsyncSequence {
enum StorageType<Base: AsyncSequence> {
enum StorageType {
case transparent(Base.AsyncIterator)
case bounded(storage: BoundedBufferStorage<Base>)
case unbounded(storage: UnboundedBufferStorage<Base>)
@@ -82,7 +82,7 @@ public struct AsyncBufferSequence<Base: AsyncSequence & Sendable>: AsyncSequence
let base: Base
let policy: AsyncBufferSequencePolicy
public init(
init(
base: Base,
policy: AsyncBufferSequencePolicy
) {
@@ -91,7 +91,7 @@ public struct AsyncBufferSequence<Base: AsyncSequence & Sendable>: AsyncSequence
}
public func makeAsyncIterator() -> Iterator {
let storageType: StorageType<Base>
let storageType: StorageType
switch self.policy.policy {
case .bounded(...0), .bufferingNewest(...0), .bufferingOldest(...0):
storageType = .transparent(self.base.makeAsyncIterator())
@@ -108,7 +108,7 @@ public struct AsyncBufferSequence<Base: AsyncSequence & Sendable>: AsyncSequence
}
public struct Iterator: AsyncIteratorProtocol {
var storageType: StorageType<Base>
var storageType: StorageType
public mutating func next() async rethrows -> Element? {
switch self.storageType {
@@ -16,7 +16,7 @@ struct BoundedBufferStateMachine<Base: AsyncSequence> {
typealias SuspendedProducer = UnsafeContinuation<Void, Never>
typealias SuspendedConsumer = UnsafeContinuation<Result<Base.Element, Error>?, Never>
private enum State {
fileprivate enum State {
case initial(base: Base)
case buffering(
task: Task<Void, Never>,
@@ -308,3 +308,6 @@ struct BoundedBufferStateMachine<Base: AsyncSequence> {
}
}
}
extension BoundedBufferStateMachine: Sendable where Base: Sendable { }
extension BoundedBufferStateMachine.State: Sendable where Base: Sendable { }
@@ -21,7 +21,7 @@ struct UnboundedBufferStateMachine<Base: AsyncSequence> {
case bufferingOldest(Int)
}
private enum State {
fileprivate enum State {
case initial(base: Base)
case buffering(
task: Task<Void, Never>,
@@ -248,3 +248,6 @@ struct UnboundedBufferStateMachine<Base: AsyncSequence> {
}
}
}
extension UnboundedBufferStateMachine: Sendable where Base: Sendable { }
extension UnboundedBufferStateMachine.State: Sendable where Base: Sendable { }
@@ -19,7 +19,7 @@
/// on the `Iterator` is made, or when `finish()` is called from another Task.
/// As `finish()` induces a terminal state, there is no more need for a back pressure management.
/// This function does not suspend and will finish all the pending iterations.
public final class AsyncChannel<Element>: AsyncSequence, @unchecked Sendable {
public final class AsyncChannel<Element: Sendable>: AsyncSequence, @unchecked Sendable {
public typealias Element = Element
public typealias AsyncIterator = Iterator
@@ -58,3 +58,6 @@ public final class AsyncChannel<Element>: AsyncSequence, @unchecked Sendable {
}
}
}
@available(*, unavailable)
extension AsyncChannel.Iterator: Sendable { }
@@ -18,7 +18,7 @@
/// and is resumed when the next call to `next()` on the `Iterator` is made, or when `finish()`/`fail(_:)` is called
/// from another Task. As `finish()` and `fail(_:)` induce a terminal state, there is no more need for a back pressure management.
/// Those functions do not suspend and will finish all the pending iterations.
public final class AsyncThrowingChannel<Element, Failure: Error>: AsyncSequence, @unchecked Sendable {
public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: AsyncSequence, @unchecked Sendable {
public typealias Element = Element
public typealias AsyncIterator = Iterator
@@ -61,3 +61,6 @@ public final class AsyncThrowingChannel<Element, Failure: Error>: AsyncSequence,
}
}
}
@available(*, unavailable)
extension AsyncThrowingChannel.Iterator: Sendable { }
@@ -10,8 +10,11 @@
//===----------------------------------------------------------------------===//
@_implementationOnly import OrderedCollections
struct ChannelStateMachine<Element, Failure: Error>: Sendable {
private struct SuspendedProducer: Hashable {
// NOTE: this is only marked as unchecked since the swift-collections tag is before auditing for Sendable
extension OrderedSet: @unchecked Sendable where Element: Sendable { }
struct ChannelStateMachine<Element: Sendable, Failure: Error>: Sendable {
private struct SuspendedProducer: Hashable, Sendable {
let id: UInt64
let continuation: UnsafeContinuation<Void, Never>?
let element: Element?
@@ -29,7 +32,7 @@ struct ChannelStateMachine<Element, Failure: Error>: Sendable {
}
}
private struct SuspendedConsumer: Hashable {
private struct SuspendedConsumer: Hashable, Sendable {
let id: UInt64
let continuation: UnsafeContinuation<Element?, any Error>?
@@ -51,7 +54,7 @@ struct ChannelStateMachine<Element, Failure: Error>: Sendable {
case failed(Error)
}
private enum State {
private enum State: Sendable {
case channeling(
suspendedProducers: OrderedSet<SuspendedProducer>,
cancelledProducers: Set<SuspendedProducer>,
@@ -8,7 +8,7 @@
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct ChannelStorage<Element, Failure: Error>: Sendable {
struct ChannelStorage<Element: Sendable, Failure: Error>: Sendable {
private let stateMachine: ManagedCriticalState<ChannelStateMachine<Element, Failure>>
private let ids = ManagedCriticalState<UInt64>(0)
@@ -46,7 +46,7 @@ public struct AsyncCombineLatest2Sequence<
let base1: Base1
let base2: Base2
public init(_ base1: Base1, _ base2: Base2) {
init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
}
@@ -87,3 +87,6 @@ public struct AsyncCombineLatest2Sequence<
}
}
}
@available(*, unavailable)
extension AsyncCombineLatest2Sequence.Iterator: Sendable { }
@@ -97,3 +97,6 @@ public struct AsyncCombineLatest3Sequence<
}
}
}
@available(*, unavailable)
extension AsyncCombineLatest3Sequence.Iterator: Sendable { }
@@ -530,7 +530,8 @@ struct CombineLatestStateMachine<
preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()")
case .upstreamsFinished:
preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()")
// We need to tolerate multiple upstreams failing
return .none
case .waitingForDemand(let task, let upstreams, _):
// An upstream threw. We can cancel everything now and transition to finished.
@@ -58,7 +58,7 @@ final class CombineLatestStorage<
base1: base1,
base2: base2,
base3: base3,
downStreamContinuation: continuation
downstreamContinuation: continuation
)
case .resumeContinuation(let downstreamContinuation, let result):
@@ -108,7 +108,7 @@ final class CombineLatestStorage<
base1: Base1,
base2: Base2,
base3: Base3?,
downStreamContinuation: StateMachine.DownstreamContinuation
downstreamContinuation: StateMachine.DownstreamContinuation
) {
// This creates a new `Task` that is iterating the upstream
// sequences. We must store it to cancel it at the right times.
@@ -319,39 +319,37 @@ final class CombineLatestStorage<
}
}
do {
try await group.waitForAll()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
switch action {
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let error,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
case .none:
break
}
}
switch action {
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let error,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
case .none:
break
group.cancelAll()
}
}
group.cancelAll()
}
}
}
stateMachine.taskIsStarted(task: task, downstreamContinuation: downStreamContinuation)
stateMachine.taskIsStarted(task: task, downstreamContinuation: downstreamContinuation)
}
}
@@ -41,7 +41,7 @@ public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable whe
/// - interval: The interval to debounce.
/// - tolerance: The tolerance of the clock.
/// - clock: The clock.
public init(_ base: Base, interval: C.Instant.Duration, tolerance: C.Instant.Duration?, clock: C) {
init(_ base: Base, interval: C.Instant.Duration, tolerance: C.Instant.Duration?, clock: C) {
self.base = base
self.interval = interval
self.tolerance = tolerance
@@ -53,20 +53,20 @@ public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable whe
extension AsyncDebounceSequence: AsyncSequence {
public typealias Element = Base.Element
public func makeAsyncIterator() -> AsyncIterator {
public func makeAsyncIterator() -> Iterator {
let storage = DebounceStorage(
base: self.base,
interval: self.interval,
tolerance: self.tolerance,
clock: self.clock
)
return AsyncIterator(storage: storage)
return Iterator(storage: storage)
}
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncDebounceSequence {
public struct AsyncIterator: AsyncIteratorProtocol {
public struct Iterator: AsyncIteratorProtocol {
/// This class is needed to hook the deinit to observe once all references to the ``AsyncIterator`` are dropped.
///
/// If we get move-only types we should be able to drop this class and use the `deinit` of the ``AsyncIterator`` struct itself.
@@ -97,3 +97,6 @@ extension AsyncDebounceSequence {
}
}
}
@available(*, unavailable)
extension AsyncDebounceSequence.Iterator: Sendable { }
@@ -390,8 +390,8 @@ struct DebounceStateMachine<Base: AsyncSequence, C: Clock> {
preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()")
case .upstreamFailure:
// The upstream already failed so it should never have throw again.
preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended()")
// We need to tolerate multiple upstreams failing
return .none
case .waitingForDemand(let task, .none, let clockContinuation, .none):
// We don't have any buffered element so we can just go ahead
@@ -517,8 +517,8 @@ struct DebounceStateMachine<Base: AsyncSequence, C: Clock> {
/// Actions returned by `clockSleepFinished()`.
enum ClockSleepFinishedAction {
/// Indicates that the downstream continuation should be resumed with the given element.
case resumeDownStreamContinuation(
downStreamContinuation: UnsafeContinuation<Result<Element?, Error>, Never>,
case resumeDownstreamContinuation(
downstreamContinuation: UnsafeContinuation<Result<Element?, Error>, Never>,
element: Element
)
}
@@ -547,8 +547,8 @@ struct DebounceStateMachine<Base: AsyncSequence, C: Clock> {
bufferedElement: nil
)
return .resumeDownStreamContinuation(
downStreamContinuation: downstreamContinuation,
return .resumeDownstreamContinuation(
downstreamContinuation: downstreamContinuation,
element: currentElement.element
)
} else {
@@ -238,8 +238,8 @@ final class DebounceStorage<Base: AsyncSequence, C: Clock>: @unchecked Sendable
let action = self.stateMachine.withCriticalRegion { $0.clockSleepFinished() }
switch action {
case .resumeDownStreamContinuation(let downStreamContinuation, let element):
downStreamContinuation.resume(returning: .success(element))
case .resumeDownstreamContinuation(let downstreamContinuation, let element):
downstreamContinuation.resume(returning: .success(element))
case .none:
break
@@ -254,39 +254,41 @@ final class DebounceStorage<Base: AsyncSequence, C: Clock>: @unchecked Sendable
}
}
do {
try await group.waitForAll()
} catch {
// The upstream sequence threw an error
let action = self.stateMachine.withCriticalRegion { $0.upstreamThrew(error) }
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
switch action {
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuation(
let downstreamContinuation,
let error,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
switch action {
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuation(
let downstreamContinuation,
let error,
let task,
let upstreamContinuation,
let clockContinuation
):
upstreamContinuation?.resume(throwing: CancellationError())
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
downstreamContinuation.resume(returning: .failure(error))
case .cancelTaskAndClockContinuation(
let task,
let clockContinuation
):
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
case .none:
break
}
}
case .cancelTaskAndClockContinuation(
let task,
let clockContinuation
):
clockContinuation?.resume(throwing: CancellationError())
task.cancel()
case .none:
break
group.cancelAll()
}
group.cancelAll()
}
}
}
@@ -0,0 +1,444 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: "-")
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: The value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: { "-" })
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () -> Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: { "-" })
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () async -> Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: { "-" })
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () throws -> Element) -> AsyncThrowingInterspersedSequence<Self> {
AsyncThrowingInterspersedSequence(self, every: every, separator: separator)
}
/// Returns a new asynchronous sequence containing the elements of this asynchronous sequence, inserting
/// the given separator between each element.
///
/// Any value of this asynchronous sequence's element type can be used as the separator.
///
/// The following example shows how an async sequences of `String`s can be interspersed using `-` as the separator:
///
/// ```
/// let input = ["A", "B", "C"].async
/// let interspersed = input.interspersed(with: { "-" })
/// for await element in interspersed {
/// print(element)
/// }
/// // Prints "A" "-" "B" "-" "C"
/// ```
///
/// - Parameters:
/// - every: Dictates after how many elements a separator should be inserted.
/// - separator: A closure that produces the value to insert in between each of this async sequence’s elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(every: Int = 1, with separator: @Sendable @escaping () async throws -> Element) -> AsyncThrowingInterspersedSequence<Self> {
AsyncThrowingInterspersedSequence(self, every: every, separator: separator)
}
}
/// An asynchronous sequence that presents the elements of a base asynchronous sequence of
/// elements with a separator between each of those elements.
public struct AsyncInterspersedSequence<Base: AsyncSequence> {
@usableFromInline
internal enum Separator {
case element(Element)
case syncClosure(@Sendable () -> Element)
case asyncClosure(@Sendable () async -> Element)
}
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal init(_ base: Base, every: Int, separator: Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .element(separator)
self.every = every
}
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .syncClosure(separator)
self.every = every
}
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () async -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .asyncClosure(separator)
self.every = every
}
}
extension AsyncInterspersedSequence: AsyncSequence {
public typealias Element = Base.Element
/// The iterator for an `AsyncInterspersedSequence` asynchronous sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
internal enum State {
case start(Element?)
case element(Int)
case separator
case finished
}
@usableFromInline
internal var iterator: Base.AsyncIterator
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal var state = State.start(nil)
@usableFromInline
internal init(_ iterator: Base.AsyncIterator, every: Int, separator: Separator) {
self.iterator = iterator
self.separator = separator
self.every = every
}
public mutating func next() async rethrows -> Base.Element? {
switch self.state {
case .start(var element):
do {
if element == nil {
element = try await self.iterator.next()
}
if let element = element {
if self.every == 1 {
self.state = .separator
} else {
self.state = .element(1)
}
return element
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .separator:
do {
if let element = try await iterator.next() {
self.state = .start(element)
switch self.separator {
case .element(let element):
return element
case .syncClosure(let closure):
return closure()
case .asyncClosure(let closure):
return await closure()
}
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .element(let count):
do {
if let element = try await iterator.next() {
let newCount = count + 1
if self.every == newCount {
self.state = .separator
} else {
self.state = .element(newCount)
}
return element
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .finished:
return nil
}
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(self.base.makeAsyncIterator(), every: self.every, separator: self.separator)
}
}
/// An asynchronous sequence that presents the elements of a base asynchronous sequence of
/// elements with a separator between each of those elements.
public struct AsyncThrowingInterspersedSequence<Base: AsyncSequence> {
@usableFromInline
internal enum Separator {
case syncClosure(@Sendable () throws -> Element)
case asyncClosure(@Sendable () async throws -> Element)
}
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () throws -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .syncClosure(separator)
self.every = every
}
@usableFromInline
internal init(_ base: Base, every: Int, separator: @Sendable @escaping () async throws -> Element) {
precondition(every > 0, "Separators can only be interspersed ever 1+ elements")
self.base = base
self.separator = .asyncClosure(separator)
self.every = every
}
}
extension AsyncThrowingInterspersedSequence: AsyncSequence {
public typealias Element = Base.Element
/// The iterator for an `AsyncInterspersedSequence` asynchronous sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
internal enum State {
case start(Element?)
case element(Int)
case separator
case finished
}
@usableFromInline
internal var iterator: Base.AsyncIterator
@usableFromInline
internal let separator: Separator
@usableFromInline
internal let every: Int
@usableFromInline
internal var state = State.start(nil)
@usableFromInline
internal init(_ iterator: Base.AsyncIterator, every: Int, separator: Separator) {
self.iterator = iterator
self.separator = separator
self.every = every
}
public mutating func next() async throws -> Base.Element? {
switch self.state {
case .start(var element):
do {
if element == nil {
element = try await self.iterator.next()
}
if let element = element {
if self.every == 1 {
self.state = .separator
} else {
self.state = .element(1)
}
return element
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .separator:
do {
if let element = try await iterator.next() {
self.state = .start(element)
switch self.separator {
case .syncClosure(let closure):
return try closure()
case .asyncClosure(let closure):
return try await closure()
}
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .element(let count):
do {
if let element = try await iterator.next() {
let newCount = count + 1
if self.every == newCount {
self.state = .separator
} else {
self.state = .element(newCount)
}
return element
} else {
self.state = .finished
return nil
}
} catch {
self.state = .finished
throw error
}
case .finished:
return nil
}
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(self.base.makeAsyncIterator(), every: self.every, separator: self.separator)
}
}
extension AsyncInterspersedSequence: Sendable where Base: Sendable, Base.Element: Sendable {}
extension AsyncInterspersedSequence.Separator: Sendable where Base: Sendable, Base.Element: Sendable {}
extension AsyncThrowingInterspersedSequence: Sendable where Base: Sendable, Base.Element: Sendable {}
extension AsyncThrowingInterspersedSequence.Separator: Sendable where Base: Sendable, Base.Element: Sendable {}
@available(*, unavailable)
extension AsyncInterspersedSequence.Iterator: Sendable {}
@available(*, unavailable)
extension AsyncThrowingInterspersedSequence.Iterator: Sendable {}
+2
View File
@@ -24,6 +24,8 @@ internal struct Lock {
typealias Primitive = pthread_mutex_t
#elseif canImport(WinSDK)
typealias Primitive = SRWLOCK
#else
typealias Primitive = Int
#endif
typealias PlatformLock = UnsafeMutablePointer<Primitive>
@@ -40,7 +40,7 @@ public struct AsyncMerge2Sequence<
/// - Parameters:
/// - base1: The first upstream ``Swift/AsyncSequence``.
/// - base2: The second upstream ``Swift/AsyncSequence``.
public init(
init(
_ base1: Base1,
_ base2: Base2
) {
@@ -50,18 +50,18 @@ public struct AsyncMerge2Sequence<
}
extension AsyncMerge2Sequence: AsyncSequence {
public func makeAsyncIterator() -> AsyncIterator {
public func makeAsyncIterator() -> Iterator {
let storage = MergeStorage<Base1, Base2, Base1>(
base1: base1,
base2: base2,
base3: nil
)
return AsyncIterator(storage: storage)
return Iterator(storage: storage)
}
}
extension AsyncMerge2Sequence {
public struct AsyncIterator: AsyncIteratorProtocol {
public struct Iterator: AsyncIteratorProtocol {
/// This class is needed to hook the deinit to observe once all references to the ``AsyncIterator`` are dropped.
///
/// If we get move-only types we should be able to drop this class and use the `deinit` of the ``AsyncIterator`` struct itself.
@@ -92,3 +92,6 @@ extension AsyncMerge2Sequence {
}
}
}
@available(*, unavailable)
extension AsyncMerge2Sequence.Iterator: Sendable { }
@@ -49,7 +49,7 @@ public struct AsyncMerge3Sequence<
/// - base1: The first upstream ``Swift/AsyncSequence``.
/// - base2: The second upstream ``Swift/AsyncSequence``.
/// - base3: The third upstream ``Swift/AsyncSequence``.
public init(
init(
_ base1: Base1,
_ base2: Base2,
_ base3: Base3
@@ -61,18 +61,18 @@ public struct AsyncMerge3Sequence<
}
extension AsyncMerge3Sequence: AsyncSequence {
public func makeAsyncIterator() -> AsyncIterator {
public func makeAsyncIterator() -> Iterator {
let storage = MergeStorage(
base1: base1,
base2: base2,
base3: base3
)
return AsyncIterator(storage: storage)
return Iterator(storage: storage)
}
}
public extension AsyncMerge3Sequence {
struct AsyncIterator: AsyncIteratorProtocol {
struct Iterator: AsyncIteratorProtocol {
/// This class is needed to hook the deinit to observe once all references to the ``AsyncIterator`` are dropped.
///
/// If we get move-only types we should be able to drop this class and use the `deinit` of the ``AsyncIterator`` struct itself.
@@ -103,3 +103,6 @@ public extension AsyncMerge3Sequence {
}
}
}
@available(*, unavailable)
extension AsyncMerge3Sequence.Iterator: Sendable { }
+125 -286
View File
@@ -147,297 +147,46 @@ final class MergeStorage<
// sequences. We must store it to cancel it at the right times.
let task = Task {
await withThrowingTaskGroup(of: Void.self) { group in
// For each upstream sequence we are adding a child task that
// is consuming the upstream sequence
group.addTask {
var iterator1 = base1.makeAsyncIterator()
// This is our upstream consumption loop
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
let action = self.lock.withLock {
self.stateMachine.childTaskSuspended(continuation)
}
switch action {
case let .resumeContinuation(continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case let .resumeContinuationWithError(continuation, error):
// This happens if another upstream already failed or if
// the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
// We got signalled from the downstream that we have demand so let's
// request a new element from the upstream
if let element1 = try await iterator1.next() {
let action = self.lock.withLock {
self.stateMachine.elementProduced(element1)
}
switch action {
case let .resumeContinuation(continuation, element):
// We had an outstanding demand and where the first
// upstream to produce an element so we can forward it to
// the downstream
continuation.resume(returning: element)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.lock.withLock {
self.stateMachine.upstreamFinished()
}
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case let .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
break loop
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
// Copy from the above just using the base2 sequence
group.addTask {
var iterator2 = base2.makeAsyncIterator()
// This is our upstream consumption loop
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
let action = self.lock.withLock {
self.stateMachine.childTaskSuspended(continuation)
}
switch action {
case let .resumeContinuation(continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case let .resumeContinuationWithError(continuation, error):
// This happens if another upstream already failed or if
// the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
// We got signalled from the downstream that we have demand so let's
// request a new element from the upstream
if let element2 = try await iterator2.next() {
let action = self.lock.withLock {
self.stateMachine.elementProduced(element2)
}
switch action {
case let .resumeContinuation(continuation, element):
// We had an outstanding demand and where the first
// upstream to produce an element so we can forward it to
// the downstream
continuation.resume(returning: element)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.lock.withLock {
self.stateMachine.upstreamFinished()
}
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case let .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
break loop
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
self.iterateAsyncSequence(base1, in: &group)
self.iterateAsyncSequence(base2, in: &group)
// Copy from the above just using the base3 sequence
if let base3 = base3 {
group.addTask {
var iterator3 = base3.makeAsyncIterator()
// This is our upstream consumption loop
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
let action = self.lock.withLock {
self.stateMachine.childTaskSuspended(continuation)
}
switch action {
case let .resumeContinuation(continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case let .resumeContinuationWithError(continuation, error):
// This happens if another upstream already failed or if
// the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
// We got signalled from the downstream that we have demand so let's
// request a new element from the upstream
if let element3 = try await iterator3.next() {
let action = self.lock.withLock {
self.stateMachine.elementProduced(element3)
}
switch action {
case let .resumeContinuation(continuation, element):
// We had an outstanding demand and where the first
// upstream to produce an element so we can forward it to
// the downstream
continuation.resume(returning: element)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.lock.withLock {
self.stateMachine.upstreamFinished()
}
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case let .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
break loop
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
self.iterateAsyncSequence(base3, in: &group)
}
do {
try await group.waitForAll()
} catch {
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
let action = self.lock.withLock {
self.stateMachine.upstreamThrew(error)
let action = self.lock.withLock {
self.stateMachine.upstreamThrew(error)
}
switch action {
case let .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
error,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(throwing: error)
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
group.cancelAll()
}
switch action {
case let .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
error,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(throwing: error)
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
group.cancelAll()
}
}
}
@@ -445,5 +194,95 @@ final class MergeStorage<
// We need to inform our state machine that we started the Task
stateMachine.taskStarted(task)
}
}
private func iterateAsyncSequence<AsyncSequence: _Concurrency.AsyncSequence>(
_ base: AsyncSequence,
in taskGroup: inout ThrowingTaskGroup<Void, Error>
) where AsyncSequence.Element == Base1.Element, AsyncSequence: Sendable {
// For each upstream sequence we are adding a child task that
// is consuming the upstream sequence
taskGroup.addTask {
var iterator = base.makeAsyncIterator()
// This is our upstream consumption loop
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
let action = self.lock.withLock {
self.stateMachine.childTaskSuspended(continuation)
}
switch action {
case let .resumeContinuation(continuation):
// This happens if there is outstanding demand
// and we need to demand from upstream right away
continuation.resume(returning: ())
case let .resumeContinuationWithError(continuation, error):
// This happens if another upstream already failed or if
// the task got cancelled.
continuation.resume(throwing: error)
case .none:
break
}
}
// We got signalled from the downstream that we have demand so let's
// request a new element from the upstream
if let element1 = try await iterator.next() {
let action = self.lock.withLock {
self.stateMachine.elementProduced(element1)
}
switch action {
case let .resumeContinuation(continuation, element):
// We had an outstanding demand and where the first
// upstream to produce an element so we can forward it to
// the downstream
continuation.resume(returning: element)
case .none:
break
}
} else {
// The upstream returned `nil` which indicates that it finished
let action = self.lock.withLock {
self.stateMachine.upstreamFinished()
}
// All of this is mostly cleanup around the Task and the outstanding
// continuations used for signalling.
switch action {
case let .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
downstreamContinuation,
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: nil)
break loop
case let .cancelTaskAndUpstreamContinuations(
task,
upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
}
}
@@ -1,47 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
enum PartialIteration<Iterator: AsyncIteratorProtocol, Partial: Sendable>: CustomStringConvertible {
case idle(Iterator)
case pending(Task<Partial, Never>)
case terminal
var description: String {
switch self {
case .idle: return "idle"
case .pending: return "pending"
case .terminal: return "terminal"
}
}
mutating func resolve(_ result: Result<Iterator.Element?, Error>, _ iterator: Iterator) rethrows -> Iterator.Element? {
do {
guard let value = try result._rethrowGet() else {
self = .terminal
return nil
}
self = .idle(iterator)
return value
} catch {
self = .terminal
throw error
}
}
mutating func cancel() {
if case .pending(let task) = self {
task.cancel()
}
self = .terminal
}
}
extension PartialIteration: Sendable where Iterator: Sendable, Iterator.Element: Sendable { }
@@ -69,3 +69,6 @@ public struct AsyncZip2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Asy
}
}
}
@available(*, unavailable)
extension AsyncZip2Sequence.Iterator: Sendable { }
@@ -74,3 +74,6 @@ public struct AsyncZip3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base
}
}
}
@available(*, unavailable)
extension AsyncZip3Sequence.Iterator: Sendable { }
+25 -25
View File
@@ -49,7 +49,7 @@ final class ZipStorage<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncS
base1: base1,
base2: base2,
base3: base3,
downStreamContinuation: continuation
downstreamContinuation: continuation
)
case .resumeUpstreamContinuations(let upstreamContinuations):
@@ -96,7 +96,7 @@ final class ZipStorage<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncS
base1: Base1,
base2: Base2,
base3: Base3?,
downStreamContinuation: StateMachine.DownstreamContinuation
downstreamContinuation: StateMachine.DownstreamContinuation
) {
// This creates a new `Task` that is iterating the upstream
// sequences. We must store it to cancel it at the right times.
@@ -286,35 +286,35 @@ final class ZipStorage<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncS
}
}
do {
try await group.waitForAll()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
while !group.isEmpty {
do {
try await group.next()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
switch action {
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let error,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
switch action {
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let error,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
case .none:
break
}
}
downstreamContinuation.resume(returning: .failure(error))
case .none:
break
group.cancelAll()
}
}
group.cancelAll()
}
}
}
stateMachine.taskIsStarted(task: task, downstreamContinuation: downStreamContinuation)
stateMachine.taskIsStarted(task: task, downstreamContinuation: downstreamContinuation)
}
}
@@ -132,3 +132,7 @@ extension AsyncSequenceValidationDiagram.Clock: TestClock { }
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram.Clock: Clock { }
// placeholders to avoid warnings
extension AsyncSequenceValidationDiagram.Clock.Instant: Hashable { }
extension AsyncSequenceValidationDiagram.Clock.Instant: Comparable { }
+1 -1
View File
@@ -19,6 +19,6 @@ struct Job: Hashable, @unchecked Sendable {
}
func execute() {
_swiftJobRun(unsafeBitCast(job, to: UnownedJob.self), AsyncSequenceValidationDiagram.Context.executor.asUnownedSerialExecutor())
_swiftJobRun(unsafeBitCast(job, to: UnownedJob.self), AsyncSequenceValidationDiagram.Context.unownedExecutor)
}
}
@@ -50,8 +50,12 @@ final class TaskDriver {
}
func start() {
#if canImport(Darwin) || canImport(Glibc)
pthread_create(&thread, nil, start_thread,
Unmanaged.passRetained(self).toOpaque())
#elseif canImport(WinSDK)
#error("TODO: Port TaskDriver threading to windows")
#endif
}
func run() {
+45 -2
View File
@@ -67,9 +67,27 @@ extension AsyncSequenceValidationDiagram {
}
struct Context {
#if swift(<5.9)
final class ClockExecutor: SerialExecutor {
func enqueue(_ job: UnownedJob) {
job._runSynchronously(on: asUnownedSerialExecutor())
job._runSynchronously(on: self.asUnownedSerialExecutor())
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
}
private static let _executor = ClockExecutor()
static var unownedExecutor: UnownedSerialExecutor {
_executor.asUnownedSerialExecutor()
}
#else
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
final class ClockExecutor_5_9: SerialExecutor {
func enqueue(_ job: __owned ExecutorJob) {
job.runSynchronously(on: asUnownedSerialExecutor())
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
@@ -77,9 +95,34 @@ extension AsyncSequenceValidationDiagram {
}
}
final class ClockExecutor_Pre5_9: SerialExecutor {
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@available(*, deprecated, message: "Implement 'enqueue(_: __owned ExecutorJob)' instead")
func enqueue(_ job: UnownedJob) {
job._runSynchronously(on: self.asUnownedSerialExecutor())
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
}
private static let _executor: AnyObject = {
if #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) {
return ClockExecutor_5_9()
} else {
return ClockExecutor_Pre5_9()
}
}()
static var unownedExecutor: UnownedSerialExecutor {
(_executor as! any SerialExecutor).asUnownedSerialExecutor()
}
#endif
static var clock: Clock?
static let executor = ClockExecutor()
static var driver: TaskDriver?
@@ -0,0 +1,181 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import AsyncAlgorithms
import XCTest
final class TestInterspersed: XCTestCase {
func test_interspersed() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_every() async {
let source = [1, 2, 3, 4, 5, 6, 7, 8]
let expected = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8]
let sequence = source.async.interspersed(every: 3, with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_closure() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed(with: { 0 })
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_async_closure() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed {
try! await Task.sleep(nanoseconds: 1000)
return 0
}
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed(with: { throw Failure() })
var iterator = sequence.makeAsyncIterator()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
let pastEnd = try! await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_async_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed {
try await Task.sleep(nanoseconds: 1000)
throw Failure()
}
var iterator = sequence.makeAsyncIterator()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
let pastEnd = try! await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_empty() async {
let source = [Int]()
let expected = [Int]()
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_with_throwing_upstream() async {
let source = [1, 2, 3, -1, 4, 5]
let expected = [1, 0, 2, 0, 3]
var actual = [Int]()
let sequence = source.async.map {
try throwOn(-1, $0)
}.interspersed(with: 0)
var iterator = sequence.makeAsyncIterator()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
let pastEnd = try! await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = source.async.interspersed(with: "sep")
let lockStepChannel = AsyncChannel<Void>()
await withTaskGroup(of: Void.self) { group in
group.addTask {
var iterator = sequence.makeAsyncIterator()
let _ = await iterator.next()
// Information the parent task that we are consuming
await lockStepChannel.send(())
while let _ = await iterator.next() {}
await lockStepChannel.send(())
}
// Waiting until the child task started consuming
_ = await lockStepChannel.first { _ in true }
// Now we cancel the child
group.cancelAll()
await group.waitForAll()
}
}
}
@@ -90,11 +90,12 @@ final class TestThroughput: XCTestCase {
zip($0, $1, $2)
}
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
func test_debounce() async {
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
await measureSequenceThroughput(source: (1...).async) {
$0.debounce(for: .zero, clock: ContinuousClock())
$0.debounce(for: .zero, clock: ContinuousClock())
}
}
}
}
#endif
@@ -56,7 +56,7 @@ final class _ThroughputMetric: NSObject, XCTMetric, @unchecked Sendable {
}
extension XCTestCase {
public func measureChannelThroughput<Output>(output: @escaping @autoclosure () -> Output) async {
public func measureChannelThroughput<Output: Sendable>(output: @Sendable @escaping @autoclosure () -> Output) async {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
@@ -85,7 +85,7 @@ extension XCTestCase {
}
}
public func measureThrowingChannelThroughput<Output>(output: @escaping @autoclosure () -> Output) async {
public func measureThrowingChannelThroughput<Output: Sendable>(output: @Sendable @escaping @autoclosure () -> Output) async {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
@@ -165,3 +165,47 @@ internal func XCTAssertThrowsError<T>(
verify(error)
}
}
class WaiterDelegate: NSObject, XCTWaiterDelegate {
let state: ManagedCriticalState<UnsafeContinuation<Void, Never>?> = ManagedCriticalState(nil)
init(_ continuation: UnsafeContinuation<Void, Never>) {
state.withCriticalRegion { $0 = continuation }
}
func waiter(_ waiter: XCTWaiter, didFulfillInvertedExpectation expectation: XCTestExpectation) {
resume()
}
func waiter(_ waiter: XCTWaiter, didTimeoutWithUnfulfilledExpectations unfulfilledExpectations: [XCTestExpectation]) {
resume()
}
func waiter(_ waiter: XCTWaiter, fulfillmentDidViolateOrderingConstraintsFor expectation: XCTestExpectation, requiredExpectation: XCTestExpectation) {
resume()
}
func nestedWaiter(_ waiter: XCTWaiter, wasInterruptedByTimedOutWaiter outerWaiter: XCTWaiter) {
}
func resume() {
let continuation = state.withCriticalRegion { continuation in
defer { continuation = nil }
return continuation
}
continuation?.resume()
}
}
extension XCTestCase {
@_disfavoredOverload
func fulfillment(of expectations: [XCTestExpectation], timeout: TimeInterval, enforceOrder: Bool = false, file: StaticString = #file, line: Int = #line) async {
return await withUnsafeContinuation { continuation in
let delegate = WaiterDelegate(continuation)
let waiter = XCTWaiter(delegate: delegate)
waiter.wait(for: expectations, timeout: timeout, enforceOrder: enforceOrder)
delegate.resume()
}
}
}
@@ -88,10 +88,11 @@ final class TestAdjacentPairs: XCTestCase {
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
+4 -4
View File
@@ -190,13 +190,13 @@ final class TestBuffer: XCTestCase {
finished.fulfill()
}
// ensure the task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// When
task.cancel()
// Then
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_given_a_base_sequence_when_buffering_with_bounded_then_the_buffer_is_filled_in_and_suspends() async {
@@ -310,13 +310,13 @@ final class TestBuffer: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// When
task.cancel()
// Then
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_given_a_base_sequence_when_bounded_with_limit_0_then_the_policy_is_transparent() async {
@@ -199,10 +199,10 @@ final class TestBufferedByteIterator: XCTestCase {
}
}
}
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
+4 -4
View File
@@ -87,13 +87,13 @@ final class TestChain2: XCTestCase {
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -192,12 +192,12 @@ final class TestChain3: XCTestCase {
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
+1 -1
View File
@@ -133,7 +133,7 @@ final class TestChannel: XCTestCase {
task1.cancel()
// Then: the first sending operation is resumed
wait(for: [send1IsResumed], timeout: 1.0)
await fulfillment(of: [send1IsResumed], timeout: 1.0)
// When: collecting elements
var iterator = sut.makeAsyncIterator()
@@ -13,10 +13,12 @@ import XCTest
import AsyncSequenceValidation
import AsyncAlgorithms
@Sendable
func sumCharacters(_ array: [String]) -> String {
return "\(array.reduce(into: 0) { $0 = $0 + Int($1)! })"
}
@Sendable
func concatCharacters(_ array: [String]) -> String {
return array.joined()
}
@@ -84,7 +84,7 @@ final class TestCombineLatest2: XCTestCase {
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b"), (3, "b"), (3, "c")])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b"), (3, "b"), (3, "c")])
}
@@ -126,7 +126,7 @@ final class TestCombineLatest2: XCTestCase {
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c")])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c")])
}
@@ -168,7 +168,7 @@ final class TestCombineLatest2: XCTestCase {
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a"), (3, "b"), (3, "c")])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a"), (3, "b"), (3, "c")])
}
@@ -210,7 +210,7 @@ final class TestCombineLatest2: XCTestCase {
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c"), (2, "c"), (3, "c")])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c"), (2, "c"), (3, "c")])
}
@@ -250,7 +250,7 @@ final class TestCombineLatest2: XCTestCase {
XCTAssertEqual(validator.failure as? Failure, Failure())
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b")])
}
@@ -290,7 +290,7 @@ final class TestCombineLatest2: XCTestCase {
XCTAssertEqual(validator.failure as? Failure, Failure())
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a")])
}
@@ -312,11 +312,11 @@ final class TestCombineLatest2: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_combineLatest_when_cancelled() async {
@@ -389,7 +389,7 @@ final class TestCombineLatest3: XCTestCase {
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)])
}
@@ -83,10 +83,10 @@ final class TestCompacted: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -1,91 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import XCTest
import AsyncAlgorithms
final class TestInterspersed: XCTestCase {
func test_interspersed() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_empty() async {
let source = [Int]()
let expected = [Int]()
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_with_throwing_upstream() async {
let source = [1, 2, 3, -1, 4, 5]
let expected = [1, 0, 2, 0, 3, 0]
var actual = [Int]()
let sequence = source.async.map {
try throwOn(-1, $0)
}.interspersed(with: 0)
var iterator = sequence.makeAsyncIterator()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
let pastEnd = try! await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = source.async.interspersed(with: "sep")
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var iterator = sequence.makeAsyncIterator()
let _ = await iterator.next()
iterated.fulfill()
while let _ = await iterator.next() { }
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
}
}
+4 -4
View File
@@ -122,11 +122,11 @@ final class TestJoinedBySeparator: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -206,10 +206,10 @@ final class TestJoined: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
+2 -2
View File
@@ -121,12 +121,12 @@ final class TestLazy: XCTestCase {
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -29,7 +29,7 @@ final class TestManualClock: XCTestCase {
clock.advance()
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
wait(for: [afterSleep], timeout: 1.0)
await fulfillment(of: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
}
@@ -51,7 +51,7 @@ final class TestManualClock: XCTestCase {
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
task.cancel()
wait(for: [afterSleep], timeout: 1.0)
await fulfillment(of: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
XCTAssertTrue(failure.withCriticalRegion { $0 is CancellationError })
}
@@ -73,7 +73,7 @@ final class TestManualClock: XCTestCase {
}
XCTAssertFalse(state.withCriticalRegion { $0 })
task.cancel()
wait(for: [afterSleep], timeout: 1.0)
await fulfillment(of: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
XCTAssertTrue(failure.withCriticalRegion { $0 is CancellationError })
}
+4 -4
View File
@@ -185,11 +185,11 @@ final class TestMerge2: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_merge_when_cancelled() async {
@@ -509,11 +509,11 @@ final class TestMerge3: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
// MARK: - IteratorInitialized
@@ -217,10 +217,10 @@ final class TestReductions: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -95,10 +95,10 @@ final class TestRemoveDuplicates: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
@@ -270,7 +270,7 @@ final class TestThrowingChannel: XCTestCase {
task1.cancel()
// Then: the first sending operation is resumed
wait(for: [send1IsResumed], timeout: 1.0)
await fulfillment(of: [send1IsResumed], timeout: 1.0)
// When: collecting elements
var iterator = sut.makeAsyncIterator()
+10 -10
View File
@@ -24,7 +24,7 @@ final class TestValidator: XCTestCase {
}
XCTAssertFalse(state.withCriticalRegion { $0 })
gate.open()
wait(for: [entered], timeout: 1.0)
await fulfillment(of: [entered], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
}
@@ -52,18 +52,18 @@ final class TestValidator: XCTestCase {
}
finished.fulfill()
}
wait(for: [started], timeout: 1.0)
await fulfillment(of: [started], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [])
gated.advance()
wait(for: [expectations[0]], timeout: 1.0)
await fulfillment(of: [expectations[0]], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [1])
gated.advance()
wait(for: [expectations[1]], timeout: 1.0)
await fulfillment(of: [expectations[1]], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [1, 2])
gated.advance()
wait(for: [expectations[2]], timeout: 1.0)
await fulfillment(of: [expectations[2]], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [1, 2, 3])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_gatedSequence_throwing() async {
@@ -93,14 +93,14 @@ final class TestValidator: XCTestCase {
}
finished.fulfill()
}
wait(for: [started], timeout: 1.0)
await fulfillment(of: [started], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [])
gated.advance()
wait(for: [expectations[0]], timeout: 1.0)
await fulfillment(of: [expectations[0]], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [1])
gated.advance()
XCTAssertEqual(state.withCriticalRegion { $0 }, [1])
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
XCTAssertEqual(state.withCriticalRegion { $0 }, [1])
XCTAssertEqual(failure.withCriticalRegion { $0 as? Failure }, Failure())
}
@@ -131,7 +131,7 @@ final class TestValidator: XCTestCase {
XCTAssertEqual(value, [2, 3, 4])
a.advance()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [2, 3, 4])
}
+4 -4
View File
@@ -152,11 +152,11 @@ final class TestZip2: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
func test_zip_when_cancelled() async {
@@ -370,10 +370,10 @@ final class TestZip3: XCTestCase {
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
await fulfillment(of: [finished], timeout: 1.0)
}
}
+24
View File
@@ -0,0 +1,24 @@
ARG swift_version=5.7
ARG ubuntu_version=focal
ARG base_image=swift:$swift_version-$ubuntu_version
FROM $base_image
# needed to do again after FROM due to docker limitation
ARG swift_version
ARG ubuntu_version
# set as UTF-8
RUN apt-get update && apt-get install -y locales locales-all
ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8
# tools
RUN mkdir -p $HOME/.tools
RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile
# swiftformat (until part of the toolchain)
ARG swiftformat_version=0.51.12
RUN git clone --branch $swiftformat_version --depth 1 https://github.com/nicklockwood/SwiftFormat $HOME/.tools/swift-format
RUN cd $HOME/.tools/swift-format && swift build -c release
RUN ln -s $HOME/.tools/swift-format/.build/release/swiftformat $HOME/.tools/swiftformat
+22
View File
@@ -0,0 +1,22 @@
version: "3"
services:
runtime-setup:
image: swift-async-algorithms:20.04-5.7
build:
args:
ubuntu_version: "focal"
swift_version: "5.7"
build:
image: swift-async-algorithms:20.04-5.7
test:
image: swift-async-algorithms:20.04-5.7
environment: []
#- SANITIZER_ARG: "--sanitize=thread"
#- TSAN_OPTIONS: "no_huge_pages_for_shadow=0 suppressions=/code/tsan_suppressions.txt"
shell:
image: swift-async-algorithms:20.04-5.7
+21
View File
@@ -0,0 +1,21 @@
version: "3"
services:
runtime-setup:
image: swift-async-algorithms:20.04-5.8
build:
args:
base_image: "swiftlang/swift:nightly-5.8-focal"
build:
image: swift-async-algorithms:20.04-5.8
test:
image: swift-async-algorithms:20.04-5.8
environment: []
#- SANITIZER_ARG: "--sanitize=thread"
#- TSAN_OPTIONS: "no_huge_pages_for_shadow=0 suppressions=/code/tsan_suppressions.txt"
shell:
image: swift-async-algorithms:20.04-5.8
+21
View File
@@ -0,0 +1,21 @@
version: "3"
services:
runtime-setup:
image: swift-async-algorithms:22.04-main
build:
args:
base_image: "swiftlang/swift:nightly-main-jammy"
build:
image: swift-async-algorithms:22.04-main
test:
image: swift-async-algorithms:22.04-main
environment: []
#- SANITIZER_ARG: "--sanitize=thread"
#- TSAN_OPTIONS: "no_huge_pages_for_shadow=0 suppressions=/code/tsan_suppressions.txt"
shell:
image: swift-async-algorithms:22.04-main
+39
View File
@@ -0,0 +1,39 @@
# this file is not designed to be run directly
# instead, use the docker-compose.<os>.<swift> files
# eg docker-compose -f docker/docker-compose.yaml -f docker/docker-compose.2004.56.yaml run test
version: "3"
services:
runtime-setup:
image: swift-async-algorithms:default
build:
context: .
dockerfile: Dockerfile
common: &common
image: swift-async-algorithms:default
depends_on: [runtime-setup]
volumes:
- ~/.ssh:/root/.ssh
- ..:/code:z
working_dir: /code
soundness:
<<: *common
command: /bin/bash -xcl "swift -version && uname -a && ./scripts/soundness.sh"
build:
<<: *common
environment: []
command: /bin/bash -cl "swift build"
test:
<<: *common
depends_on: [runtime-setup]
command: /bin/bash -xcl "swift $${SWIFT_TEST_VERB-test} $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-}"
# util
shell:
<<: *common
entrypoint: /bin/bash