mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-23 04:14:23 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cca423ff03 | ||
|
|
9a3e94d440 | ||
|
|
07b8d74cc7 | ||
|
|
434591a571 | ||
|
|
6e9a5757bc | ||
|
|
a973b06d06 | ||
|
|
6b59cfb8d0 | ||
|
|
d185b2068b | ||
|
|
bbbe08d331 | ||
|
|
6d5d6319f4 | ||
|
|
047ab6abef | ||
|
|
d2164b9ef6 | ||
|
|
b3d4ffb94c | ||
|
|
5b78eaf423 | ||
|
|
a3576e669b | ||
|
|
94a7ecec28 | ||
|
|
6a8aec2a1f | ||
|
|
9d03d90a13 | ||
|
|
c174e4603e | ||
|
|
b6755e6313 | ||
|
|
18749897a8 | ||
|
|
6971c8fc67 | ||
|
|
f1581d0973 | ||
|
|
442d20e8c8 |
No files matched your search
@@ -0,0 +1,110 @@
|
||||
# Zip
|
||||
|
||||
* 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**
|
||||
|
||||
* 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) |
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestZip.swift)]
|
||||
* Decision Notes:
|
||||
* Bugs:
|
||||
|
||||
## Introduction
|
||||
|
||||
The swift standard library has a function that allows for the combining of two sequences into one sequence of tuples of the elements of the base sequences. This concept can be achieved for `AsyncSequence` with the iteration being asynchronous but also each side being concurrently iterated while still rethrowing potential failures. This proposal covers that parity between `AsyncSequence` and `Sequence`. It is often times useful to describe asynchronous sequences of events as paired occurrences. The fundamental algorithm for this is zip.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
Zip combines the latest values produced from two or more asynchronous sequences into an asynchronous sequence of tuples.
|
||||
|
||||
```swift
|
||||
let appleFeed = URL(string: "http://www.example.com/ticker?symbol=AAPL")!.lines
|
||||
let nasdaqFeed = URL(string: "http://www.example.com/ticker?symbol=^IXIC")!.lines
|
||||
|
||||
for try await (apple, nasdaq) in zip(appleFeed, nasdaqFeed) {
|
||||
print("APPL: \(apple) NASDAQ: \(nasdaq)")
|
||||
}
|
||||
```
|
||||
|
||||
Given some sample inputs the following zipped events can be expected.
|
||||
|
||||
| Timestamp | appleFeed | nasdaqFeed | combined output |
|
||||
| ----------- | --------- | ---------- | ----------------------------- |
|
||||
| 11:40 AM | 173.91 | | |
|
||||
| 12:25 AM | | 14236.78 | AAPL: 173.91 NASDAQ: 14236.78 |
|
||||
| 12:40 AM | | 14218.34 | |
|
||||
| 1:15 PM | 173.00 | | AAPL: 173.00 NASDAQ: 14218.34 |
|
||||
|
||||
This function family and the associated family of return types are prime candidates for variadic generics. Until that proposal is accepted, these will be implemented in terms of two- and three-base sequence cases.
|
||||
|
||||
```swift
|
||||
public func zip<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncZip2Sequence<Base1, Base2>
|
||||
|
||||
public func zip<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>(_ base1: Base1, _ base2: Base2, _ base3: Base3) -> AsyncZip3Sequence<Base1, Base2, Base3>
|
||||
|
||||
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 {
|
||||
public typealias Element = (Base1.Element, Base2.Element)
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
public mutating func next() async rethrows -> Element?
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
|
||||
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 {
|
||||
public typealias Element = (Base1.Element, Base2.Element, Base3.Element)
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
public mutating func next() async rethrows -> Element?
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The `zip(_:...)` function takes two or more asynchronous sequences as arguments with the resulting `AsyncZipSequence` which is an asynchronous sequence.
|
||||
|
||||
Each iteration of an `AsyncZipSequence` will await for all base iterators to produce a value. This iteration will be done concurrently to produce a singular tuple result. If any of the base iterations terminates by returning `nil` from its iteration, the `AsyncZipSequence` iteration is immediately considered unsatisfiable and returns `nil` and all iterations of other bases will be cancelled. If any iteration of the bases throws an error, then the other iterations concurrently running are cancelled and the produced error is rethrown, terminating the iteration.
|
||||
|
||||
`AsyncZipSequence` requires that the iterations are done concurrently. This means that the base sequences, their elements, and iterators must all be `Sendable`. That makes `AsyncZipSequence` inherently `Sendable`.
|
||||
|
||||
The source of throwing of `AsyncZipSequence` is determined by its bases. That means that if any base can throw an error then the iteration of the `AsyncZipSequence` can throw. If no bases can throw, then the `AsyncZipSequence` does not throw.
|
||||
|
||||
### Naming
|
||||
|
||||
The `zip(_:...)` function takes its name from the Swift standard library function of the same name. The `AsyncZipSequence` family of types take their name from the same family from the standard library for the type returned by `zip(_:_:)`. The one difference is that this asynchronous version allows for the affordance of recognizing the eventual variadic generic need of expanding a zip of more than just two sources.
|
||||
|
||||
It is common in some libraries to have a `ZipMap` or some other combination of `zip` and `map`. This is a common usage pattern, but leaving a singular type for composition feels considerably more approachable.
|
||||
|
||||
### Comparison with other libraries
|
||||
|
||||
**Swift** The swift standard library has an [API definition of zip](https://developer.apple.com/documentation/swift/1541125-zip) as a top level function for combining two sequences.
|
||||
|
||||
**ReactiveX** ReactiveX has an [API definition of Zip](https://reactivex.io/documentation/operators/zip.html) as a top level function for combining Observables.
|
||||
|
||||
**Combine** Combine has an [API definition of zip](https://developer.apple.com/documentation/combine/publisher/zip(_:)/) as an operator style method for combining Publishers.
|
||||
|
||||
## Effect on API resilience
|
||||
|
||||
### `@frozen` and `@inlinable`
|
||||
|
||||
These types utilize rethrowing mechanisms that are awaiting an implementation in the compiler for supporting implementation based rethrows. So none of them are marked as frozen or marked as inlinable. This feature (discussed as `rethrows(unsafe)` or `rethrows(SourceOfRethrowyness)` has not yet been reviewed or implemented. The current implementation takes liberties with an internal protocol to accomplish this task. Future revisions will remove that protocol trick to replace it with proper rethrows semantics at the actual call site. The types are expected to be stable boundaries to prevent that workaround for the compilers yet to be supported rethrowing (or TaskGroup rethrowing) mechanisms. As soon as that feature is resolved; a more detailed investigation on performance impact of inlining and frozen should be done before 1.0.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
It was considered to have zip be shaped as an extension method on `AsyncSequence` however that infers a "primary-ness" of one `AsyncSequence` over another. Since the standard library spells this as a global function (which infers no preference to one side or another) it was decided that having symmetry between the asynchronous version and the synchronous version inferred the right connotations.
|
||||
|
||||
There are other methods with similar behavior that could be controlled by options passed in. This concept has merit but was initially disregarded since that would complicate the interface. Design-wise this is still an open question if having a "zip-behavior-options" parameter to encompass combining the latest values or zipping based upon a preference to a "primary" side or not is meaningful.
|
||||
|
||||
It is common to have a zip+map to create structures instead of tuples, however that was disregarded since that concept could easily be expressed by composing zip and map.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# Merge
|
||||
|
||||
* 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**
|
||||
|
||||
* 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) |
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestMerge.swift)]
|
||||
* Decision Notes:
|
||||
* Bugs:
|
||||
|
||||
## Introduction
|
||||
|
||||
In the category of combinations of asynchronous sequences there are a few different potential behaviors. This category all take two or more `AsyncSequence` types and produce one `AsyncSequence`. One fundamental behavior is taking all values produced by the inputs and resuming the iteration of the singular downstream `AsyncSequence` with those values. This shape is called merge.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
Merge takes two or more asynchronous sequences sharing the same element type and combines them into one singular asynchronous sequence of those elements.
|
||||
|
||||
```swift
|
||||
let appleFeed = URL(string: "http://www.example.com/ticker?symbol=AAPL")!.lines.map { "AAPL: " + $0 }
|
||||
let nasdaqFeed = URL(string:"http://www.example.com/ticker?symbol=^IXIC")!.lines.map { "^IXIC: " + $0 }
|
||||
|
||||
for try await ticker in merge(appleFeed, nasdaqFeed) {
|
||||
print(ticker)
|
||||
}
|
||||
```
|
||||
|
||||
Given some sample inputs the following merged events can be expected.
|
||||
|
||||
| Timestamp | appleFeed | nasdaqFeed | merged output |
|
||||
| ----------- | --------- | ---------- | --------------- |
|
||||
| 11:40 AM | 173.91 | | AAPL: 173.91 |
|
||||
| 12:25 AM | | 14236.78 | ^IXIC: 14236.78 |
|
||||
| 12:40 AM | | 14218.34 | ^IXIC: 14218.34 |
|
||||
| 1:15 PM | 173.00 | | AAPL: 173.00 |
|
||||
|
||||
This function family and the associated family of return types are prime candidates for variadic generics. Until that proposal is accepted, these will be implemented in terms of two- and three-base sequence cases.
|
||||
|
||||
```swift
|
||||
public func merge<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncMerge2Sequence<Base1, Base2>
|
||||
|
||||
public func merge<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>(_ base1: Base1, _ base2: Base2, _ base3: Base3) -> AsyncMerge3Sequence<Base1, Base2, Base3>
|
||||
|
||||
public struct AsyncMerge2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable
|
||||
where
|
||||
Base1.Element == Base2.Element,
|
||||
Base1: Sendable, Base2: Sendable,
|
||||
Base1.Element: Sendable, Base2.Element: Sendable,
|
||||
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable {
|
||||
public typealias Element = Base1.Element
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
public mutating func next() async rethrows -> Element?
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
|
||||
public struct AsyncMerge3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>: Sendable
|
||||
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 {
|
||||
public typealias Element = Base1.Element
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
public mutating func next() async rethrows -> Element?
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The `merge(_:...)` function takes two or more asynchronous sequences as arguments and produces an `AsyncMergeSequence` which is an asynchronous sequence.
|
||||
|
||||
Since the bases comprising the `AsyncMergeSequence` must be iterated concurrently to produce the latest value, those sequences must be able to be sent to child tasks. This means that a prerequisite of the bases must be that the base asynchronous sequences, their iterators, and the elements they produce must be `Sendable`.
|
||||
|
||||
When iterating a `AsyncMergeSequence`, the sequence terminates when all of the base asynchronous sequences terminate, since this means there is no potential for any further elements to be produced.
|
||||
|
||||
The throwing behavior of `AsyncMergeSequence` is that if any of the bases throw, then the composed asynchronous sequence throws on its iteration. If at any point an error is thrown by any base, the other iterations are cancelled and the thrown error is immediately thrown to the consuming iteration.
|
||||
|
||||
### Naming
|
||||
|
||||
Since the inherent behavior of `merge(_:...)` merges values from multiple streams into a singular asynchronous sequence, the naming is intended to be quite literal. There are precedent terms of art in other frameworks and libraries (listed in the comparison section). Other naming takes the form of "withLatestFrom". This was disregarded since the "with" prefix is often most associated with the passing of a closure and some sort of contextual concept; `withUnsafePointer` or `withUnsafeContinuation` are prime examples.
|
||||
|
||||
### Comparison with other libraries
|
||||
|
||||
**ReactiveX** ReactiveX has an [API definition of Merge](https://reactivex.io/documentation/operators/merge.html) as a top level function for merging Observables.
|
||||
|
||||
**Combine** Combine has an [API definition of merge(with:)](https://developer.apple.com/documentation/combine/publisher/merge(with:)-7qt71/) as an operator style method for merging Publishers.
|
||||
|
||||
## Effect on API resilience
|
||||
|
||||
### `@frozen` and `@inlinable`
|
||||
|
||||
These types utilize rethrowing mechanisms that are awaiting an implementation in the compiler for supporting implementation based rethrows. So none of them are marked as frozen or marked as inlinable. This feature (discussed as `rethrows(unsafe)` or `rethrows(SourceOfRethrowyness)` has not yet been reviewed or implemented. The current implementation takes liberties with an internal protocol to accomplish this task. Future revisions will remove that protocol trick to replace it with proper rethrows semantics at the actual call site. The types are expected to be stable boundaries to prevent that workaround for the compilers yet to be supported rethrowing (or TaskGroup rethrowing) mechanisms. As soon as that feature is resolved; a more detailed investigation on performance impact of inlining and frozen should be done before 1.0.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
It was considered to have merge be shaped as an extension method on `AsyncSequence` however that infers a "primary-ness" of one `AsyncSequence` over another. Since the behavior of this as a global function (which infers no preference to one side or another) it was decided that having symmetry between the asynchronous version and the synchronous version inferred the right connotations.
|
||||
+21
-7
@@ -13,7 +13,8 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "AsyncAlgorithms", targets: ["AsyncAlgorithms"]),
|
||||
.library(name: "AsyncSequenceValidation", targets: ["AsyncSequenceValidation"]),
|
||||
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"])
|
||||
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"]),
|
||||
.library(name: "AsyncAlgorithms_XCTest", targets: ["AsyncAlgorithms_XCTest"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
@@ -22,13 +23,26 @@ let package = Package(
|
||||
name: "AsyncSequenceValidation",
|
||||
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"]),
|
||||
.systemLibrary(name: "_CAsyncSequenceValidationSupport"),
|
||||
.target(
|
||||
name: "AsyncAlgorithms_XCTest",
|
||||
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"]),
|
||||
.testTarget(
|
||||
name: "AsyncAlgorithmsTests",
|
||||
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"],
|
||||
swiftSettings: [
|
||||
.unsafeFlags([
|
||||
"-Xfrontend", "-disable-availability-checking"
|
||||
])
|
||||
]),
|
||||
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"),
|
||||
] : []
|
||||
@@ -1,6 +1,5 @@
|
||||
# swift-async-algorithms
|
||||
|
||||
|
||||
**Swift Async Algorithms** is an open-source package of asynchronous sequence and advanced algorithms that involve concurrency, along with their related types.
|
||||
|
||||
This package has three main goals:
|
||||
@@ -21,53 +20,53 @@ This package is the home for these APIs. Development and API design take place o
|
||||
|
||||
#### Combining asynchronous sequences
|
||||
|
||||
- [`chain(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chain.md): Concatenates two or more asynchronous sequences with the same element type.
|
||||
- [`combineLatest(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/CombineLatest.md): Combines two or more asynchronous sequences into an asynchronous sequence producing a tuple of elements from those base asynchronous sequences that updates when any of the base sequences produce a value.
|
||||
- [`merge(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Merge.md): Merges two or more asynchronous sequence into a single asynchronous sequence producing the elements of all of the underlying asynchronous sequences.
|
||||
- [`zip(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Zip.md): Creates an asynchronous sequence of pairs built out of underlying asynchronous sequences.
|
||||
- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Joined.md): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element.
|
||||
- [`chain(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Chain.md): Concatenates two or more asynchronous sequences with the same element type.
|
||||
- [`combineLatest(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/CombineLatest.md): Combines two or more asynchronous sequences into an asynchronous sequence producing a tuple of elements from those base asynchronous sequences that updates when any of the base sequences produce a value.
|
||||
- [`merge(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Merge.md): Merges two or more asynchronous sequence into a single asynchronous sequence producing the elements of all of the underlying asynchronous sequences.
|
||||
- [`zip(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Zip.md): Creates an asynchronous sequence of pairs built out of underlying asynchronous sequences.
|
||||
- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Joined.md): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element.
|
||||
|
||||
#### Creating asynchronous sequences
|
||||
|
||||
- [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence.
|
||||
- [`AsyncChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics.
|
||||
- [`AsyncThrowingChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics that can emit failures.
|
||||
- [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence.
|
||||
- [`AsyncChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics.
|
||||
- [`AsyncThrowingChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics that can emit failures.
|
||||
|
||||
#### Performance optimized asynchronous iterators
|
||||
|
||||
- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions.
|
||||
- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions.
|
||||
|
||||
#### Other useful asynchronous sequences
|
||||
- [`adjacentPairs()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/AdjacentPairs.md): Collects tuples of adjacent elements.
|
||||
- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chunked.md): Collect values into chunks.
|
||||
- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Compacted.md): Remove nil values from an asynchronous sequence.
|
||||
- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of an asynchronous sequence.
|
||||
- [`adjacentPairs()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/AdjacentPairs.md): Collects tuples of adjacent elements.
|
||||
- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Chunked.md): Collect values into chunks.
|
||||
- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Compacted.md): Remove nil values from an asynchronous sequence.
|
||||
- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Intersperse.md): Place a value between every two elements of an asynchronous sequence.
|
||||
|
||||
#### Asynchronous Sequences that transact in time
|
||||
|
||||
- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Debounce.md): Emit values after a quiescence period has been reached.
|
||||
- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Throttle.md): Ensure a minimum interval has elapsed between events.
|
||||
- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Timer.md): Emit the value of now at a given interval repeatedly.
|
||||
- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Debounce.md): Emit values after a quiescence period has been reached.
|
||||
- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Throttle.md): Ensure a minimum interval has elapsed between events.
|
||||
- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Timer.md): Emit the value of now at a given interval repeatedly.
|
||||
|
||||
#### Obtaining all values from an asynchronous sequence
|
||||
|
||||
- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new instance of a collection containing the elements of an asynchronous sequence.
|
||||
- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence.
|
||||
- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys.
|
||||
- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): /// Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
|
||||
- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new set from an asynchronous sequence of items.
|
||||
- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new instance of a collection containing the elements of an asynchronous sequence.
|
||||
- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence.
|
||||
- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys.
|
||||
- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
|
||||
- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new set from an asynchronous sequence of items.
|
||||
|
||||
|
||||
#### Task management
|
||||
|
||||
- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Select.md): Determine the first task to complete of a sequence of tasks.
|
||||
- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md): Determine the first task to complete of a sequence of tasks.
|
||||
|
||||
#### Effects
|
||||
|
||||
Each algorithm has specific behavioral effects. For throwing effects these can either be if the sequence throws, does not throw, or rethrows errors. Sendability effects in some asynchronous sequences are conditional whereas others require the composed parts to all be sendable to satisfy a requirement of `Sendable`. The effects are [listed here](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Effects.md).
|
||||
Each algorithm has specific behavioral effects. For throwing effects these can either be if the sequence throws, does not throw, or rethrows errors. Sendability effects in some asynchronous sequences are conditional whereas others require the composed parts to all be sendable to satisfy a requirement of `Sendable`. The effects are [listed here](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Effects.md).
|
||||
|
||||
## Adding Swift Algorithms as a Dependency
|
||||
## Adding Swift Async Algorithms as a Dependency
|
||||
|
||||
To use the `AsyncAlgorithms` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
@@ -88,28 +87,17 @@ Finally, add `import AsyncAlgorithms` to your source code.
|
||||
|
||||
## Getting Started
|
||||
|
||||
⚠️ Please note that this package currently requires a recent [Swift Trunk Development toolchain](https://www.swift.org/download/#trunk-development-main). More information on how to use custom toolchains with Xcode can be viewed [here](https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/Xcode_Overview/AlternativeToolchains.html).
|
||||
⚠️ Please note that this package requires Xcode 14 on macOS hosts. Previous versions of Xcode do not contain the required Swift version.
|
||||
|
||||
### Building/Testing Using Xcode on macOS
|
||||
|
||||
1. Download the most recent development Xcode toolchain.
|
||||
2. Install the package
|
||||
4. Select the development toolchain in Xcode
|
||||
4. Open the `swift-async-algorithms` package directory in Xcode
|
||||
5. Build or Test in Xcode as normal
|
||||
|
||||
⚠️ Note: `swift test` does not currently work properly with custom toolchains for this package.
|
||||
1. In the `swift-async-algorithms` directory run `swift build` or `swift test` accordingly
|
||||
|
||||
### Building/Testing on Linux
|
||||
|
||||
1. Download the most recent development toolchain for your Linux distribution
|
||||
2. Decompress the archive to a path in which the `swift` executable is in the binary search path environment variable (`$PATH`)
|
||||
3. In the `swift-async-algorithms` directory run `swift build` or `swift test` accordingly
|
||||
|
||||
### Building with Swift 5.6
|
||||
|
||||
1. `git checkout swift-5.6`
|
||||
2. run `swift build` or `swift test` accordingly
|
||||
|
||||
## Source Stability
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# ``AsyncAlgorithms``
|
||||
|
||||
**Swift Async Algorithms** is an open-source package of asynchronous sequence and advanced algorithms that involve concurrency, along with their related types.
|
||||
|
||||
## Overview
|
||||
|
||||
This package has three main goals:
|
||||
|
||||
- First-class integration with `async/await`
|
||||
- Provide a home for time-based algorithms
|
||||
- Be cross-platform and open source
|
||||
|
||||
## Topics
|
||||
|
||||
### Getting Started
|
||||
|
||||
- <doc:AdjacentPairs>
|
||||
- <doc:BufferedBytes>
|
||||
- <doc:Chain>
|
||||
- <doc:Channel>
|
||||
- <doc:Chunked>
|
||||
- <doc:Collections>
|
||||
- <doc:CombineLatest>
|
||||
- <doc:Compacted>
|
||||
- <doc:Debounce>
|
||||
- <doc:Effects>
|
||||
- <doc:Intersperse>
|
||||
- <doc:Joined>
|
||||
- <doc:Lazy>
|
||||
- <doc:Merge>
|
||||
- <doc:Reductions>
|
||||
- <doc:RemoveDuplicates>
|
||||
- <doc:Select>
|
||||
- <doc:Throttle>
|
||||
- <doc:Timer>
|
||||
- <doc:Zip>
|
||||
File renamed without changes.
+1
-1
@@ -17,7 +17,7 @@ struct AsyncBytes: AsyncSequence {
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> AsyncBufferedByteIterator {
|
||||
return BufferedAsyncByteIterator(capacity: 16384) { buffer in
|
||||
return AsyncBufferedByteIterator(capacity: 16384) { buffer in
|
||||
// This runs once every 16384 invocations of next()
|
||||
return try await handle.read(into: buffer)
|
||||
}
|
||||
@@ -9,8 +9,8 @@ This operation is available for all `AsyncSequence` types who share the same `El
|
||||
|
||||
```swift
|
||||
let preamble = [
|
||||
"// Some header to add as a preamble"
|
||||
"//"
|
||||
"// Some header to add as a preamble",
|
||||
"//",
|
||||
""
|
||||
].async
|
||||
let lines = chain(preamble, URL(fileURLWithPath: "/tmp/Sample.swift").lines)
|
||||
@@ -60,7 +60,7 @@ extension AsyncChain3Sequence.Iterator: Sendable where Base1.AsyncIterator: Send
|
||||
|
||||
The `chain(_:...)` function takes two or more sequences as arguments.
|
||||
|
||||
The resulting `AsyncChainSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments conform.
|
||||
The resulting `AsyncChainSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments also conform to it.
|
||||
|
||||
When any of the asynchronous sequences being chained together come to their end of iteration, the `AsyncChainSequence` iteration proceeds to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration, the `AsyncChainSequence` then ends its iteration.
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
## Proposed Solution
|
||||
|
||||
To achieve a system that supports back pressure and allows for the communication of more than one value from one task to another we are introducing a new type, the _channel_. The channel will be a reference-type asynchronous sequence with an asynchronous sending capability that awaits the consumption of iteration. Each value sent by the channel, or finish transmitted, will await the consumption of that value or event by iteration. That awaiting behavior will allow for the affordance of back pressure applied from the consumption site to be transmitted to the production site. This means that the rate of production cannot exceed the rate of consumption, and that the rate of consumption cannot exceed the rate of production.
|
||||
To achieve a system that supports back pressure and allows for the communication of more than one value from one task to another we are introducing a new type, the _channel_. The channel will be a reference-type asynchronous sequence with an asynchronous sending capability that awaits the consumption of iteration. Each value sent by the channel will await the consumption of that value by iteration. That awaiting behavior will allow for the affordance of back pressure applied from the consumption site to be transmitted to the production site. This means that the rate of production cannot exceed the rate of consumption, and that the rate of consumption cannot exceed the rate of production. Sending a terminal event to the channel will instantly resume all pending operations for every producers and consumers.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
@@ -31,7 +31,7 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
public init(element elementType: Element.Type = Element.self)
|
||||
|
||||
public func send(_ element: Element) async
|
||||
public func finish() async
|
||||
public func finish()
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
@@ -45,13 +45,13 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
|
||||
public func send(_ element: Element) async
|
||||
public func fail(_ error: Error) async where Failure == Error
|
||||
public func finish() async
|
||||
public func finish()
|
||||
|
||||
public func makeAsyncIterator() -> Iterator
|
||||
}
|
||||
```
|
||||
|
||||
Channels are intended to be used as communication types between tasks. Particularly when one task produces values and another task consumes said values. The back pressure applied by `send(_:)`, `fail(_:)` and `finish()` via the suspension/resume ensure that the production of values does not exceed the consumption of values from iteration. Each of these methods suspend after enqueuing the event and are resumed when the next call to `next()` on the `Iterator` is made.
|
||||
Channels are intended to be used as communication types between tasks. Particularly when one task produces values and another task consumes said values. On the one hand, the back pressure applied by `send(_:)` and `fail(_:)` via the suspension/resume ensure that the production of values does not exceed the consumption of values from iteration. Each of these methods suspend after enqueuing the event and are resumed when the next call to `next()` on the `Iterator` is made. On the other hand, the call to `finish()` immediately resumes all the pending operations for every producers and consumers. Thus, every suspended `send(_:)` operations instantly resume, so as every suspended `next()` operations by producing a nil value, indicating the termination of the iterations. Further calls to `send(_:)` will immediately resume.
|
||||
|
||||
```swift
|
||||
let channel = AsyncChannel<String>()
|
||||
@@ -59,7 +59,7 @@ Task {
|
||||
while let resultOfLongCalculation = doLongCalculations() {
|
||||
await channel.send(resultOfLongCalculation)
|
||||
}
|
||||
await channel.finish()
|
||||
channel.finish()
|
||||
}
|
||||
|
||||
for await calculationResult in channel {
|
||||
File renamed without changes.
+2
-2
@@ -7,7 +7,7 @@
|
||||
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/RangeReplaceableCollection.swift),
|
||||
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/SetAlgebra.swift) |
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestDictionary.swift),
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRangeReplacableCollection.swift),
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRangeReplaceableCollection.swift),
|
||||
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestSetAlgebra.swift),
|
||||
]
|
||||
|
||||
@@ -22,7 +22,7 @@ This type of functionality can be useful for examples and testing, and also for
|
||||
|
||||
Three categories of initializers will be added to provide initializers for those three primary types: `Array`, `Dictionary` and `Set`. However these initializers can be written in a generic fashion such that they can apply to all similar collections.
|
||||
|
||||
`RangeReplaceableCollection` will gain a new that constructs a collection given an `AsyncSequence`. This will allow for creating arrays from asynchronous sequences but also allow for creating types like `Data` or `ContiguousArray`. Because of the nature of asynchronous sequences, this initializer must be asynchronous and declare that it rethrows errors from the base asynchronous sequence.
|
||||
`RangeReplaceableCollection` will gain a new initializer that constructs a collection given an `AsyncSequence`. This will allow for creating arrays from asynchronous sequences but also allow for creating types like `Data` or `ContiguousArray`. Because of the nature of asynchronous sequences, this initializer must be asynchronous and declare that it rethrows errors from the base asynchronous sequence.
|
||||
|
||||
```swift
|
||||
extension RangeReplaceableCollection {
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -6,10 +6,10 @@
|
||||
Merges two or more asynchronous sequences sharing the same element type into one singular asynchronous sequence.
|
||||
|
||||
```swift
|
||||
let appleFeed = URL("http://www.example.com/ticker?symbol=AAPL").lines.map { "AAPL: " + $0 }
|
||||
let nasdaqFeed = URL("http://www.example.com/ticker?symbol=^IXIC").lines.map { "^IXIC: " + $0 }
|
||||
let appleFeed = URL(string: "http://www.example.com/ticker?symbol=AAPL")!.lines.map { "AAPL: " + $0 }
|
||||
let nasdaqFeed = URL(string:"http://www.example.com/ticker?symbol=^IXIC")!.lines.map { "^IXIC: " + $0 }
|
||||
|
||||
for try await ticker = merge(appleFeed, nasdaqFeed) {
|
||||
for try await ticker in merge(appleFeed, nasdaqFeed) {
|
||||
print(ticker)
|
||||
}
|
||||
```
|
||||
File renamed without changes.
File renamed without changes.
@@ -50,5 +50,4 @@ This means that `withTaskGroup` is highly suited to run work in parallel, wherea
|
||||
## Future Directions
|
||||
|
||||
|
||||
|
||||
## Credits/Inspiration
|
||||
@@ -77,6 +77,8 @@ extension AsyncThrottleSequence.Iterator: Sendable
|
||||
|
||||
The `AsyncThrottleSequence` and its `Iterator` are conditionally `Sendable` if the base types comprising it are `Sendable`.
|
||||
|
||||
The time in which events are measured are from the previous emission if present. If a duration has elapsed between the last emission and the point in time the throttle is measured then that duration is counted as elapsed. The first element is considered not throttled because no interval can be constructed from the start to the first element.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
It was considered to only provide the "latest" style APIs, however the reduction version grants more flexibility and can act as a funnel to the implementations of `latest`.
|
||||
File renamed without changes.
File renamed without changes.
@@ -234,8 +234,8 @@ public struct AsyncBufferSequence<Base: AsyncSequence, Buffer: AsyncBuffer> wher
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncBufferSequence: Sendable where Base: Sendable, Base.AsyncIterator: Sendable, Base.Element: Sendable { }
|
||||
extension AsyncBufferSequence.Iterator: Sendable where Base: Sendable, Base.AsyncIterator: Sendable, Base.Element: Sendable { }
|
||||
extension AsyncBufferSequence: Sendable where Base: Sendable { }
|
||||
extension AsyncBufferSequence.Iterator: Sendable where Base: Sendable { }
|
||||
|
||||
extension AsyncBufferSequence: AsyncSequence {
|
||||
public typealias Element = Buffer.Output
|
||||
|
||||
@@ -110,6 +110,24 @@ internal struct _AsyncBytesBuffer: @unchecked Sendable {
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
// If two tasks have access to this iterator then the references on
|
||||
// the storage will be non uniquely owned. This means that any reload
|
||||
// must happen into it's own fresh buffer. The consumption of those
|
||||
// bytes between two tasks are inherently defined as potential
|
||||
// duplication by the nature of sending that buffer across the two
|
||||
// tasks - this means that the brief period in which they may be
|
||||
// sharing non reloaded bytes is to be expected; basically in that
|
||||
// edge case of making the iterator and sending that across to two
|
||||
// places to iterate is asking for something bizzare and the answer
|
||||
// should not be crash, but it definitely cannot be consistent.
|
||||
//
|
||||
// The unique ref check is here to prevent the potentials of a crashing
|
||||
// secnario.
|
||||
if !isKnownUniquelyReferenced(&storage) {
|
||||
// The count is not mutated across invocations so the access is safe.
|
||||
let capacity = storage.buffer.count
|
||||
storage = Storage(capacity: capacity)
|
||||
}
|
||||
let readSize: Int = try await readFunction(storage.buffer)
|
||||
if readSize == 0 {
|
||||
finished = true
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
///
|
||||
/// The `AsyncChannel` class is intended to be used as a communication type between tasks,
|
||||
/// particularly when one task produces values and another task consumes those values. The back
|
||||
/// pressure applied by `send(_:)` and `finish()` via the suspension/resume ensure that
|
||||
/// the production of values does not exceed the consumption of values from iteration. Each of these
|
||||
/// methods suspends after enqueuing the event and is resumed when the next call to `next()`
|
||||
/// on the `Iterator` is made.
|
||||
/// pressure applied by `send(_:)` and `finish()` via the suspension/resume ensures that
|
||||
/// the production of values does not exceed the consumption of values from iteration. Each of these
|
||||
/// methods suspends after enqueuing the event and is resumed when the next call to `next()`
|
||||
/// on the `Iterator` is made.
|
||||
public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
/// The iterator for a `AsyncChannel` instance.
|
||||
public struct Iterator: AsyncIteratorProtocol, Sendable {
|
||||
@@ -89,7 +89,11 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
switch self {
|
||||
case .awaiting(var awaiting):
|
||||
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
|
||||
self = .awaiting(awaiting)
|
||||
if awaiting.isEmpty {
|
||||
self = .idle
|
||||
} else {
|
||||
self = .awaiting(awaiting)
|
||||
}
|
||||
return continuation
|
||||
case .idle:
|
||||
self = .awaiting([Awaiting(cancelled: generation)])
|
||||
@@ -127,7 +131,12 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
func next(_ generation: Int) async -> Element? {
|
||||
return await withUnsafeContinuation { continuation in
|
||||
var cancelled = false
|
||||
var terminal = false
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
|
||||
if state.terminal {
|
||||
terminal = true
|
||||
return nil
|
||||
}
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)])
|
||||
@@ -145,62 +154,86 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
nexts.remove(Awaiting(placeholder: generation))
|
||||
cancelled = true
|
||||
}
|
||||
state.emission = .awaiting(nexts)
|
||||
if nexts.isEmpty {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}?.resume()
|
||||
if cancelled {
|
||||
if cancelled || terminal {
|
||||
continuation.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _send(_ result: Result<Element?, Never>) async {
|
||||
let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
|
||||
if state.terminal {
|
||||
return UnsafeResumption(continuation: continuation, success: nil)
|
||||
}
|
||||
switch result {
|
||||
case .success(let value):
|
||||
if value == nil {
|
||||
state.terminal = true
|
||||
}
|
||||
case .failure:
|
||||
state.terminal = true
|
||||
}
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .pending([continuation])
|
||||
return nil
|
||||
case .pending(var sends):
|
||||
sends.append(continuation)
|
||||
state.emission = .pending(sends)
|
||||
return nil
|
||||
case .awaiting(var nexts):
|
||||
let next = nexts.removeFirst().continuation
|
||||
if nexts.count == 0 {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
}?.resume()
|
||||
func finishAll() {
|
||||
let (sends, nexts) = state.withCriticalRegion { state -> ([UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>], Set<Awaiting>) in
|
||||
if state.terminal {
|
||||
return ([], [])
|
||||
}
|
||||
state.terminal = true
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
return ([], [])
|
||||
case .pending(let nexts):
|
||||
state.emission = .idle
|
||||
return (nexts, [])
|
||||
case .awaiting(let nexts):
|
||||
state.emission = .idle
|
||||
return ([], nexts)
|
||||
}
|
||||
}
|
||||
for send in sends {
|
||||
send.resume(returning: nil)
|
||||
}
|
||||
for next in nexts {
|
||||
next.continuation?.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
|
||||
func _send(_ element: Element) async {
|
||||
await withTaskCancellationHandler {
|
||||
finishAll()
|
||||
} operation: {
|
||||
let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
|
||||
if state.terminal {
|
||||
return UnsafeResumption(continuation: continuation, success: nil)
|
||||
}
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .pending([continuation])
|
||||
return nil
|
||||
case .pending(var sends):
|
||||
sends.append(continuation)
|
||||
state.emission = .pending(sends)
|
||||
return nil
|
||||
case .awaiting(var nexts):
|
||||
let next = nexts.removeFirst().continuation
|
||||
if nexts.count == 0 {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
}?.resume()
|
||||
}
|
||||
continuation?.resume(returning: element)
|
||||
}
|
||||
continuation?.resume(with: result)
|
||||
}
|
||||
|
||||
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
|
||||
/// If the channel is already finished then this returns immediately
|
||||
public func send(_ element: Element) async {
|
||||
await _send(.success(element))
|
||||
await _send(element)
|
||||
}
|
||||
|
||||
/// Send a finish to an awaiting iteration. This function will resume when the next call to `next()` is made.
|
||||
/// If the channel is already finished then this returns immediately
|
||||
public func finish() async {
|
||||
await _send(.success(nil))
|
||||
/// Send a finish to all awaiting iterations.
|
||||
public func finish() {
|
||||
finishAll()
|
||||
}
|
||||
|
||||
/// Create an `Iterator` for iteration of an `AsyncChannel`
|
||||
|
||||
@@ -37,6 +37,7 @@ extension AsyncSequence {
|
||||
/// error, `AsyncChunkedByGroupSequence` will rethrow that error immediately and discard
|
||||
/// any current group.
|
||||
///
|
||||
/// let numbers = [10, 20, 30, 10, 40, 40, 10, 20].async
|
||||
/// let chunks = numbers.chunked { $0 <= $1 }
|
||||
/// for await numberChunk in chunks {
|
||||
/// print(numberChunk)
|
||||
|
||||
@@ -31,25 +31,25 @@ extension AsyncSequence {
|
||||
}
|
||||
|
||||
/// Creates an asynchronous sequence that creates chunks of a given `RangeReplaceableCollection` type of a given count or when an `AsyncTimerSequence` fires.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func chunks<C: Clock, Collected: RangeReplaceableCollection>(ofCount count: Int, or timer: AsyncTimerSequence<C>, into: Collected.Type) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
|
||||
AsyncChunksOfCountOrSignalSequence(self, count: count, signal: timer)
|
||||
}
|
||||
|
||||
/// Creates an asynchronous sequence that creates chunks of a given count or when an `AsyncTimerSequence` fires.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func chunks<C: Clock>(ofCount count: Int, or timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountOrSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
|
||||
chunks(ofCount: count, or: timer, into: [Element].self)
|
||||
}
|
||||
|
||||
/// Creates an asynchronous sequence that creates chunks of a given `RangeReplaceableCollection` type when an `AsyncTimerSequence` fires.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func chunked<C: Clock, Collected: RangeReplaceableCollection>(by timer: AsyncTimerSequence<C>, into: Collected.Type) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
|
||||
AsyncChunksOfCountOrSignalSequence(self, count: nil, signal: timer)
|
||||
}
|
||||
|
||||
/// Creates an asynchronous sequence that creates chunks when an `AsyncTimerSequence` fires.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func chunked<C: Clock>(by timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountOrSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
|
||||
chunked(by: timer, into: [Element].self)
|
||||
}
|
||||
|
||||
@@ -12,14 +12,14 @@
|
||||
extension AsyncSequence {
|
||||
/// Creates an asynchronous sequence that emits the latest element after a given quiescence period
|
||||
/// has elapsed by using a specified Clock.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func debounce<C: Clock>(for interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncDebounceSequence<Self, C> {
|
||||
AsyncDebounceSequence(self, interval: interval, tolerance: tolerance, clock: clock)
|
||||
}
|
||||
|
||||
/// Creates an asynchronous sequence that emits the latest element after a given quiescence period
|
||||
/// has elapsed.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func debounce(for interval: Duration, tolerance: Duration? = nil) -> AsyncDebounceSequence<Self, ContinuousClock> {
|
||||
debounce(for: interval, tolerance: tolerance, clock: .continuous)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ extension AsyncSequence {
|
||||
|
||||
/// An `AsyncSequence` that emits the latest element after a given quiescence period
|
||||
/// has elapsed.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable
|
||||
where Base.AsyncIterator: Sendable, Base.Element: Sendable, Base: Sendable {
|
||||
let base: Base
|
||||
@@ -43,7 +43,7 @@ public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncDebounceSequence: AsyncSequence {
|
||||
public typealias Element = Base.Element
|
||||
|
||||
|
||||
@@ -11,19 +11,19 @@
|
||||
|
||||
extension AsyncSequence {
|
||||
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func throttle<C: Clock, Reduced>(for interval: C.Instant.Duration, clock: C, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> AsyncThrottleSequence<Self, C, Reduced> {
|
||||
AsyncThrottleSequence(self, interval: interval, clock: clock, reducing: reducing)
|
||||
}
|
||||
|
||||
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func throttle<Reduced>(for interval: Duration, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> AsyncThrottleSequence<Self, ContinuousClock, Reduced> {
|
||||
throttle(for: interval, clock: .continuous, reducing: reducing)
|
||||
}
|
||||
|
||||
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func throttle<C: Clock>(for interval: C.Instant.Duration, clock: C, latest: Bool = true) -> AsyncThrottleSequence<Self, C, Element> {
|
||||
throttle(for: interval, clock: clock) { previous, element in
|
||||
if latest {
|
||||
@@ -35,14 +35,14 @@ extension AsyncSequence {
|
||||
}
|
||||
|
||||
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public func throttle(for interval: Duration, latest: Bool = true) -> AsyncThrottleSequence<Self, ContinuousClock, Element> {
|
||||
throttle(for: interval, clock: .continuous, latest: latest)
|
||||
}
|
||||
}
|
||||
|
||||
/// A rate-limited `AsyncSequence` by emitting values at most every specified interval.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
|
||||
let base: Base
|
||||
let interval: C.Instant.Duration
|
||||
@@ -57,13 +57,14 @@ public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncThrottleSequence: AsyncSequence {
|
||||
public typealias Element = Reduced
|
||||
|
||||
/// The iterator for an `AsyncThrottleSequence` instance.
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
var base: Base.AsyncIterator
|
||||
var last: C.Instant?
|
||||
let interval: C.Instant.Duration
|
||||
let clock: C
|
||||
let reducing: @Sendable (Reduced?, Base.Element) async -> Reduced
|
||||
@@ -77,13 +78,15 @@ extension AsyncThrottleSequence: AsyncSequence {
|
||||
|
||||
public mutating func next() async rethrows -> Reduced? {
|
||||
var reduced: Reduced?
|
||||
let start = clock.now
|
||||
let start = last ?? clock.now
|
||||
repeat {
|
||||
guard let element = try await base.next() else {
|
||||
return nil
|
||||
}
|
||||
let reduction = await reducing(reduced, element)
|
||||
if start.duration(to: clock.now) >= interval {
|
||||
let now = clock.now
|
||||
if start.duration(to: now) >= interval || last == nil {
|
||||
last = now
|
||||
return reduction
|
||||
} else {
|
||||
reduced = reduction
|
||||
@@ -97,8 +100,8 @@ extension AsyncThrottleSequence: AsyncSequence {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncThrottleSequence: Sendable where Base: Sendable, Element: Sendable { }
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncThrottleSequence.Iterator: Sendable where Base.AsyncIterator: Sendable { }
|
||||
@@ -88,7 +88,11 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
switch self {
|
||||
case .awaiting(var awaiting):
|
||||
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
|
||||
self = .awaiting(awaiting)
|
||||
if awaiting.isEmpty {
|
||||
self = .idle
|
||||
} else {
|
||||
self = .awaiting(awaiting)
|
||||
}
|
||||
return continuation
|
||||
case .idle:
|
||||
self = .awaiting([Awaiting(cancelled: generation)])
|
||||
@@ -125,7 +129,12 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
func next(_ generation: Int) async throws -> Element? {
|
||||
return try await withUnsafeThrowingContinuation { continuation in
|
||||
var cancelled = false
|
||||
var terminal = false
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
|
||||
if state.terminal {
|
||||
terminal = true
|
||||
return nil
|
||||
}
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)])
|
||||
@@ -143,50 +152,80 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
nexts.remove(Awaiting(placeholder: generation))
|
||||
cancelled = true
|
||||
}
|
||||
state.emission = .awaiting(nexts)
|
||||
if nexts.isEmpty {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}?.resume()
|
||||
if cancelled {
|
||||
if cancelled || terminal {
|
||||
continuation.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _send(_ result: Result<Element?, Error>) async {
|
||||
let continuation: UnsafeContinuation<Element?, Error>? = await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
|
||||
if state.terminal {
|
||||
return UnsafeResumption(continuation: continuation, success: nil)
|
||||
}
|
||||
switch result {
|
||||
case .success(let value):
|
||||
if value == nil {
|
||||
func finishAll() {
|
||||
let (sends, nexts) = state.withCriticalRegion { state -> ([UnsafeContinuation<UnsafeContinuation<Element?, Error>?, Never>], Set<Awaiting>) in
|
||||
if state.terminal {
|
||||
return ([], [])
|
||||
}
|
||||
state.terminal = true
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
return ([], [])
|
||||
case .pending(let nexts):
|
||||
state.emission = .idle
|
||||
return (nexts, [])
|
||||
case .awaiting(let nexts):
|
||||
state.emission = .idle
|
||||
return ([], nexts)
|
||||
}
|
||||
}
|
||||
for send in sends {
|
||||
send.resume(returning: nil)
|
||||
}
|
||||
for next in nexts {
|
||||
next.continuation?.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
|
||||
func _send(_ result: Result<Element, Error>) async {
|
||||
await withTaskCancellationHandler {
|
||||
finishAll()
|
||||
} operation: {
|
||||
let continuation: UnsafeContinuation<Element?, Error>? = await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
|
||||
if state.terminal {
|
||||
return UnsafeResumption(continuation: continuation, success: nil)
|
||||
}
|
||||
|
||||
if case .failure = result {
|
||||
state.terminal = true
|
||||
}
|
||||
case .failure:
|
||||
state.terminal = true
|
||||
}
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .pending([continuation])
|
||||
return nil
|
||||
case .pending(var sends):
|
||||
sends.append(continuation)
|
||||
state.emission = .pending(sends)
|
||||
return nil
|
||||
case .awaiting(var nexts):
|
||||
let next = nexts.removeFirst().continuation
|
||||
if nexts.count == 0 {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
|
||||
switch state.emission {
|
||||
case .idle:
|
||||
state.emission = .pending([continuation])
|
||||
return nil
|
||||
case .pending(var sends):
|
||||
sends.append(continuation)
|
||||
state.emission = .pending(sends)
|
||||
return nil
|
||||
case .awaiting(var nexts):
|
||||
let next = nexts.removeFirst().continuation
|
||||
if nexts.count == 0 {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
}?.resume()
|
||||
}?.resume()
|
||||
}
|
||||
continuation?.resume(with: result.map { $0 as Element? })
|
||||
}
|
||||
continuation?.resume(with: result)
|
||||
}
|
||||
|
||||
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
|
||||
@@ -201,10 +240,9 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
await _send(.failure(error))
|
||||
}
|
||||
|
||||
/// Send a finish to an awaiting iteration. This function will resume when the next call to `next()` is made.
|
||||
/// If the channel is already finished then this returns immediately
|
||||
public func finish() async {
|
||||
await _send(.success(nil))
|
||||
/// Send a finish to all awaiting iterations.
|
||||
public func finish() {
|
||||
finishAll()
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// An `AsyncSequence` that produces elements at regular intervals.
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
|
||||
public typealias Element = C.Instant
|
||||
|
||||
@@ -71,7 +71,7 @@ public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncTimerSequence {
|
||||
/// Create an `AsyncTimerSequence` with a given repeating interval.
|
||||
public static func repeating(every interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncTimerSequence<C> {
|
||||
@@ -79,7 +79,7 @@ extension AsyncTimerSequence {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncTimerSequence where C == SuspendingClock {
|
||||
/// Create an `AsyncTimerSequence` with a given repeating interval.
|
||||
public static func repeating(every interval: Duration, tolerance: Duration? = nil) -> AsyncTimerSequence<SuspendingClock> {
|
||||
@@ -87,8 +87,8 @@ extension AsyncTimerSequence where C == SuspendingClock {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncTimerSequence: Sendable { }
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncTimerSequence.Iterator: Sendable { }
|
||||
File renamed without changes.
+14
@@ -0,0 +1,14 @@
|
||||
# ``AsyncSequenceValidation``
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
Testing is a critical area of focus for any package to make it robust, catch bugs, and explain the expected behaviors in a documented manner. Testing things that are asynchronous can be difficult, testing things that are asynchronous multiple times can be even more difficult.
|
||||
|
||||
Types that implement `AsyncSequence` can often be described in deterministic actions given particular inputs. For the inputs, the events can be described as a discrete set: values, errors being thrown, the terminal state of returning a `nil` value from the iterator, or advancing in time and not doing anything. Likewise, the expected output has a discrete set of events: values, errors being caught, the terminal state of receiving a `nil` value from the iterator, or advancing in time and not doing anything.
|
||||
|
||||
## Topics
|
||||
|
||||
### Getting Started
|
||||
|
||||
- <doc:Validation>
|
||||
File renamed without changes.
@@ -11,7 +11,6 @@
|
||||
|
||||
import _CAsyncSequenceValidationSupport
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@resultBuilder
|
||||
public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
public struct Component<T> {
|
||||
@@ -97,15 +96,20 @@ public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
}
|
||||
|
||||
let queue: WorkQueue
|
||||
let _clock: Clock
|
||||
|
||||
public var inputs: InputList
|
||||
public let clock: Clock
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
public var clock: Clock {
|
||||
_clock
|
||||
}
|
||||
|
||||
internal init() {
|
||||
let queue = WorkQueue()
|
||||
self.queue = queue
|
||||
self.inputs = InputList(queue: queue)
|
||||
self.clock = Clock(queue: queue)
|
||||
self._clock = Clock(queue: queue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
import AsyncAlgorithms
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct Clock {
|
||||
let queue: WorkQueue
|
||||
@@ -22,8 +21,20 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock: Clock {
|
||||
|
||||
public protocol TestClock: Sendable {
|
||||
associatedtype Instant: TestInstant
|
||||
|
||||
var now: Instant { get }
|
||||
|
||||
func sleep(until deadline: Self.Instant, tolerance: Self.Instant.Duration?) async throws
|
||||
}
|
||||
|
||||
public protocol TestInstant: Equatable {
|
||||
associatedtype Duration
|
||||
}
|
||||
|
||||
extension AsyncSequenceValidationDiagram.Clock {
|
||||
public struct Step: DurationProtocol, Hashable, CustomStringConvertible {
|
||||
internal var rawValue: Int
|
||||
|
||||
@@ -66,7 +77,7 @@ extension AsyncSequenceValidationDiagram.Clock: Clock {
|
||||
}
|
||||
}
|
||||
|
||||
public struct Instant: InstantProtocol, CustomStringConvertible {
|
||||
public struct Instant: CustomStringConvertible {
|
||||
public typealias Duration = Step
|
||||
|
||||
let when: Step
|
||||
@@ -111,3 +122,13 @@ extension AsyncSequenceValidationDiagram.Clock: Clock {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: TestInstant { }
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock.Instant: InstantProtocol { }
|
||||
|
||||
extension AsyncSequenceValidationDiagram.Clock: TestClock { }
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock: Clock { }
|
||||
@@ -9,7 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
struct Failure: Error, Equatable { }
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct ExpectationResult: Sendable {
|
||||
public struct Event: Sendable {
|
||||
@@ -42,7 +41,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
|
||||
func reconstitute<Theme: AsyncSequenceValidationTheme>(_ events: [Clock.Instant : [Result<String?, Error>]], theme: Theme, end: Clock.Instant) -> String {
|
||||
var now = Clock.Instant(when: .zero)
|
||||
var now = Clock.Instant(when: .steps(1)) // adjust for the offset index
|
||||
var reconstituted = ""
|
||||
while now <= end {
|
||||
if let results = events[now] {
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct Specification: Sendable {
|
||||
public let specification: String
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
import _CAsyncSequenceValidationSupport
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
struct Job: Hashable, @unchecked Sendable {
|
||||
let job: JobRef
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ import _CAsyncSequenceValidationSupport
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
func start_thread(_ raw: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
|
||||
Unmanaged<TaskDriver>.fromOpaque(raw).takeRetainedValue().run()
|
||||
return nil
|
||||
@@ -34,7 +33,6 @@ func start_thread(_ raw: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? {
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
final class TaskDriver {
|
||||
let work: (TaskDriver) -> Void
|
||||
let queue: WorkQueue
|
||||
|
||||
@@ -19,22 +19,20 @@ internal func _swiftJobRun(
|
||||
_ executor: UnownedSerialExecutor
|
||||
) -> ()
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public protocol AsyncSequenceValidationTest: Sendable {
|
||||
var inputs: [AsyncSequenceValidationDiagram.Specification] { get }
|
||||
var output: AsyncSequenceValidationDiagram.Specification { get }
|
||||
|
||||
func test<C: Clock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
|
||||
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
struct Test<Operation: AsyncSequence>: AsyncSequenceValidationTest, @unchecked Sendable where Operation.Element == String {
|
||||
let inputs: [Specification]
|
||||
let sequence: Operation
|
||||
let output: Specification
|
||||
|
||||
func test<C: _Concurrency.Clock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
|
||||
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
do {
|
||||
for tick in activeTicks {
|
||||
@@ -265,7 +263,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
@AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test
|
||||
) throws -> (ExpectationResult, [ExpectationFailure]) {
|
||||
let diagram = AsyncSequenceValidationDiagram()
|
||||
let clock = diagram.clock
|
||||
let clock = diagram._clock
|
||||
let test = build(diagram)
|
||||
for index in 0..<test.inputs.count {
|
||||
// fault in all inputs
|
||||
|
||||
@@ -9,21 +9,18 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public protocol AsyncSequenceValidationTheme {
|
||||
func token(_ character: Character, inValue: Bool) -> AsyncSequenceValidationDiagram.Token
|
||||
|
||||
func description(for token: AsyncSequenceValidationDiagram.Token) -> String
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationTheme where Self == AsyncSequenceValidationDiagram.ASCIITheme {
|
||||
public static var ascii: AsyncSequenceValidationDiagram.ASCIITheme {
|
||||
return AsyncSequenceValidationDiagram.ASCIITheme()
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public enum Token: Sendable {
|
||||
case step
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
struct WorkQueue: Sendable {
|
||||
enum Item: CustomStringConvertible, Comparable {
|
||||
case blocked(Token, AsyncSequenceValidationDiagram.Clock.Instant, UnsafeContinuation<Void, Error>)
|
||||
|
||||
@@ -13,13 +13,16 @@
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestChannel: XCTestCase {
|
||||
func test_channel() async {
|
||||
func test_asyncChannel_delivers_values_when_two_producers_and_two_consumers() async {
|
||||
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
|
||||
let expected = Set([sentFromProducer1, sentFromProducer2])
|
||||
|
||||
let channel = AsyncChannel<String>()
|
||||
Task {
|
||||
await channel.send("test1")
|
||||
await channel.send(sentFromProducer1)
|
||||
}
|
||||
Task {
|
||||
await channel.send("test2")
|
||||
await channel.send(sentFromProducer2)
|
||||
}
|
||||
|
||||
let t: Task<String?, Never> = Task {
|
||||
@@ -28,13 +31,17 @@ final class TestChannel: XCTestCase {
|
||||
return value
|
||||
}
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let value = await iterator.next()
|
||||
let other = await t.value
|
||||
|
||||
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
|
||||
|
||||
let (collectedFromConsumer1, collectedFromConsumer2) = (await t.value, await iterator.next())
|
||||
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
|
||||
|
||||
XCTAssertEqual(collected, expected)
|
||||
}
|
||||
|
||||
func test_throwing_channel() async throws {
|
||||
func test_asyncThrowingChannel_delivers_values_when_two_producers_and_two_consumers() async throws {
|
||||
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
|
||||
let expected = Set([sentFromProducer1, sentFromProducer2])
|
||||
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
Task {
|
||||
await channel.send("test1")
|
||||
@@ -49,13 +56,14 @@ final class TestChannel: XCTestCase {
|
||||
return value
|
||||
}
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let value = try await iterator.next()
|
||||
let other = try await t.value
|
||||
|
||||
let (collectedFromConsumer1, collectedFromConsumer2) = (try await t.value, try await iterator.next())
|
||||
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
|
||||
|
||||
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
|
||||
XCTAssertEqual(collected, expected)
|
||||
}
|
||||
|
||||
func test_throwing() async {
|
||||
func test_asyncThrowingChannel_throws_when_fail_is_called() async {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
Task {
|
||||
await channel.fail(Failure())
|
||||
@@ -63,37 +71,170 @@ final class TestChannel: XCTestCase {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
do {
|
||||
let _ = try await iterator.next()
|
||||
XCTFail()
|
||||
XCTFail("The AsyncThrowingChannel should have thrown")
|
||||
} catch {
|
||||
XCTAssertEqual(error as? Failure, Failure())
|
||||
}
|
||||
}
|
||||
|
||||
func test_send_finish() async {
|
||||
|
||||
func test_asyncChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called() async {
|
||||
let channel = AsyncChannel<String>()
|
||||
let complete = ManagedCriticalState(false)
|
||||
let finished = expectation(description: "finished")
|
||||
|
||||
Task {
|
||||
await channel.finish()
|
||||
channel.finish()
|
||||
complete.withCriticalRegion { $0 = true }
|
||||
finished.fulfill()
|
||||
}
|
||||
XCTAssertFalse(complete.withCriticalRegion { $0 })
|
||||
let value = ManagedCriticalState<String?>(nil)
|
||||
|
||||
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
|
||||
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
|
||||
|
||||
let received = expectation(description: "received")
|
||||
received.expectedFulfillmentCount = 2
|
||||
|
||||
let pastEnd = expectation(description: "pastEnd")
|
||||
pastEnd.expectedFulfillmentCount = 2
|
||||
|
||||
Task {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = await iterator.next()
|
||||
value.withCriticalRegion { $0 = ending }
|
||||
valueFromConsumer1.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
Task {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = await iterator.next()
|
||||
valueFromConsumer2.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
wait(for: [finished, received], timeout: 1.0)
|
||||
|
||||
XCTAssertTrue(complete.withCriticalRegion { $0 })
|
||||
XCTAssertEqual(value.withCriticalRegion { $0 }, nil)
|
||||
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
|
||||
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
|
||||
|
||||
wait(for: [pastEnd], timeout: 1.0)
|
||||
let additionalSend = expectation(description: "additional send")
|
||||
Task {
|
||||
await channel.send("test")
|
||||
additionalSend.fulfill()
|
||||
}
|
||||
wait(for: [additionalSend], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_asyncChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called2() async throws {
|
||||
let channel = AsyncChannel<String>()
|
||||
let complete = ManagedCriticalState(false)
|
||||
let finished = expectation(description: "finished")
|
||||
|
||||
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
|
||||
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
|
||||
|
||||
let received = expectation(description: "received")
|
||||
received.expectedFulfillmentCount = 2
|
||||
|
||||
let pastEnd = expectation(description: "pastEnd")
|
||||
pastEnd.expectedFulfillmentCount = 2
|
||||
|
||||
Task(priority: .high) {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = await iterator.next()
|
||||
valueFromConsumer1.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
Task(priority: .high) {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = await iterator.next()
|
||||
valueFromConsumer2.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
try await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
|
||||
Task(priority: .low) {
|
||||
channel.finish()
|
||||
complete.withCriticalRegion { $0 = true }
|
||||
finished.fulfill()
|
||||
}
|
||||
|
||||
wait(for: [finished, received], timeout: 1.0)
|
||||
|
||||
XCTAssertTrue(complete.withCriticalRegion { $0 })
|
||||
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
|
||||
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
|
||||
|
||||
wait(for: [pastEnd], timeout: 1.0)
|
||||
let additionalSend = expectation(description: "additional send")
|
||||
Task {
|
||||
await channel.send("test")
|
||||
additionalSend.fulfill()
|
||||
}
|
||||
wait(for: [additionalSend], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_asyncThrowingChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called() async {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
let complete = ManagedCriticalState(false)
|
||||
let finished = expectation(description: "finished")
|
||||
|
||||
Task {
|
||||
channel.finish()
|
||||
complete.withCriticalRegion { $0 = true }
|
||||
finished.fulfill()
|
||||
}
|
||||
|
||||
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
|
||||
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
|
||||
|
||||
let received = expectation(description: "received")
|
||||
received.expectedFulfillmentCount = 2
|
||||
|
||||
let pastEnd = expectation(description: "pastEnd")
|
||||
pastEnd.expectedFulfillmentCount = 2
|
||||
|
||||
Task {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = try await iterator.next()
|
||||
valueFromConsumer1.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = try await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
Task {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
let ending = try await iterator.next()
|
||||
valueFromConsumer2.withCriticalRegion { $0 = ending }
|
||||
received.fulfill()
|
||||
let item = try await iterator.next()
|
||||
XCTAssertNil(item)
|
||||
pastEnd.fulfill()
|
||||
}
|
||||
|
||||
wait(for: [finished, received], timeout: 1.0)
|
||||
|
||||
XCTAssertTrue(complete.withCriticalRegion { $0 })
|
||||
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
|
||||
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
|
||||
|
||||
wait(for: [pastEnd], timeout: 1.0)
|
||||
let additionalSend = expectation(description: "additional send")
|
||||
Task {
|
||||
@@ -103,7 +244,7 @@ final class TestChannel: XCTestCase {
|
||||
wait(for: [additionalSend], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_cancellation() async {
|
||||
func test_asyncChannel_ends_iterator_when_task_is_cancelled() async {
|
||||
let channel = AsyncChannel<String>()
|
||||
let ready = expectation(description: "ready")
|
||||
let task: Task<String?, Never> = Task {
|
||||
@@ -116,8 +257,8 @@ final class TestChannel: XCTestCase {
|
||||
let value = await task.value
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
func test_cancellation_throwing() async throws {
|
||||
|
||||
func test_asyncThrowingChannel_ends_iterator_when_task_is_cancelled() async throws {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
let ready = expectation(description: "ready")
|
||||
let task: Task<String?, Error> = Task {
|
||||
@@ -130,4 +271,34 @@ final class TestChannel: XCTestCase {
|
||||
let value = try await task.value
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
func test_asyncChannel_resumes_send_when_task_is_cancelled() async {
|
||||
let channel = AsyncChannel<Int>()
|
||||
let notYetDone = expectation(description: "not yet done")
|
||||
notYetDone.isInverted = true
|
||||
let done = expectation(description: "done")
|
||||
let task = Task {
|
||||
await channel.send(1)
|
||||
notYetDone.fulfill()
|
||||
done.fulfill()
|
||||
}
|
||||
wait(for: [notYetDone], timeout: 0.1)
|
||||
task.cancel()
|
||||
wait(for: [done], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_asyncThrowingChannel_resumes_send_when_task_is_cancelled() async {
|
||||
let channel = AsyncThrowingChannel<Int, Error>()
|
||||
let notYetDone = expectation(description: "not yet done")
|
||||
notYetDone.isInverted = true
|
||||
let done = expectation(description: "done")
|
||||
let task = Task {
|
||||
await channel.send(1)
|
||||
notYetDone.fulfill()
|
||||
done.fulfill()
|
||||
}
|
||||
wait(for: [notYetDone], timeout: 0.1)
|
||||
task.cancel()
|
||||
wait(for: [done], timeout: 1.0)
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,6 @@ func concatCharacters(_ array: [String]) -> String {
|
||||
}
|
||||
|
||||
final class TestChunk: XCTestCase {
|
||||
|
||||
func test_signal_equalChunks() {
|
||||
validate {
|
||||
"ABC- DEF- GHI- |"
|
||||
@@ -113,7 +112,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_equalChunks() {
|
||||
func test_time_equalChunks() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"ABC- DEF- GHI- |"
|
||||
$0.inputs[0].chunked(by: .repeating(every: .steps(4), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -121,7 +121,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_unequalChunks() {
|
||||
func test_time_unequalChunks() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"AB------ A------- ABCDEFG- |"
|
||||
$0.inputs[0].chunked(by: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -129,7 +130,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_emptyChunks() {
|
||||
func test_time_emptyChunks() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"-- 1- --|"
|
||||
$0.inputs[0].chunked(by: .repeating(every: .steps(2), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -137,7 +139,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_error() {
|
||||
func test_time_error() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"AB^"
|
||||
$0.inputs[0].chunked(by: .repeating(every: .steps(5), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -145,7 +148,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_unsignaledTrailingChunk() {
|
||||
func test_time_unsignaledTrailingChunk() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"111-111|"
|
||||
$0.inputs[0].chunked(by: .repeating(every: .steps(4), clock: $0.clock)).map(sumCharacters)
|
||||
@@ -153,7 +157,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_timeAlwaysPrevails() {
|
||||
func test_timeAndCount_timeAlwaysPrevails() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"AB------ A------- ABCDEFG- |"
|
||||
$0.inputs[0].chunks(ofCount: 42, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -161,7 +166,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countAlwaysPrevails() {
|
||||
func test_timeAndCount_countAlwaysPrevails() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"AB --A-B -|"
|
||||
$0.inputs[0].chunks(ofCount: 2, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -169,7 +175,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countResetsAfterCount() {
|
||||
func test_timeAndCount_countResetsAfterCount() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"ABCDE --- ABCDE |"
|
||||
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -177,7 +184,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countResetsAfterSignal() {
|
||||
func test_timeAndCount_countResetsAfterSignal() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"AB------ ABCDE |"
|
||||
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
@@ -185,7 +193,8 @@ final class TestChunk: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_error() {
|
||||
func test_timeAndCount_error() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"ABC^"
|
||||
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestCompacted: XCTestCase {
|
||||
func test_compacting() async {
|
||||
func test_compacted_is_equivalent_to_compactMap_when_input_as_nil_elements() async {
|
||||
let source = [1, 2, nil, 3, 4, nil, 5]
|
||||
let expected = source.compactMap { $0 }
|
||||
let sequence = source.async.compacted()
|
||||
@@ -24,7 +24,7 @@ final class TestCompacted: XCTestCase {
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_compacting_past_end() async {
|
||||
func test_compacted_produces_nil_next_element_when_iteration_is_finished() async {
|
||||
let source = [1, 2, nil, 3, 4, nil, 5]
|
||||
let expected = source.compactMap { $0 }
|
||||
let sequence = source.async.compacted()
|
||||
@@ -38,7 +38,7 @@ final class TestCompacted: XCTestCase {
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_compactingNonNils() async {
|
||||
func test_compacted_is_equivalent_to_compactMap_when_input_as_no_nil_elements() async {
|
||||
let source: [Int?] = [1, 2, 3, 4, 5]
|
||||
let expected = source.compactMap { $0 }
|
||||
let sequence = source.async.compacted()
|
||||
@@ -49,7 +49,7 @@ final class TestCompacted: XCTestCase {
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_throwing() async throws {
|
||||
func test_compacted_throws_when_root_sequence_throws() async throws {
|
||||
let sequence = [1, nil, 3, 4, 5, nil, 7].async.map { try throwOn(4, $0) }.compacted()
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
var collected = [Int]()
|
||||
@@ -66,7 +66,7 @@ final class TestCompacted: XCTestCase {
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_cancellation() async {
|
||||
func test_compacted_finishes_when_iteration_task_is_cancelled() async {
|
||||
let value: String? = "test"
|
||||
let source = Indefinite(value: value)
|
||||
let sequence = source.async.compacted()
|
||||
|
||||
@@ -13,7 +13,8 @@ import XCTest
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestDebounce: XCTestCase {
|
||||
func test_delayingValues() {
|
||||
func test_delayingValues() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcd----e---f-g----|"
|
||||
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
|
||||
@@ -21,7 +22,8 @@ final class TestDebounce: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_delayingValues_dangling_last() {
|
||||
func test_delayingValues_dangling_last() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcd----e---f-g-|"
|
||||
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
|
||||
@@ -30,7 +32,8 @@ final class TestDebounce: XCTestCase {
|
||||
}
|
||||
|
||||
|
||||
func test_finishDoesntDebounce() {
|
||||
func test_finishDoesntDebounce() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"a|"
|
||||
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
|
||||
@@ -38,7 +41,8 @@ final class TestDebounce: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_throwDoesntDebounce() {
|
||||
func test_throwDoesntDebounce() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"a^"
|
||||
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
|
||||
@@ -46,7 +50,8 @@ final class TestDebounce: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_noValues() {
|
||||
func test_noValues() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"----|"
|
||||
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
import XCTest
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestRangeReplacableCollection: XCTestCase {
|
||||
final class TestRangeReplaceableCollection: XCTestCase {
|
||||
func test_String() async {
|
||||
let source = "abc"
|
||||
let expected = source
|
||||
@@ -18,7 +18,11 @@ final class TestTaskSelect: XCTestCase {
|
||||
let firstValue = await Task.select(Task {
|
||||
return 1
|
||||
}, Task {
|
||||
try! await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
|
||||
try! await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
} else {
|
||||
try! await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
return 2
|
||||
}).value
|
||||
XCTAssertEqual(firstValue, 1)
|
||||
@@ -26,7 +30,11 @@ final class TestTaskSelect: XCTestCase {
|
||||
|
||||
func test_second() async {
|
||||
let firstValue = await Task.select(Task {
|
||||
try! await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
|
||||
try! await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
} else {
|
||||
try! await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
return 1
|
||||
}, Task {
|
||||
return 2
|
||||
@@ -37,7 +45,11 @@ final class TestTaskSelect: XCTestCase {
|
||||
func test_throwing() async {
|
||||
do {
|
||||
_ = try await Task.select(Task { () async throws -> Int in
|
||||
try await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
|
||||
try await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
} else {
|
||||
try await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
return 1
|
||||
}, Task { () async throws -> Int in
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil)
|
||||
@@ -59,7 +71,11 @@ final class TestTaskSelect: XCTestCase {
|
||||
firstCancelled.fulfill()
|
||||
} operation: { () -> Int in
|
||||
firstReady.fulfill()
|
||||
try? await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
|
||||
try? await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
} else {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}, Task {
|
||||
@@ -67,7 +83,11 @@ final class TestTaskSelect: XCTestCase {
|
||||
secondCancelled.fulfill()
|
||||
} operation: { () -> Int in
|
||||
secondReady.fulfill()
|
||||
try? await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) {
|
||||
try? await Task.sleep(until: .now + .seconds(2), clock: .continuous)
|
||||
} else {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
})
|
||||
|
||||
@@ -13,7 +13,8 @@ import XCTest
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestThrottle: XCTestCase {
|
||||
func test_rate_0() {
|
||||
func test_rate_0() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(0), clock: $0.clock)
|
||||
@@ -21,7 +22,8 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_0_leading_edge() {
|
||||
func test_rate_0_leading_edge() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(0), clock: $0.clock, latest: false)
|
||||
@@ -29,7 +31,8 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_1() {
|
||||
func test_rate_1() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(1), clock: $0.clock)
|
||||
@@ -37,7 +40,8 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_1_leading_edge() {
|
||||
func test_rate_1_leading_edge() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(1), clock: $0.clock, latest: false)
|
||||
@@ -45,55 +49,62 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_2() {
|
||||
func test_rate_2() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
"-b-d-f-h-j-|"
|
||||
"a-c-e-g-i-k|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_2_leading_edge() {
|
||||
func test_rate_2_leading_edge() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
|
||||
"-a-c-e-g-i-|"
|
||||
"a-b-d-f-h-j|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_3() {
|
||||
func test_rate_3() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock)
|
||||
"--c--f--i--|"
|
||||
"a--d--g--j-|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_rate_3_leading_edge() {
|
||||
func test_rate_3_leading_edge() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock, latest: false)
|
||||
"--a--d--g--|"
|
||||
"a--b--e--h-|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_throwing() {
|
||||
func test_throwing() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdef^hijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
"-b-d-f^"
|
||||
"a-c-e-^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_throwing_leading_edge() {
|
||||
func test_throwing_leading_edge() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"abcdef^hijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
|
||||
"-a-c-e^"
|
||||
"a-b-d-^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_emission_2_rate_1() {
|
||||
func test_emission_2_rate_1() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"-a-b-c-d-e-f-g-h-i-j-k-|"
|
||||
$0.inputs[0].throttle(for: .steps(1), clock: $0.clock)
|
||||
@@ -101,7 +112,8 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_emission_2_rate_2() {
|
||||
func test_emission_2_rate_2() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"-a-b-c-d-e-f-g-h-i-j-k-|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
@@ -109,7 +121,8 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_emission_3_rate_2() {
|
||||
func test_emission_3_rate_2() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"--a--b--c--d--e--f--g|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
@@ -117,11 +130,12 @@ final class TestThrottle: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_emission_2_rate_3() {
|
||||
func test_emission_2_rate_3() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"-a-b-c-d-e-f-g-h-i-j-k-|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock)
|
||||
"---b---d---f---h---j---|"
|
||||
"-a---c---e---g---i---k-|"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,28 +14,32 @@ import AsyncAlgorithms
|
||||
import AsyncSequenceValidation
|
||||
|
||||
final class TestTimer: XCTestCase {
|
||||
func test_tick1() {
|
||||
func test_tick1() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
AsyncTimerSequence(interval: .steps(1), clock: $0.clock).map { _ in "x" }
|
||||
"xxxxxxx[;|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_tick2() {
|
||||
func test_tick2() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
AsyncTimerSequence(interval: .steps(2), clock: $0.clock).map { _ in "x" }
|
||||
"-x-x-x-[;|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_tick3() {
|
||||
func test_tick3() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
AsyncTimerSequence(interval: .steps(3), clock: $0.clock).map { _ in "x" }
|
||||
"--x--x-[;|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_tick2_event_skew3() {
|
||||
func test_tick2_event_skew3() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate { diagram in
|
||||
AsyncTimerSequence(interval: .steps(2), clock: diagram.clock).map { [diagram] (_) -> String in
|
||||
try? await diagram.clock.sleep(until: diagram.clock.now.advanced(by: .steps(3)))
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import XCTest
|
||||
import AsyncAlgorithms
|
||||
import AsyncSequenceValidation
|
||||
@testable import AsyncAlgorithms_XCTest
|
||||
|
||||
final class TestValidationDiagram: XCTestCase {
|
||||
func test_diagram() {
|
||||
@@ -291,7 +292,8 @@ final class TestValidationDiagram: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_delayNext_into_emptyTick() {
|
||||
func test_delayNext_into_emptyTick() throws {
|
||||
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
|
||||
validate {
|
||||
"xx|"
|
||||
LaggingAsyncSequence($0.inputs[0], delayBy: .steps(3), using: $0.clock)
|
||||
@@ -308,6 +310,7 @@ final class TestValidationDiagram: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
struct LaggingAsyncSequence<Base: AsyncSequence, C: Clock> : AsyncSequence {
|
||||
typealias Element = Base.Element
|
||||
|
||||
|
||||
@@ -13,111 +13,129 @@
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestZip2: XCTestCase {
|
||||
func test_zip() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
let actual = await Array(zip(a.async, b.async))
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_zip_first_longer() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
|
||||
let a = [1, 2, 3, 4, 5]
|
||||
let b = ["a", "b", "c"]
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
let actual = await Array(zip(a.async, b.async))
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_zip_second_longer() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c", "d", "e"]
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
let actual = await Array(zip(a.async, b.async))
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_iterate_past_end() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let sequence = zip(a.async, b.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
var collected = [(Int, String)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_iterate_past_end_first_longer() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
|
||||
let a = [1, 2, 3, 4, 5]
|
||||
let b = ["a", "b", "c"]
|
||||
let sequence = zip(a.async, b.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
var collected = [(Int, String)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_iterate_past_end_second_longer() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c", "d", "e"]
|
||||
let sequence = zip(a.async, b.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = Array(zip(a, b))
|
||||
var collected = [(Int, String)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_first_throwing() async throws {
|
||||
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let sequence = zip(a.async.map { try throwOn(2, $0) }, b.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a")]
|
||||
var collected = [(Int, String)]()
|
||||
do {
|
||||
while let item = try await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTFail()
|
||||
XCTFail("Zipped sequence should throw after one collected element")
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual([(1, "a")], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_second_throwing() async throws {
|
||||
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let sequence = zip(a.async, b.async.map { try throwOn("b", $0) })
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a")]
|
||||
var collected = [(Int, String)]()
|
||||
do {
|
||||
while let item = try await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTFail()
|
||||
XCTFail("Zipped sequence should throw after one collected element")
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual([(1, "a")], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_cancellation() async {
|
||||
func test_zip_finishes_when_iteration_task_is_cancelled() async {
|
||||
let source1 = Indefinite(value: "test1")
|
||||
let source2 = Indefinite(value: "test2")
|
||||
let sequence = zip(source1.async, source2.async)
|
||||
@@ -143,159 +161,188 @@ final class TestZip2: XCTestCase {
|
||||
}
|
||||
|
||||
final class TestZip3: XCTestCase {
|
||||
func test_zip() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
let actual = await Array(zip(a.async, b.async, c.async))
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_zip_first_longer() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
|
||||
let a = [1, 2, 3, 4, 5]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
let actual = await Array(zip(a.async, b.async, c.async))
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_zip_second_longer() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c", "d", "e"]
|
||||
let c = [1, 2, 3]
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
let actual = await Array(zip(a.async, b.async, c.async))
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_zip_third_longer() async {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_third_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3, 4, 5]
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
let actual = await Array(zip(a.async, b.async, c.async))
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
XCTAssertEqual(expected, actual)
|
||||
}
|
||||
|
||||
func test_iterate_past_end() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async, b.async, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_iterate_past_end_first_longer() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
|
||||
let a = [1, 2, 3, 4, 5]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async, b.async, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_iterate_past_end_second_longer() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c", "d", "e"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async, b.async, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_iterate_past_end_third_longer() async {
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_third_is_longer() async {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3, 4, 5]
|
||||
let sequence = zip(a.async, b.async, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
while let item = await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_first_throwing() async throws {
|
||||
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async.map { try throwOn(2, $0) }, b.async, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
do {
|
||||
while let item = try await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTFail()
|
||||
XCTFail("Zipped sequence should throw after one collected element")
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_second_throwing() async throws {
|
||||
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async, b.async.map { try throwOn("b", $0) }, c.async)
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
do {
|
||||
while let item = try await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTFail()
|
||||
XCTFail("Zipped sequence should throw after one collected element")
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_third_throwing() async throws {
|
||||
func test_zip_produces_one_element_and_throws_when_third_produces_one_element_and_throws() async throws {
|
||||
let a = [1, 2, 3]
|
||||
let b = ["a", "b", "c"]
|
||||
let c = [1, 2, 3]
|
||||
let sequence = zip(a.async, b.async, c.async.map { try throwOn(2, $0) })
|
||||
var iterator = sequence.makeAsyncIterator()
|
||||
|
||||
let expected = [(1, "a", 1)]
|
||||
var collected = [(Int, String, Int)]()
|
||||
do {
|
||||
while let item = try await iterator.next() {
|
||||
collected.append(item)
|
||||
}
|
||||
XCTFail()
|
||||
XCTFail("Zipped sequence should throw after one collected element")
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_cancellation() async {
|
||||
func test_zip_finishes_when_iteration_task_is_cancelled() async {
|
||||
let source1 = Indefinite(value: "test1")
|
||||
let source2 = Indefinite(value: "test2")
|
||||
let source3 = Indefinite(value: "test3")
|
||||
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# This source file is part of the Swift.org 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
|
||||
# See https://swift.org/CONTRIBUTORS.txt for Swift project authors
|
||||
#
|
||||
# Updates the GitHub Pages documentation site thats published from the 'docs'
|
||||
# subdirectory in the 'gh-pages' branch of this repository.
|
||||
#
|
||||
# This script should be run by someone with commit access to the 'gh-pages' branch
|
||||
# at a regular frequency so that the documentation content on the GitHub Pages site
|
||||
# is up-to-date with the content in this repo.
|
||||
#
|
||||
|
||||
export BUILDING_FOR_DOCUMENTATION_GENERATION=1
|
||||
|
||||
set -eu
|
||||
|
||||
# A `realpath` alternative using the default C implementation.
|
||||
filepath() {
|
||||
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
|
||||
}
|
||||
|
||||
SWIFT_ASYNC_ALGORITHMS_ROOT="$(dirname $(dirname $(filepath $0)))"
|
||||
|
||||
ASYNC_ALGORITHMS_BUILD_DIR="$SWIFT_ASYNC_ALGORITHMS_ROOT"/.build/async-algorithms-gh-pages-build
|
||||
|
||||
# Set current directory to the repository root
|
||||
cd "$SWIFT_ASYNC_ALGORITHMS_ROOT"
|
||||
|
||||
# Use git worktree to checkout the gh-pages branch of this repository in a gh-pages sub-directory
|
||||
git fetch
|
||||
git worktree add --checkout gh-pages origin/gh-pages
|
||||
|
||||
# Pretty print DocC JSON output so that it can be consistently diffed between commits
|
||||
export DOCC_JSON_PRETTYPRINT="YES"
|
||||
|
||||
# Generate documentation for the 'AsyncAlgorithms' target and output it
|
||||
# to the /docs subdirectory in the gh-pages worktree directory.
|
||||
swift package \
|
||||
--allow-writing-to-directory "$SWIFT_ASYNC_ALGORITHMS_ROOT/gh-pages/docs" \
|
||||
generate-documentation \
|
||||
--target AsyncAlgorithms \
|
||||
--disable-indexing \
|
||||
--transform-for-static-hosting \
|
||||
--hosting-base-path swift-async-algorithms \
|
||||
--output-path "$SWIFT_ASYNC_ALGORITHMS_ROOT/gh-pages/docs"
|
||||
|
||||
# Save the current commit we've just built documentation from in a variable
|
||||
CURRENT_COMMIT_HASH=`git rev-parse --short HEAD`
|
||||
|
||||
# Commit and push our changes to the gh-pages branch
|
||||
cd gh-pages
|
||||
git add docs
|
||||
|
||||
if [ -n "$(git status --porcelain)" ]; then
|
||||
echo "Documentation changes found. Commiting the changes to the 'gh-pages' branch and pushing to origin."
|
||||
git commit -m "Update GitHub Pages documentation site to $CURRENT_COMMIT_HASH"
|
||||
git push origin HEAD:gh-pages
|
||||
else
|
||||
# No changes found, nothing to commit.
|
||||
echo "No documentation changes found."
|
||||
fi
|
||||
|
||||
# Delete the git worktree we created
|
||||
cd ..
|
||||
git worktree remove gh-pages
|
||||
Reference in new issue
Block a user