mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-23 04:14:23 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90e26aa898 |
No files matched your search
@@ -1,110 +0,0 @@
|
||||
# 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.
|
||||
|
||||
File renamed without changes.
+1
-1
@@ -17,7 +17,7 @@ struct AsyncBytes: AsyncSequence {
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> AsyncBufferedByteIterator {
|
||||
return AsyncBufferedByteIterator(capacity: 16384) { buffer in
|
||||
return BufferedAsyncByteIterator(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 also conform to it.
|
||||
The resulting `AsyncChainSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments conform.
|
||||
|
||||
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 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.
|
||||
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.
|
||||
|
||||
## 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()
|
||||
public func finish() async
|
||||
|
||||
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()
|
||||
public func finish() async
|
||||
|
||||
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. 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.
|
||||
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.
|
||||
|
||||
```swift
|
||||
let channel = AsyncChannel<String>()
|
||||
@@ -59,7 +59,7 @@ Task {
|
||||
while let resultOfLongCalculation = doLongCalculations() {
|
||||
await channel.send(resultOfLongCalculation)
|
||||
}
|
||||
channel.finish()
|
||||
await 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/TestRangeReplaceableCollection.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/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 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.
|
||||
`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.
|
||||
|
||||
```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(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 }
|
||||
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 }
|
||||
|
||||
for try await ticker in merge(appleFeed, nasdaqFeed) {
|
||||
for try await ticker = merge(appleFeed, nasdaqFeed) {
|
||||
print(ticker)
|
||||
}
|
||||
```
|
||||
File renamed without changes.
File renamed without changes.
@@ -50,4 +50,5 @@ This means that `withTaskGroup` is highly suited to run work in parallel, wherea
|
||||
## Future Directions
|
||||
|
||||
|
||||
|
||||
## Credits/Inspiration
|
||||
@@ -77,8 +77,6 @@ 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.
File renamed without changes.
+2
-26
@@ -13,8 +13,7 @@ let package = Package(
|
||||
products: [
|
||||
.library(name: "AsyncAlgorithms", targets: ["AsyncAlgorithms"]),
|
||||
.library(name: "AsyncSequenceValidation", targets: ["AsyncSequenceValidation"]),
|
||||
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"]),
|
||||
.library(name: "AsyncAlgorithms_XCTest", targets: ["AsyncAlgorithms_XCTest"]),
|
||||
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"])
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
@@ -23,17 +22,9 @@ let package = Package(
|
||||
name: "AsyncSequenceValidation",
|
||||
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"]),
|
||||
.systemLibrary(name: "_CAsyncSequenceValidationSupport"),
|
||||
.target(
|
||||
name: "AsyncAlgorithms_XCTest",
|
||||
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"],
|
||||
swiftSettings: [
|
||||
.unsafeFlags([
|
||||
"-Xfrontend", "-disable-availability-checking"
|
||||
])
|
||||
]),
|
||||
.testTarget(
|
||||
name: "AsyncAlgorithmsTests",
|
||||
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation", "AsyncAlgorithms_XCTest"],
|
||||
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation"],
|
||||
swiftSettings: [
|
||||
.unsafeFlags([
|
||||
"-Xfrontend", "-disable-availability-checking"
|
||||
@@ -41,18 +32,3 @@ let package = Package(
|
||||
]),
|
||||
]
|
||||
)
|
||||
|
||||
#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,5 +1,6 @@
|
||||
# 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:
|
||||
@@ -20,53 +21,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/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.
|
||||
- [`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.
|
||||
|
||||
#### Creating asynchronous sequences
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### Performance optimized asynchronous iterators
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### Other useful asynchronous sequences
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### Asynchronous Sequences that transact in time
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### Obtaining all values from an asynchronous sequence
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
|
||||
#### Task management
|
||||
|
||||
- [`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.
|
||||
- [`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.
|
||||
|
||||
#### 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/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/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/Guides/Effects.md).
|
||||
|
||||
## Adding Swift Async Algorithms as a Dependency
|
||||
## Adding Swift 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:
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# ``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>
|
||||
@@ -234,8 +234,8 @@ public struct AsyncBufferSequence<Base: AsyncSequence, Buffer: AsyncBuffer> wher
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncBufferSequence: Sendable where Base: Sendable { }
|
||||
extension AsyncBufferSequence.Iterator: Sendable where Base: Sendable { }
|
||||
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: AsyncSequence {
|
||||
public typealias Element = Buffer.Output
|
||||
|
||||
@@ -110,24 +110,6 @@ 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 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.
|
||||
/// 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.
|
||||
public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
/// The iterator for a `AsyncChannel` instance.
|
||||
public struct Iterator: AsyncIteratorProtocol, Sendable {
|
||||
@@ -89,11 +89,7 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
switch self {
|
||||
case .awaiting(var awaiting):
|
||||
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
|
||||
if awaiting.isEmpty {
|
||||
self = .idle
|
||||
} else {
|
||||
self = .awaiting(awaiting)
|
||||
}
|
||||
self = .awaiting(awaiting)
|
||||
return continuation
|
||||
case .idle:
|
||||
self = .awaiting([Awaiting(cancelled: generation)])
|
||||
@@ -131,12 +127,7 @@ 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)])
|
||||
@@ -154,86 +145,62 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
|
||||
nexts.remove(Awaiting(placeholder: generation))
|
||||
cancelled = true
|
||||
}
|
||||
if nexts.isEmpty {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
state.emission = .awaiting(nexts)
|
||||
return nil
|
||||
}
|
||||
}?.resume()
|
||||
if cancelled || terminal {
|
||||
if cancelled {
|
||||
continuation.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
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
|
||||
}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}?.resume()
|
||||
}
|
||||
continuation?.resume(returning: element)
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
}?.resume()
|
||||
}
|
||||
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(element)
|
||||
await _send(.success(element))
|
||||
}
|
||||
|
||||
/// Send a finish to all awaiting iterations.
|
||||
public func finish() {
|
||||
finishAll()
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// Create an `Iterator` for iteration of an `AsyncChannel`
|
||||
|
||||
@@ -37,7 +37,6 @@ 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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
|
||||
let base: Base
|
||||
let interval: C.Instant.Duration
|
||||
@@ -57,14 +57,13 @@ public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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
|
||||
@@ -78,15 +77,13 @@ extension AsyncThrottleSequence: AsyncSequence {
|
||||
|
||||
public mutating func next() async rethrows -> Reduced? {
|
||||
var reduced: Reduced?
|
||||
let start = last ?? clock.now
|
||||
let start = clock.now
|
||||
repeat {
|
||||
guard let element = try await base.next() else {
|
||||
return nil
|
||||
}
|
||||
let reduction = await reducing(reduced, element)
|
||||
let now = clock.now
|
||||
if start.duration(to: now) >= interval || last == nil {
|
||||
last = now
|
||||
if start.duration(to: clock.now) >= interval {
|
||||
return reduction
|
||||
} else {
|
||||
reduced = reduction
|
||||
@@ -100,8 +97,8 @@ extension AsyncThrottleSequence: AsyncSequence {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncThrottleSequence: Sendable where Base: Sendable, Element: Sendable { }
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncThrottleSequence.Iterator: Sendable where Base.AsyncIterator: Sendable { }
|
||||
@@ -88,11 +88,7 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
switch self {
|
||||
case .awaiting(var awaiting):
|
||||
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
|
||||
if awaiting.isEmpty {
|
||||
self = .idle
|
||||
} else {
|
||||
self = .awaiting(awaiting)
|
||||
}
|
||||
self = .awaiting(awaiting)
|
||||
return continuation
|
||||
case .idle:
|
||||
self = .awaiting([Awaiting(cancelled: generation)])
|
||||
@@ -129,12 +125,7 @@ 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)])
|
||||
@@ -152,80 +143,50 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
nexts.remove(Awaiting(placeholder: generation))
|
||||
cancelled = true
|
||||
}
|
||||
if nexts.isEmpty {
|
||||
state.emission = .idle
|
||||
} else {
|
||||
state.emission = .awaiting(nexts)
|
||||
}
|
||||
state.emission = .awaiting(nexts)
|
||||
return nil
|
||||
}
|
||||
}?.resume()
|
||||
if cancelled || terminal {
|
||||
if cancelled {
|
||||
continuation.resume(returning: 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 {
|
||||
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 {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}?.resume()
|
||||
}
|
||||
continuation?.resume(with: result.map { $0 as Element? })
|
||||
return UnsafeResumption(continuation: continuation, success: next)
|
||||
}
|
||||
}?.resume()
|
||||
}
|
||||
continuation?.resume(with: result)
|
||||
}
|
||||
|
||||
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
|
||||
@@ -240,9 +201,10 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
|
||||
await _send(.failure(error))
|
||||
}
|
||||
|
||||
/// Send a finish to all awaiting iterations.
|
||||
public func finish() {
|
||||
finishAll()
|
||||
/// 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))
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// An `AsyncSequence` that produces elements at regular intervals.
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
|
||||
public typealias Element = C.Instant
|
||||
|
||||
@@ -71,7 +71,7 @@ public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncTimerSequence: Sendable { }
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncTimerSequence.Iterator: Sendable { }
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
# ``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>
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
import _CAsyncSequenceValidationSupport
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
@resultBuilder
|
||||
public struct AsyncSequenceValidationDiagram : Sendable {
|
||||
public struct Component<T> {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
import AsyncAlgorithms
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct Clock {
|
||||
let queue: WorkQueue
|
||||
@@ -22,7 +22,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram.Clock: Clock {
|
||||
public struct Step: DurationProtocol, Hashable, CustomStringConvertible {
|
||||
internal var rawValue: Int
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
struct Failure: Error, Equatable { }
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct ExpectationResult: Sendable {
|
||||
public struct Event: Sendable {
|
||||
@@ -42,7 +42,7 @@ extension AsyncSequenceValidationDiagram {
|
||||
}
|
||||
|
||||
func reconstitute<Theme: AsyncSequenceValidationTheme>(_ events: [Clock.Instant : [Result<String?, Error>]], theme: Theme, end: Clock.Instant) -> String {
|
||||
var now = Clock.Instant(when: .steps(1)) // adjust for the offset index
|
||||
var now = Clock.Instant(when: .zero)
|
||||
var reconstituted = ""
|
||||
while now <= end {
|
||||
if let results = events[now] {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public struct Specification: Sendable {
|
||||
public let specification: String
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
import _CAsyncSequenceValidationSupport
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
struct Job: Hashable, @unchecked Sendable {
|
||||
let job: JobRef
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import _CAsyncSequenceValidationSupport
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@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 +34,7 @@ func start_thread(_ raw: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? {
|
||||
#error("TODO: Port TaskDriver threading to windows")
|
||||
#endif
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
final class TaskDriver {
|
||||
let work: (TaskDriver) -> Void
|
||||
let queue: WorkQueue
|
||||
|
||||
@@ -19,7 +19,7 @@ internal func _swiftJobRun(
|
||||
_ executor: UnownedSerialExecutor
|
||||
) -> ()
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public protocol AsyncSequenceValidationTest: Sendable {
|
||||
var inputs: [AsyncSequenceValidationDiagram.Specification] { get }
|
||||
var output: AsyncSequenceValidationDiagram.Specification { get }
|
||||
@@ -27,7 +27,7 @@ public protocol AsyncSequenceValidationTest: Sendable {
|
||||
func test<C: Clock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
|
||||
}
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@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]
|
||||
|
||||
@@ -9,21 +9,21 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@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 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
extension AsyncSequenceValidationDiagram {
|
||||
public enum Token: Sendable {
|
||||
case step
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
|
||||
@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>)
|
||||
|
||||
File renamed without changes.
@@ -13,16 +13,13 @@
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestChannel: XCTestCase {
|
||||
func test_asyncChannel_delivers_values_when_two_producers_and_two_consumers() async {
|
||||
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
|
||||
let expected = Set([sentFromProducer1, sentFromProducer2])
|
||||
|
||||
func test_channel() async {
|
||||
let channel = AsyncChannel<String>()
|
||||
Task {
|
||||
await channel.send(sentFromProducer1)
|
||||
await channel.send("test1")
|
||||
}
|
||||
Task {
|
||||
await channel.send(sentFromProducer2)
|
||||
await channel.send("test2")
|
||||
}
|
||||
|
||||
let t: Task<String?, Never> = Task {
|
||||
@@ -31,17 +28,13 @@ final class TestChannel: XCTestCase {
|
||||
return value
|
||||
}
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
|
||||
let (collectedFromConsumer1, collectedFromConsumer2) = (await t.value, await iterator.next())
|
||||
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
|
||||
|
||||
XCTAssertEqual(collected, expected)
|
||||
let value = await iterator.next()
|
||||
let other = await t.value
|
||||
|
||||
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
|
||||
}
|
||||
|
||||
func test_asyncThrowingChannel_delivers_values_when_two_producers_and_two_consumers() async throws {
|
||||
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
|
||||
let expected = Set([sentFromProducer1, sentFromProducer2])
|
||||
|
||||
func test_throwing_channel() async throws {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
Task {
|
||||
await channel.send("test1")
|
||||
@@ -56,14 +49,13 @@ final class TestChannel: XCTestCase {
|
||||
return value
|
||||
}
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
|
||||
let (collectedFromConsumer1, collectedFromConsumer2) = (try await t.value, try await iterator.next())
|
||||
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
|
||||
let value = try await iterator.next()
|
||||
let other = try await t.value
|
||||
|
||||
XCTAssertEqual(collected, expected)
|
||||
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
|
||||
}
|
||||
|
||||
func test_asyncThrowingChannel_throws_when_fail_is_called() async {
|
||||
func test_throwing() async {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
Task {
|
||||
await channel.fail(Failure())
|
||||
@@ -71,170 +63,37 @@ final class TestChannel: XCTestCase {
|
||||
var iterator = channel.makeAsyncIterator()
|
||||
do {
|
||||
let _ = try await iterator.next()
|
||||
XCTFail("The AsyncThrowingChannel should have thrown")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(error as? Failure, Failure())
|
||||
}
|
||||
}
|
||||
|
||||
func test_asyncChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called() async {
|
||||
|
||||
func test_send_finish() async {
|
||||
let channel = AsyncChannel<String>()
|
||||
let complete = ManagedCriticalState(false)
|
||||
let finished = expectation(description: "finished")
|
||||
|
||||
Task {
|
||||
channel.finish()
|
||||
await channel.finish()
|
||||
complete.withCriticalRegion { $0 = true }
|
||||
finished.fulfill()
|
||||
}
|
||||
|
||||
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
|
||||
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
|
||||
|
||||
XCTAssertFalse(complete.withCriticalRegion { $0 })
|
||||
let value = 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()
|
||||
valueFromConsumer1.withCriticalRegion { $0 = ending }
|
||||
value.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(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)
|
||||
|
||||
XCTAssertEqual(value.withCriticalRegion { $0 }, nil)
|
||||
wait(for: [pastEnd], timeout: 1.0)
|
||||
let additionalSend = expectation(description: "additional send")
|
||||
Task {
|
||||
@@ -244,7 +103,7 @@ final class TestChannel: XCTestCase {
|
||||
wait(for: [additionalSend], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_asyncChannel_ends_iterator_when_task_is_cancelled() async {
|
||||
func test_cancellation() async {
|
||||
let channel = AsyncChannel<String>()
|
||||
let ready = expectation(description: "ready")
|
||||
let task: Task<String?, Never> = Task {
|
||||
@@ -257,8 +116,8 @@ final class TestChannel: XCTestCase {
|
||||
let value = await task.value
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
|
||||
func test_asyncThrowingChannel_ends_iterator_when_task_is_cancelled() async throws {
|
||||
|
||||
func test_cancellation_throwing() async throws {
|
||||
let channel = AsyncThrowingChannel<String, Error>()
|
||||
let ready = expectation(description: "ready")
|
||||
let task: Task<String?, Error> = Task {
|
||||
@@ -271,34 +130,4 @@ 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)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
import XCTest
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestRangeReplaceableCollection: XCTestCase {
|
||||
final class TestRangeReplacableCollection: XCTestCase {
|
||||
func test_String() async {
|
||||
let source = "abc"
|
||||
let expected = source
|
||||
@@ -49,7 +49,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
"a-c-e-g-i-k|"
|
||||
"-b-d-f-h-j-|"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
|
||||
"a-b-d-f-h-j|"
|
||||
"-a-c-e-g-i-|"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock)
|
||||
"a--d--g--j-|"
|
||||
"--c--f--i--|"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdefghijk|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock, latest: false)
|
||||
"a--b--e--h-|"
|
||||
"--a--d--g--|"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdef^hijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
|
||||
"a-c-e-^"
|
||||
"-b-d-f^"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"abcdef^hijk|"
|
||||
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
|
||||
"a-b-d-^"
|
||||
"-a-c-e^"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ final class TestThrottle: XCTestCase {
|
||||
validate {
|
||||
"-a-b-c-d-e-f-g-h-i-j-k-|"
|
||||
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock)
|
||||
"-a---c---e---g---i---k-|"
|
||||
"---b---d---f---h---j---|"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@
|
||||
import XCTest
|
||||
import AsyncAlgorithms
|
||||
import AsyncSequenceValidation
|
||||
@testable import AsyncAlgorithms_XCTest
|
||||
|
||||
final class TestValidationDiagram: XCTestCase {
|
||||
func test_diagram() {
|
||||
|
||||
@@ -13,129 +13,111 @@
|
||||
import AsyncAlgorithms
|
||||
|
||||
final class TestZip2: XCTestCase {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
|
||||
func test_zip() 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_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
|
||||
func test_zip_first_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_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
|
||||
func test_zip_second_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_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
|
||||
func test_iterate_past_end() 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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
|
||||
func test_iterate_past_end_first_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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
|
||||
func test_iterate_past_end_second_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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
|
||||
func test_first_throwing() 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("Zipped sequence should throw after one collected element")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a")], collected)
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
|
||||
func test_second_throwing() 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("Zipped sequence should throw after one collected element")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a")], collected)
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_finishes_when_iteration_task_is_cancelled() async {
|
||||
func test_cancellation() async {
|
||||
let source1 = Indefinite(value: "test1")
|
||||
let source2 = Indefinite(value: "test2")
|
||||
let sequence = zip(source1.async, source2.async)
|
||||
@@ -161,188 +143,159 @@ final class TestZip2: XCTestCase {
|
||||
}
|
||||
|
||||
final class TestZip3: XCTestCase {
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
|
||||
func test_zip() 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(expected, actual)
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
}
|
||||
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
|
||||
func test_zip_first_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(expected, actual)
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
}
|
||||
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
|
||||
func test_zip_second_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(expected, actual)
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
}
|
||||
|
||||
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_third_is_longer() async {
|
||||
func test_zip_third_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(expected, actual)
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
|
||||
func test_iterate_past_end() 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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
|
||||
func test_iterate_past_end_first_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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
|
||||
func test_iterate_past_end_second_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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_third_is_longer() async {
|
||||
func test_iterate_past_end_third_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(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
|
||||
let pastEnd = await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
|
||||
func test_first_throwing() 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("Zipped sequence should throw after one collected element")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
|
||||
func test_second_throwing() 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("Zipped sequence should throw after one collected element")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_produces_one_element_and_throws_when_third_produces_one_element_and_throws() async throws {
|
||||
func test_third_throwing() 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("Zipped sequence should throw after one collected element")
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual(Failure(), error as? Failure)
|
||||
}
|
||||
XCTAssertEqual(expected, collected)
|
||||
|
||||
XCTAssertEqual([(1, "a", 1)], collected)
|
||||
let pastEnd = try await iterator.next()
|
||||
XCTAssertNil(pastEnd)
|
||||
}
|
||||
|
||||
func test_zip_finishes_when_iteration_task_is_cancelled() async {
|
||||
func test_cancellation() async {
|
||||
let source1 = Indefinite(value: "test1")
|
||||
let source2 = Indefinite(value: "test2")
|
||||
let source3 = Indefinite(value: "test3")
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
#!/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