Compare commits

...
34 Commits
Author SHA1 Message Date
Philippe Hausler 434591a571 Update availability to be in sync with Clock/Instant/Duration (#159) 2022-06-13 10:18:45 -07:00
Max Desiatov 6e9a5757bc Fix typo in BufferedBytes.md (#158)
`BufferedAsyncByteIterator` -> `AsyncBufferedByteIterator`
2022-05-30 19:29:53 -07:00
Thibault Wittemberg a973b06d06 Fix async channel finishes all (#152)
* asyncChannel: enforce termination for all when finished

* asyncThrowingChannel: enforce termination for all when finished

* asyncChannel: improve unit tests readability

* asyncChannel: adapt the Guide to the new finish behaviour

* asyncChannel: adapt the Guide to the new finish behaviour
2022-05-04 13:07:33 -07:00
Kevin Tan 6b59cfb8d0 Minor documentation improvements (#153) 2022-05-03 21:17:53 -07:00
Philippe Hausler d185b2068b [SAA-0001] Zip (#149) 2022-04-27 16:08:26 -07:00
Thibault Wittemberg bbbe08d331 zip: improve unit tests readability (#151) 2022-04-25 17:50:09 -07:00
Thibault Wittemberg 6d5d6319f4 asyncThrowingChannel: fixes potential crashes when no more awaiting (#150)
This commit fixes crashes where the state is "awaiting" with no more awaiting clients.
The state is now set to .idle to reflect the reality.
2022-04-21 11:10:14 -07:00
Thibault Wittemberg 047ab6abef asyncChannel: fixes potential crashes when no more awaiting (#143)
This commit fixes crashes where the state is "awaiting" with no more awaiting clients.
The state is now set to .idle to reflect the reality.
2022-04-15 10:05:40 -07:00
Tiago Lopes d2164b9ef6 Fix redundant where clauses in AsyncBufferSequence extension (#141) 2022-04-12 07:23:05 -07:00
Tiago Lopes b3d4ffb94c Fix broken links to guides in README.md (#146) 2022-04-11 16:53:54 -07:00
Tiago Lopes 5b78eaf423 Fix some typos in Chain.md (#144) 2022-04-11 15:06:39 -07:00
Kyle a3576e669b Add docc support and publish documentation to GitHub pages (#137)
* Move Guides into docc base location

* Add Github gh-page support

* Conditionally add docc-plugin dependency

* Temp skip AsyncSequenceValidation target
2022-04-11 14:25:33 -07:00
Kristoffer Johansson 94a7ecec28 Moves XCTestCase.validate into its own module (#135)
* Move XCTestCase.validate into it’s own module

* Remove unnecessary import statement
2022-04-08 14:15:55 -07:00
Philippe Hausler 6a8aec2a1f #131 Cancel sends as if they were terminal events on task cancellation (#132) 2022-04-08 10:44:30 -07:00
Philippe Hausler 9d03d90a13 #120 Ensure concurrent access to AsyncBufferedByteIterator does not crash from dangling pointers (#121) 2022-04-08 10:44:06 -07:00
k-kohey c174e4603e fix merge example (#140) 2022-04-08 08:47:25 -07:00
Yuka Ezura b6755e6313 Fix typo (#138) 2022-04-07 12:18:56 -07:00
Philippe Hausler 18749897a8 #113 Define the first element of throttled sequences by not exceeding the rate (and fix a expectation misalignment of events) (#133)
* #113 Define the first element of throttled sequences by not exceeding the rate (and fix a expectation misalignment of events)

* Update guide for throttle referencing the first element and duration measurement
2022-04-01 11:40:44 -07:00
Guillaume Lessard 6971c8fc67 Update README.md (#134)
Insert a forgotten word.
2022-04-01 09:24:42 -07:00
Tiago Lopes f1581d0973 Fix a grammatical sentence in Collections.md (#127) 2022-03-30 10:20:47 -07:00
Tiago Lopes 442d20e8c8 Fix TestRangeReplaceableCollection.swift file name (#128) 2022-03-30 10:20:19 -07:00
Laszlo Teveli b8a8d5d2ae Rename AdjacentPairsSequence.swift (#126) 2022-03-29 12:15:04 -07:00
Laszlo Teveli b136d48e7f Adjacent Pairs (#111) 2022-03-29 10:01:55 -07:00
Reza Shirazian 4b5a3ef050 measureSequenceThroughput-duration-clean-up (#125)
duration and start property in measureSequenceThroughput is vestigial from early development. This PR cleans that up.
2022-03-29 09:10:51 -07:00
Tiago Lopes 9ce65b089c Fix the README link to the Swift Forums (#123) 2022-03-28 17:54:26 -07:00
Reza Shirazian fac138c517 #45 - Two sided performance test for merge (#114)
This PR extends `measureSequenceThroughput` to take two outputs so functions like merge/ zip etc can be tested by both sides.
2022-03-28 17:09:22 -07:00
Jordan Kay a8bba84598 Fix spelling and typos (#122)
* Fix spelling

* Fix typos
2022-03-28 17:02:51 -07:00
Vikram Kriplaney 739815f65d Fix zip example (#119) 2022-03-28 11:08:46 -07:00
Reza Shirazian 0dfb244b1b Fixing a few typos (#115)
This PR fixes a few typos across various comments in the code.
2022-03-27 08:19:52 -07:00
Philippe Hausler f9369af30c Add instructions for building with swift 5.6 toolchains (#106) 2022-03-25 14:49:20 -07:00
jamieQ 1656fd8839 Fix typo in AsyncChannel documentation (#108)
fix typo
2022-03-25 14:49:10 -07:00
Philippe Hausler db847ef410 Remove shims for use with the swift development toolchains (#105) 2022-03-24 16:03:21 -07:00
Philippe Hausler 21f20e9030 Only emit diagnostics for unexpected diagram mismatches (#103) 2022-03-24 15:14:40 -07:00
Philippe Hausler df97fdaced Update the code of conduct to avoid it going out of sync (#102) 2022-03-24 12:28:19 -07:00
72 changed files with 1131 additions and 2550 deletions

No files matched your search

+2 -52
View File
@@ -1,55 +1,5 @@
# Code of Conduct
To be a truly great community, Swift.org needs to welcome developers from all walks of life,
with different backgrounds, and with a wide range of experience. A diverse and friendly
community will have more great ideas, more unique perspectives, and produce more great
code. We will work diligently to make the Swift community welcoming to everyone.
To give clarity of what is expected of our members, Swift.org has adopted the code of conduct
defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source
communities, and we think it articulates our values well. The full text is copied below:
The code of conduct for this project can be found at https://swift.org/code-of-conduct.
### Contributor Code of Conduct v1.3
As contributors and maintainers of this project, and in the interest of fostering an open and
welcoming community, we pledge to respect all people who contribute through reporting
issues, posting feature requests, updating documentation, submitting pull requests or patches,
and other activities.
We are committed to making participation in this project a harassment-free experience for
everyone, regardless of level of experience, gender, gender identity and expression, sexual
orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or
nationality.
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery
- Personal attacks
- Trolling or insulting/derogatory comments
- Public or private harassment
- Publishing other’s private information, such as physical or electronic addresses, without explicit permission
- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of
Conduct, or to ban temporarily or permanently any contributor for other behaviors that they
deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and
consistently applying these principles to every aspect of managing this project. Project
maintainers who do not follow or enforce the Code of Conduct may be permanently removed
from the project team.
This code of conduct applies both within project spaces and in public spaces when an
individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
contacting a project maintainer at [conduct@swift.org](mailto:conduct@swift.org). All complaints will be reviewed and
investigated and will result in a response that is deemed necessary and appropriate to the
circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter
of an incident.
*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](http://contributor-covenant.org/version/1/3/0/).*
### Reporting
A working group of community members is committed to promptly addressing any [reported
issues](mailto:conduct@swift.org). Working group members are volunteers appointed by the project lead, with a
preference for individuals with varied backgrounds and perspectives. Membership is expected
to change regularly, and may grow or shrink.
<!-- Copyright (c) 2022 Apple Inc and the Swift Project authors. All Rights Reserved. -->
+110
View File
@@ -0,0 +1,110 @@
# Zip
* Proposal: [SAA-0001](https://github.com/apple/swift-async-algorithms/blob/main/Evolution/0001-zip.md)
* Authors: [Philippe Hausler](https://github.com/phausler)
* Status: **Implemented**
* Implementation: [[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncZip2Sequence.swift), [Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncZip3Sequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestZip.swift)]
* Decision Notes:
* Bugs:
## Introduction
The swift standard library has a function that allows for the combining of two sequences into one sequence of tuples of the elements of the base sequences. This concept can be achieved for `AsyncSequence` with the iteration being asynchronous but also each side being concurrently iterated while still rethrowing potential failures. This proposal covers that parity between `AsyncSequence` and `Sequence`. It is often times useful to describe asynchronous sequences of events as paired occurrences. The fundamental algorithm for this is zip.
## Detailed Design
Zip combines the latest values produced from two or more asynchronous sequences into an asynchronous sequence of tuples.
```swift
let appleFeed = URL(string: "http://www.example.com/ticker?symbol=AAPL")!.lines
let nasdaqFeed = URL(string: "http://www.example.com/ticker?symbol=^IXIC")!.lines
for try await (apple, nasdaq) in zip(appleFeed, nasdaqFeed) {
print("APPL: \(apple) NASDAQ: \(nasdaq)")
}
```
Given some sample inputs the following zipped events can be expected.
| Timestamp | appleFeed | nasdaqFeed | combined output |
| ----------- | --------- | ---------- | ----------------------------- |
| 11:40 AM | 173.91 | | |
| 12:25 AM | | 14236.78 | AAPL: 173.91 NASDAQ: 14236.78 |
| 12:40 AM | | 14218.34 | |
| 1:15 PM | 173.00 | | AAPL: 173.00 NASDAQ: 14218.34 |
This function family and the associated family of return types are prime candidates for variadic generics. Until that proposal is accepted, these will be implemented in terms of two- and three-base sequence cases.
```swift
public func zip<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncZip2Sequence<Base1, Base2>
public func zip<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>(_ base1: Base1, _ base2: Base2, _ base3: Base3) -> AsyncZip3Sequence<Base1, Base2, Base3>
public struct AsyncZip2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable,
Base1.Element: Sendable, Base2.Element: Sendable,
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable {
public typealias Element = (Base1.Element, Base2.Element)
public struct Iterator: AsyncIteratorProtocol {
public mutating func next() async rethrows -> Element?
}
public func makeAsyncIterator() -> Iterator
}
public struct AsyncZip3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>: Sendable
where
Base1: Sendable, Base2: Sendable, Base3: Sendable
Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable
Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base3.AsyncIterator: Sendable {
public typealias Element = (Base1.Element, Base2.Element, Base3.Element)
public struct Iterator: AsyncIteratorProtocol {
public mutating func next() async rethrows -> Element?
}
public func makeAsyncIterator() -> Iterator
}
```
The `zip(_:...)` function takes two or more asynchronous sequences as arguments with the resulting `AsyncZipSequence` which is an asynchronous sequence.
Each iteration of an `AsyncZipSequence` will await for all base iterators to produce a value. This iteration will be done concurrently to produce a singular tuple result. If any of the base iterations terminates by returning `nil` from its iteration, the `AsyncZipSequence` iteration is immediately considered unsatisfiable and returns `nil` and all iterations of other bases will be cancelled. If any iteration of the bases throws an error, then the other iterations concurrently running are cancelled and the produced error is rethrown, terminating the iteration.
`AsyncZipSequence` requires that the iterations are done concurrently. This means that the base sequences, their elements, and iterators must all be `Sendable`. That makes `AsyncZipSequence` inherently `Sendable`.
The source of throwing of `AsyncZipSequence` is determined by its bases. That means that if any base can throw an error then the iteration of the `AsyncZipSequence` can throw. If no bases can throw, then the `AsyncZipSequence` does not throw.
### Naming
The `zip(_:...)` function takes its name from the Swift standard library function of the same name. The `AsyncZipSequence` family of types take their name from the same family from the standard library for the type returned by `zip(_:_:)`. The one difference is that this asynchronous version allows for the affordance of recognizing the eventual variadic generic need of expanding a zip of more than just two sources.
It is common in some libraries to have a `ZipMap` or some other combination of `zip` and `map`. This is a common usage pattern, but leaving a singular type for composition feels considerably more approachable.
### Comparison with other libraries
**Swift** The swift standard library has an [API definition of zip](https://developer.apple.com/documentation/swift/1541125-zip) as a top level function for combining two sequences.
**ReactiveX** ReactiveX has an [API definition of Zip](https://reactivex.io/documentation/operators/zip.html) as a top level function for combining Observables.
**Combine** Combine has an [API definition of zip](https://developer.apple.com/documentation/combine/publisher/zip(_:)/) as an operator style method for combining Publishers.
## Effect on API resilience
### `@frozen` and `@inlinable`
These types utilize rethrowing mechanisms that are awaiting an implementation in the compiler for supporting implementation based rethrows. So none of them are marked as frozen or marked as inlinable. This feature (discussed as `rethrows(unsafe)` or `rethrows(SourceOfRethrowyness)` has not yet been reviewed or implemented. The current implementation takes liberties with an internal protocol to accomplish this task. Future revisions will remove that protocol trick to replace it with proper rethrows semantics at the actual call site. The types are expected to be stable boundaries to prevent that workaround for the compilers yet to be supported rethrowing (or TaskGroup rethrowing) mechanisms. As soon as that feature is resolved; a more detailed investigation on performance impact of inlining and frozen should be done before 1.0.
## Alternatives considered
It was considered to have zip be shaped as an extension method on `AsyncSequence` however that infers a "primary-ness" of one `AsyncSequence` over another. Since the standard library spells this as a global function (which infers no preference to one side or another) it was decided that having symmetry between the asynchronous version and the synchronous version inferred the right connotations.
There are other methods with similar behavior that could be controlled by options passed in. This concept has merit but was initially disregarded since that would complicate the interface. Design-wise this is still an open question if having a "zip-behavior-options" parameter to encompass combining the latest values or zipping based upon a preference to a "primary" side or not is meaningful.
It is common to have a zip+map to create structures instead of tuples, however that was disregarded since that concept could easily be expressed by composing zip and map.
+27 -5
View File
@@ -12,21 +12,28 @@ let package = Package(
],
products: [
.library(name: "AsyncAlgorithms", targets: ["AsyncAlgorithms"]),
.library(name: "ClockShims", type: .static, targets: ["ClockShims"]),
.library(name: "AsyncSequenceValidation", targets: ["AsyncSequenceValidation"]),
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"])
.library(name: "_CAsyncSequenceValidationSupport", type: .static, targets: ["AsyncSequenceValidation"]),
.library(name: "AsyncAlgorithms_XCTest", targets: ["AsyncAlgorithms_XCTest"]),
],
dependencies: [],
targets: [
.target(name: "AsyncAlgorithms", dependencies: ["ClockShims"]),
.target(name: "ClockShims"),
.target(name: "AsyncAlgorithms"),
.target(
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"],
dependencies: ["AsyncAlgorithms", "AsyncSequenceValidation", "AsyncAlgorithms_XCTest"],
swiftSettings: [
.unsafeFlags([
"-Xfrontend", "-disable-availability-checking"
@@ -34,3 +41,18 @@ 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"),
] : []
+40 -33
View File
@@ -14,58 +14,59 @@ This package has three main goals:
The foundation for AsyncAlgorithms was included in Swift 5.5 from [AsyncSequence](https://github.com/apple/swift-evolution/blob/main/proposals/0298-asyncsequence.md). Swift 5.5 also brings the ability to use a natural `for/in` loop with `await` to process the values in an `AsyncSequence` and `Sequence`-equivalent API like `map` and `filter`. Structured concurrency allows us to write code where intermediate state is simply a local variable, `try` can be used directly on functions that `throw`, and generally treat the logic for asynchronous code similar to that of synchronous code.
This package is the home for these APIs. Development and API design take place on [GitHub](https://github.com/apple/swift-async-algorithms) and the [Swift Forums](https://forums.swift.org/c/related-projects/).
This package is the home for these APIs. Development and API design take place on [GitHub](https://github.com/apple/swift-async-algorithms) and the [Swift Forums](https://forums.swift.org/c/related-projects/swift-async-algorithms).
## Contents
#### Combining asynchronous sequences
- [`chain(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chain.md): Concatenates two or more asynchronous sequences with the same element type.
- [`combineLatest(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/CombineLatest.md): Combines two or more asynchronous sequences into an asynchronous sequence producing a tuple of elements from those base asynchronous sequences that updates when any of the base sequences produce a value.
- [`merge(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Merge.md): Merges two or more asynchronous sequence into a single asynchronous sequence producing the elements of all of the underlying asynchronous sequences.
- [`zip(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Zip.md): Creates an asynchronous sequence of pairs built out of underlying asynchronous sequences.
- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Joined.md): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element.
- [`chain(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Chain.md): Concatenates two or more asynchronous sequences with the same element type.
- [`combineLatest(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/CombineLatest.md): Combines two or more asynchronous sequences into an asynchronous sequence producing a tuple of elements from those base asynchronous sequences that updates when any of the base sequences produce a value.
- [`merge(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Merge.md): Merges two or more asynchronous sequence into a single asynchronous sequence producing the elements of all of the underlying asynchronous sequences.
- [`zip(_:...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Zip.md): Creates an asynchronous sequence of pairs built out of underlying asynchronous sequences.
- [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Joined.md): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element.
#### Creating asynchronous sequences
- [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence.
- [`AsyncChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics.
- [`AsyncThrowingChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics that can emit failures.
- [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence.
- [`AsyncChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics.
- [`AsyncThrowingChannel`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Channel.md): An asynchronous sequence with back pressure sending semantics that can emit failures.
#### Performance optimized asynchronous iterators
- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions.
- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions.
#### Other useful asynchronous sequences
- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chunked.md): Collect values into chunks.
- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Compacted.md): Remove nil values from an asynchronous sequence.
- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values.
- [`interspersed(with:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of an asynchronous sequence.
- [`adjacentPairs()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/AdjacentPairs.md): Collects tuples of adjacent elements.
- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Chunked.md): Collect values into chunks.
- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Compacted.md): Remove nil values from an asynchronous sequence.
- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values.
- [`interspersed(with:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Intersperse.md): Place a value between every two elements of an asynchronous sequence.
#### Asynchronous Sequences that transact in time
- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Debounce.md): Emit values after a quiessence period has been reached.
- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Throttle.md): Ensure a minimum interval has elapsed between events.
- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Timer.md): Emit the value of now at a given interval repeatedly.
- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Debounce.md): Emit values after a quiescence period has been reached.
- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Throttle.md): Ensure a minimum interval has elapsed between events.
- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Timer.md): Emit the value of now at a given interval repeatedly.
#### Obtaining all values from an asynchronous sequence
- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new instance of a collection containing the elements of an asynchronous sequence.
- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence.
- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys.
- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): /// Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md): Creates a new set from an asynchronous sequence of items.
- [`RangeReplaceableCollection.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new instance of a collection containing the elements of an asynchronous sequence.
- [`Dictionary.init(uniqueKeysWithValues:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence.
- [`Dictionary.init(_:uniquingKeysWith:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary from the key-value pairs in the given asynchronous sequence, using a combining closure to determine the value for any duplicate keys.
- [`Dictionary.init(grouping:by:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.
- [`SetAlgebra.init(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Collections.md): Creates a new set from an asynchronous sequence of items.
#### Task management
- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Select.md): Determine the first task to complete of a sequence of tasks.
- [`Task.select(_:)`](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Select.md): Determine the first task to complete of a sequence of tasks.
#### Effects
Each algorithm has specific behavioral effects. For throwing effects these can either be if the sequence throws, does not throw, or rethrows errors. Sendability effects in some asynchronous sequences are conditional whereas others require the composed parts to all be sendable to satisfy a requirement of `Sendable`. The effects are [listed here](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Effects.md).
Each algorithm has specific behavioral effects. For throwing effects these can either be if the sequence throws, does not throw, or rethrows errors. Sendability effects in some asynchronous sequences are conditional whereas others require the composed parts to all be sendable to satisfy a requirement of `Sendable`. The effects are [listed here](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Effects.md).
## Adding Swift Algorithms as a Dependency
## Adding Swift Async Algorithms as a Dependency
To use the `AsyncAlgorithms` library in a SwiftPM project,
add the following line to the dependencies in your `Package.swift` file:
@@ -86,27 +87,33 @@ Finally, add `import AsyncAlgorithms` to your source code.
## Getting Started
⚠️ Please note that this package currently requires a recent [Swift Trunk Development toolchain](https://www.swift.org/download/#trunk-development-main). More information on how to use custom toolchains with Xcode can be viewed [here](https://developer.apple.com/library/archive/documentation/ToolsLanguages/Conceptual/Xcode_Overview/AlternativeToolchains.html).
### Building/Testing Using Xcode on macOS
1. Open the `swift-async-algorithms` package directory in Xcode
2. Build or Test in Xcode as normal
### Building/Testing Using Swift Package Manager
1. Download the most recent development Xcode toolchain.
2. Install the package
4. Select the development toolchain in Xcode
4. Open the `swift-async-algorithms` package directory in Xcode
5. Build or Test in Xcode as normal
1. In the `swift-async-algorithms` directory run `swift build` or `swift test` accordingly
⚠️ Note: `swift test` does not currently work properly with custom toolchains for this package.
### Building/Testing on Linux
1. Download the most recent toolchain for your Linux distribution
1. Download the most recent development toolchain for your Linux distribution
2. Decompress the archive to a path in which the `swift` executable is in the binary search path environment variable (`$PATH`)
3. In the `swift-async-algorithms` directory run `swift build` or `swift test` accordingly
### Building with Swift 5.6
1. `git checkout swift-5.6`
2. run `swift build` or `swift test` accordingly
## Source Stability
The Swift Async Algorithms package has a goal of being source stable as soon as possible; version numbers will follow [Semantic Versioning](https://semver.org/). Source breaking changes to public API can only land in a new major version.
Before the version 1.0 the `swift-async-algorithms` package will not be source or ABI stable. Particularly the shims associated with `Clock`, `Instant` and `Duration` are present just to provide backwards compatability to older toolchains. As soon as this is available widely the shims will be removed; which will be an ABI breaking change.
The public API of version 1.0 of the `swift-async-algorithms` package will consist of non-underscored declarations that are marked `public` in the `AsyncAlgorithms` module. Interfaces that aren't part of the public API may continue to change in any release, including patch releases.
Future minor versions of the package may introduce changes to these rules as needed.
@@ -0,0 +1,87 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// An `AsyncSequence` that iterates over the adjacent pairs of the original
/// `AsyncSequence`.
@frozen
public struct AsyncAdjacentPairsSequence<Base: AsyncSequence>: AsyncSequence {
public typealias Element = (Base.Element, Base.Element)
@usableFromInline
let base: Base
@inlinable
init(_ base: Base) {
self.base = base
}
/// The iterator for an `AsyncAdjacentPairsSequence` instance.
@frozen
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = (Base.Element, Base.Element)
@usableFromInline
var base: Base.AsyncIterator
@usableFromInline
internal var previousElement: Base.Element?
@inlinable
init(_ base: Base.AsyncIterator) {
self.base = base
}
@inlinable
public mutating func next() async rethrows -> (Base.Element, Base.Element)? {
if previousElement == nil {
previousElement = try await base.next()
}
guard let previous = previousElement, let next = try await base.next() else {
return nil
}
previousElement = next
return (previous, next)
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(base.makeAsyncIterator())
}
}
extension AsyncSequence {
/// An `AsyncSequence` that iterates over the adjacent pairs of the original
/// original `AsyncSequence`.
///
/// ```
/// for await (first, second) in (1...5).async.adjacentPairs() {
/// print("First: \(first), Second: \(second)")
/// }
///
/// // First: 1, Second: 2
/// // First: 2, Second: 3
/// // First: 3, Second: 4
/// // First: 4, Second: 5
/// ```
///
/// - Returns: An `AsyncSequence` where the element is a tuple of two adjacent elements
/// or the original `AsyncSequence`.
@inlinable
public func adjacentPairs() -> AsyncAdjacentPairsSequence<Self> {
AsyncAdjacentPairsSequence(self)
}
}
extension AsyncAdjacentPairsSequence: Sendable where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { }
extension AsyncAdjacentPairsSequence.Iterator: Sendable where Base: Sendable, Base.Element: Sendable, Base.AsyncIterator: Sendable { }
@@ -0,0 +1,36 @@
# ``AsyncAlgorithms``
**Swift Async Algorithms** is an open-source package of asynchronous sequence and advanced algorithms that involve concurrency, along with their related types.
## Overview
This package has three main goals:
- First-class integration with `async/await`
- Provide a home for time-based algorithms
- Be cross-platform and open source
## Topics
### Getting Started
- <doc:AdjacentPairs>
- <doc:BufferedBytes>
- <doc:Chain>
- <doc:Channel>
- <doc:Chunked>
- <doc:Collections>
- <doc:CombineLatest>
- <doc:Compacted>
- <doc:Debounce>
- <doc:Effects>
- <doc:Intersperse>
- <doc:Joined>
- <doc:Lazy>
- <doc:Merge>
- <doc:Reductions>
- <doc:RemoveDuplicates>
- <doc:Select>
- <doc:Throttle>
- <doc:Timer>
- <doc:Zip>
@@ -0,0 +1,49 @@
# AdjacentPairs
* Author(s): [László Teveli](https://github.com/tevelee)
[[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAdjacentPairsSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestAdjacentPairs.swift)]
The `adjacentPairs()` API serve the purpose of collecting adjacent values. This operation is available for any `AsyncSequence` by calling the `adjacentPairs()` method.
```swift
extension AsyncSequence {
public func adjacentPairs() -> AsyncAdjacentPairsSequence<Self>
}
```
## Detailed Design
The `adjacentPairs()` algorithm produces elements of tuple (size of 2), containing a pair of the original `Element` type.
The interface for this algorithm is available on all `AsyncSequence` types. The returned `AsyncAdjacentPairsSequence` conditionally conforms to `Sendable`.
Its iterator keeps track of the previous element returned in the `next()` function and updates it in every turn.
```swift
for await (first, second) in (1...5).async.adjacentPairs() {
print("First: \(first), Second: \(second)")
}
// First: 1, Second: 2
// First: 2, Second: 3
// First: 3, Second: 4
// First: 4, Second: 5
```
It composes well with the [Dictionary.init(_:uniquingKeysWith:)](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Collections.md) API that deals with `AsyncSequence` of tuples.
```swift
Dictionary(uniqueKeysWithValues: url.lines.adjacentPairs())
```
## Alternatives Considered
This functionality is often written as a `zip` of a sequence together with itself, dropping its first element (`zip(source, source.dropFirst())`).
It's such a dominant use-case, the [swift-algorithms](https://github.com/apple/swift-algorithms) package also [introduced](https://github.com/apple/swift-algorithms/pull/119) it to its collection of algorithms.
## Credits/Inspiration
The synchronous counterpart in [swift-algorithms](https://github.com/apple/swift-algorithms/blob/main/Guides/AdjacentPairs.md).
@@ -17,7 +17,7 @@ struct AsyncBytes: AsyncSequence {
}
public func makeAsyncIterator() -> AsyncBufferedByteIterator {
return BufferedAsyncByteIterator(capacity: 16384) { buffer in
return AsyncBufferedByteIterator(capacity: 16384) { buffer in
// This runs once every 16384 invocations of next()
return try await handle.read(into: buffer)
}
@@ -9,8 +9,8 @@ This operation is available for all `AsyncSequence` types who share the same `El
```swift
let preamble = [
"// Some header to add as a preamble"
"//"
"// Some header to add as a preamble",
"//",
""
].async
let lines = chain(preamble, URL(fileURLWithPath: "/tmp/Sample.swift").lines)
@@ -60,7 +60,7 @@ extension AsyncChain3Sequence.Iterator: Sendable where Base1.AsyncIterator: Send
The `chain(_:...)` function takes two or more sequences as arguments.
The resulting `AsyncChainSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments conform.
The resulting `AsyncChainSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments also conform to it.
When any of the asynchronous sequences being chained together come to their end of iteration, the `AsyncChainSequence` iteration proceeds to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration, the `AsyncChainSequence` then ends its iteration.
@@ -14,7 +14,7 @@
## Proposed Solution
To achieve a system that supports back pressure and allows for the communication of more than one value from one task to another we are introducing a new type, the _channel_. The channel will be a reference-type asynchronous sequence with an asynchronous sending capability that awaits the consumption of iteration. Each value sent by the channel, or finish transmitted, will await the consumption of that value or event by iteration. That awaiting behavior will allow for the affordance of back pressure applied from the consumption site to be transmitted to the production site. This means that the rate of production cannot exceed the rate of consumption, and that the rate of consumption cannot exceed the rate of production.
To achieve a system that supports back pressure and allows for the communication of more than one value from one task to another we are introducing a new type, the _channel_. The channel will be a reference-type asynchronous sequence with an asynchronous sending capability that awaits the consumption of iteration. Each value sent by the channel will await the consumption of that value by iteration. That awaiting behavior will allow for the affordance of back pressure applied from the consumption site to be transmitted to the production site. This means that the rate of production cannot exceed the rate of consumption, and that the rate of consumption cannot exceed the rate of production. Sending a terminal event to the channel will instantly resume all pending operations for every producers and consumers.
## Detailed Design
@@ -31,7 +31,7 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
public init(element elementType: Element.Type = Element.self)
public func send(_ element: Element) async
public func finish() async
public func finish()
public func makeAsyncIterator() -> Iterator
}
@@ -45,13 +45,13 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
public func send(_ element: Element) async
public func fail(_ error: Error) async where Failure == Error
public func finish() async
public func finish()
public func makeAsyncIterator() -> Iterator
}
```
Channels are intended to be used as communication types between tasks. Particularly when one task produces values and another task consumes said values. The back pressure applied by `send(_:)`, `fail(_:)` and `finish()` via the suspension/resume ensure that the production of values does not exceed the consumption of values from iteration. Each of these methods suspend after enqueuing the event and are resumed when the next call to `next()` on the `Iterator` is made.
Channels are intended to be used as communication types between tasks. Particularly when one task produces values and another task consumes said values. On the one hand, the back pressure applied by `send(_:)` and `fail(_:)` via the suspension/resume ensure that the production of values does not exceed the consumption of values from iteration. Each of these methods suspend after enqueuing the event and are resumed when the next call to `next()` on the `Iterator` is made. On the other hand, the call to `finish()` immediately resumes all the pending operations for every producers and consumers. Thus, every suspended `send(_:)` operations instantly resume, so as every suspended `next()` operations by producing a nil value, indicating the termination of the iterations. Further calls to `send(_:)` will immediately resume.
```swift
let channel = AsyncChannel<String>()
@@ -59,7 +59,7 @@ Task {
while let resultOfLongCalculation = doLongCalculations() {
await channel.send(resultOfLongCalculation)
}
await channel.finish()
channel.finish()
}
for await calculationResult in channel {
@@ -7,7 +7,7 @@
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/RangeReplaceableCollection.swift),
[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/SetAlgebra.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestDictionary.swift),
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRangeReplacableCollection.swift),
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestRangeReplaceableCollection.swift),
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestSetAlgebra.swift),
]
@@ -22,7 +22,7 @@ This type of functionality can be useful for examples and testing, and also for
Three categories of initializers will be added to provide initializers for those three primary types: `Array`, `Dictionary` and `Set`. However these initializers can be written in a generic fashion such that they can apply to all similar collections.
`RangeReplaceableCollection` will gain a new that constructs a collection given an `AsyncSequence`. This will allow for creating arrays from asynchronous sequences but also allow for creating types like `Data` or `ContiguousArray`. Because of the nature of asynchronous sequences, this initializer must be asynchronous and declare that it rethrows errors from the base asynchronous sequence.
`RangeReplaceableCollection` will gain a new initializer that constructs a collection given an `AsyncSequence`. This will allow for creating arrays from asynchronous sequences but also allow for creating types like `Data` or `ContiguousArray`. Because of the nature of asynchronous sequences, this initializer must be asynchronous and declare that it rethrows errors from the base asynchronous sequence.
```swift
extension RangeReplaceableCollection {
@@ -64,7 +64,7 @@ public struct AsyncCombineLatest3Sequence<Base1: AsyncSequence, Base2: AsyncSequ
The `combineLatest(_:...)` function takes two or more asynchronous sequences as arguments and produces an `AsyncCombineLatestSequence` which is an asynchronous sequence.
Since the bases comprising the `AsyncCombineLatestSequence` must be iterated concurrently to produce the latest value, those sequences must be able to be sent to child tasks. This means that a prerequisite of the bases must be that the base asynchronous sequences, their iterators, and the elemnts they produce must all be `Sendable`.
Since the bases comprising the `AsyncCombineLatestSequence` must be iterated concurrently to produce the latest value, those sequences must be able to be sent to child tasks. This means that a prerequisite of the bases must be that the base asynchronous sequences, their iterators, and the elements they produce must all be `Sendable`.
If any of the bases terminate before the first element is produced, then the `AsyncCombineLatestSequence` iteration can never be satisfied. So, if a base's iterator returns `nil` at the first iteration, then the `AsyncCombineLatestSequence` iterator immediately returns `nil` to signify a terminal state. In this particular case, any outstanding iteration of other bases will be cancelled. After the first element is produced ,this behavior is different since the latest values can still be satisfied by at least one base. This means that beyond the construction of the first tuple comprised of the returned elements of the bases, the terminal state of the `AsyncCombineLatestSequence` iteration will only be reached when all of the base iterations reach a terminal state.
@@ -72,12 +72,12 @@ The throwing behavior of `AsyncCombineLatestSequence` is that if any of the base
### Naming
Since the inherent behavior of `combineLatest(_:...)` combines the latest values from multiple streams into a tuple the naming is intended to be quite literal. There are precident terms of art in other frameworks and libraries (listed in the comparison section). Other naming takes the form of "withLatestFrom". This was disregarded since the "with" prefix is often most associated with the passing of a closure and some sort of contextual concept; `withUnsafePointer` or `withUnsafeContinuation` are prime examples.
Since the inherent behavior of `combineLatest(_:...)` combines the latest values from multiple streams into a tuple the naming is intended to be quite literal. There are precedent terms of art in other frameworks and libraries (listed in the comparison section). Other naming takes the form of "withLatestFrom". This was disregarded since the "with" prefix is often most associated with the passing of a closure and some sort of contextual concept; `withUnsafePointer` or `withUnsafeContinuation` are prime examples.
### Comparison with other libraries
Combine latest often appears in libraries developed for processing events over time since the event ordering of a concept of "latest" only occurs when asynchrony is involved.
**ReactiveX** ReactiveX has an [API definition of CombineLatest](https://reactivex.io/documentation/operators/combinelatest.html) as a top level function for combinining Observables.
**ReactiveX** ReactiveX has an [API definition of CombineLatest](https://reactivex.io/documentation/operators/combinelatest.html) as a top level function for combining Observables.
**Combine** Combine has an [API definition of combineLatest](https://developer.apple.com/documentation/combine/publisher/combinelatest(_:)/) has an operator style method for combining Publishers.
@@ -9,7 +9,7 @@
## Introduction
Just as it is common for `Sequence` types that contain optional values to need to `.compactMap { $0 }`, `AsyncSequence` types have the same use cases. This common task means that the type must employ a closure to test the optional value. This can be done more efficeintly for both execution performance as well as API efficiency of typing.
Just as it is common for `Sequence` types that contain optional values to need to `.compactMap { $0 }`, `AsyncSequence` types have the same use cases. This common task means that the type must employ a closure to test the optional value. This can be done more efficiently for both execution performance as well as API efficiency of typing.
## Proposed Solution
@@ -1,5 +1,6 @@
| Type | Throws | Sendablity |
| Type | Throws | Sendability |
|-----------------------------------------------------|--------------|-------------|
| `AsyncAdjacentPairsSequence` | rethrows | Conditional |
| `AsyncBufferedByteIterator` | throws | Sendable |
| `AsyncBufferSequence` | rethrows | Conditional |
| `AsyncBufferSequence.Iterator` | rethrows | Conditional |
@@ -108,7 +108,7 @@ extension AsyncJoinedBySeparatorSequence.Iterator: Sendable
The resulting `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` type is an asynchronous sequence, with conditional conformance to `Sendable` when the arguments conform.
When any of the asynchronous sequences being joined together come to their end of iteration, the `Joined` sequence iteration proceeds to the separator asynchronous sequence, if any. When the separator asynchronous sequence terminates, or if no sepaerator was specified, it proceeds on to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` then ends its iteration. At any point in time if one of the comprising asynchronous sequences ever throws an error during iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` iteration will throw that error and end iteration.
When any of the asynchronous sequences being joined together come to their end of iteration, the `Joined` sequence iteration proceeds to the separator asynchronous sequence, if any. When the separator asynchronous sequence terminates, or if no separator was specified, it proceeds on to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` then ends its iteration. At any point in time if one of the comprising asynchronous sequences ever throws an error during iteration the `AsyncJoinedSequence` or `AsyncJoinedBySeparatorSequence` iteration will throw that error and end iteration.
## Future Directions
File renamed without changes.
@@ -6,10 +6,10 @@
Merges two or more asynchronous sequences sharing the same element type into one singular asynchronous sequence.
```swift
let appleFeed = URL("http://www.example.com/ticker?symbol=AAPL").lines.map { "AAPL: " + $0 }
let nasdaqFeed = URL("http://www.example.com/ticker?symbol=^IXIC").lines.map { "^IXIC: " + $0 }
let appleFeed = URL(string: "http://www.example.com/ticker?symbol=AAPL")!.lines.map { "AAPL: " + $0 }
let nasdaqFeed = URL(string:"http://www.example.com/ticker?symbol=^IXIC")!.lines.map { "^IXIC: " + $0 }
for try await ticker = merge(appleFeed, nasdaqFeed) {
for try await ticker in merge(appleFeed, nasdaqFeed) {
print(ticker)
}
```
@@ -50,5 +50,4 @@ This means that `withTaskGroup` is highly suited to run work in parallel, wherea
## Future Directions
## Credits/Inspiration
@@ -77,6 +77,8 @@ extension AsyncThrottleSequence.Iterator: Sendable
The `AsyncThrottleSequence` and its `Iterator` are conditionally `Sendable` if the base types comprising it are `Sendable`.
The time in which events are measured are from the previous emission if present. If a duration has elapsed between the last emission and the point in time the throttle is measured then that duration is counted as elapsed. The first element is considered not throttled because no interval can be constructed from the start to the first element.
## Alternatives Considered
It was considered to only provide the "latest" style APIs, however the reduction version grants more flexibility and can act as a funnel to the implementations of `latest`.
@@ -9,7 +9,7 @@
## Introduction
Producing elements at regular intervals can be useful for composing with other algorithms. These can range from invoking code at specific times to using those regular intervals as a delimter of events. There are other cases this exists in APIs however those do not currently interact with Swift concurrency. These existing APIs are ones like `Timer` or `DispatchTimer` but are bound to internal clocks that are not extensible.
Producing elements at regular intervals can be useful for composing with other algorithms. These can range from invoking code at specific times to using those regular intervals as a delimiter of events. There are other cases this exists in APIs however those do not currently interact with Swift concurrency. These existing APIs are ones like `Timer` or `DispatchTimer` but are bound to internal clocks that are not extensible.
## Proposed Solution
@@ -6,10 +6,10 @@
Combines the latest values produced from two or more asynchronous sequences into an asynchronous sequence of tuples.
```swift
let appleFeed = URL("http://www.example.com/ticker?symbol=AAPL").lines
let nasdaqFeed = URL("http://www.example.com/ticker?symbol=^IXIC").lines
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) = zip(appleFeed, nasdaqFeed) {
for try await (apple, nasdaq) in zip(appleFeed, nasdaqFeed) {
print("APPL: \(apple) NASDAQ: \(nasdaq)")
}
```
@@ -80,6 +80,6 @@ It is common in some libraries to have a `ZipMap` or some other combination of `
**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 combinining Observables.
**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.
@@ -203,7 +203,7 @@ extension AsyncSequence where Element: Sendable {
///
/// Use the `buffer(_:)` method to account for `AsyncSequence` types that may produce elements faster
/// than they are iterated. The `createBuffer` closure returns a backing buffer for storing elements and dealing with
/// behavioral charcteristics of the `buffer(_:)` algorithm.
/// behavioral characteristics of the `buffer(_:)` algorithm.
///
/// - Parameter createBuffer: A closure that constructs a new `AsyncBuffer` actor to store buffered values.
/// - Returns: An asynchronous sequence that buffers elements using the specified `AsyncBuffer`.
@@ -234,8 +234,8 @@ public struct AsyncBufferSequence<Base: AsyncSequence, Buffer: AsyncBuffer> wher
}
}
extension AsyncBufferSequence: Sendable where Base: Sendable, Base.AsyncIterator: Sendable, Base.Element: Sendable { }
extension AsyncBufferSequence.Iterator: Sendable where Base: Sendable, Base.AsyncIterator: Sendable, Base.Element: Sendable { }
extension AsyncBufferSequence: Sendable where Base: Sendable { }
extension AsyncBufferSequence.Iterator: Sendable where Base: Sendable { }
extension AsyncBufferSequence: AsyncSequence {
public typealias Element = Buffer.Output
@@ -110,6 +110,24 @@ internal struct _AsyncBytesBuffer: @unchecked Sendable {
}
try Task.checkCancellation()
do {
// If two tasks have access to this iterator then the references on
// the storage will be non uniquely owned. This means that any reload
// must happen into it's own fresh buffer. The consumption of those
// bytes between two tasks are inherently defined as potential
// duplication by the nature of sending that buffer across the two
// tasks - this means that the brief period in which they may be
// sharing non reloaded bytes is to be expected; basically in that
// edge case of making the iterator and sending that across to two
// places to iterate is asking for something bizzare and the answer
// should not be crash, but it definitely cannot be consistent.
//
// The unique ref check is here to prevent the potentials of a crashing
// secnario.
if !isKnownUniquelyReferenced(&storage) {
// The count is not mutated across invocations so the access is safe.
let capacity = storage.buffer.count
storage = Storage(capacity: capacity)
}
let readSize: Int = try await readFunction(storage.buffer)
if readSize == 0 {
finished = true
@@ -15,7 +15,7 @@
/// - Parameters:
/// - s1: The first asynchronous sequence.
/// - s2: The second asynchronous sequence.
/// - Returns: An asynchonous sequence that iterates first over the elements of `s1`, and
/// - Returns: An asynchronous sequence that iterates first over the elements of `s1`, and
/// then over the elements of `s2`.
@inlinable
public func chain<Base1: AsyncSequence, Base2: AsyncSequence>(_ s1: Base1, _ s2: Base2) -> AsyncChain2Sequence<Base1, Base2> where Base1.Element == Base2.Element {
@@ -16,7 +16,7 @@
/// - s1: The first asynchronous sequence.
/// - s2: The second asynchronous sequence.
/// - s3: The third asynchronous sequence.
/// - Returns: An asynchonous sequence that iterates first over the elements of `s1`, and
/// - Returns: An asynchronous sequence that iterates first over the elements of `s1`, and
/// then over the elements of `s2`, and then over the elements of `s3`
@inlinable
public func chain<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>(_ s1: Base1, _ s2: Base2, _ s3: Base3) -> AsyncChain3Sequence<Base1, Base2, Base3> {
+79 -46
View File
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
/// A channel for sending elements from on task to another with back pressure.
/// A channel for sending elements from one task to another with back pressure.
///
/// The `AsyncChannel` class is intended to be used as a communication type between tasks,
/// particularly when one task produces values and another task consumes those values. The back
/// pressure applied by `send(_:)` and `finish()` via the suspension/resume ensure that
/// the production of values does not exceed the consumption of values from iteration. Each of these
/// methods suspends after enqueuing the event and is resumed when the next call to `next()`
/// on the `Iterator` is made.
/// pressure applied by `send(_:)` and `finish()` via the suspension/resume ensures that
/// the production of values does not exceed the consumption of values from iteration. Each of these
/// methods suspends after enqueuing the event and is resumed when the next call to `next()`
/// on the `Iterator` is made.
public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
/// The iterator for a `AsyncChannel` instance.
public struct Iterator: AsyncIteratorProtocol, Sendable {
@@ -89,7 +89,11 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
switch self {
case .awaiting(var awaiting):
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
self = .awaiting(awaiting)
if awaiting.isEmpty {
self = .idle
} else {
self = .awaiting(awaiting)
}
return continuation
case .idle:
self = .awaiting([Awaiting(cancelled: generation)])
@@ -127,7 +131,12 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
func next(_ generation: Int) async -> Element? {
return await withUnsafeContinuation { continuation in
var cancelled = false
var terminal = false
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
if state.terminal {
terminal = true
return nil
}
switch state.emission {
case .idle:
state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)])
@@ -145,62 +154,86 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
nexts.remove(Awaiting(placeholder: generation))
cancelled = true
}
state.emission = .awaiting(nexts)
if nexts.isEmpty {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
return nil
}
}?.resume()
if cancelled {
if cancelled || terminal {
continuation.resume(returning: nil)
}
}
}
func _send(_ result: Result<Element?, Never>) async {
let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
if state.terminal {
return UnsafeResumption(continuation: continuation, success: nil)
}
switch result {
case .success(let value):
if value == nil {
state.terminal = true
}
case .failure:
state.terminal = true
}
switch state.emission {
case .idle:
state.emission = .pending([continuation])
return nil
case .pending(var sends):
sends.append(continuation)
state.emission = .pending(sends)
return nil
case .awaiting(var nexts):
let next = nexts.removeFirst().continuation
if nexts.count == 0 {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
return UnsafeResumption(continuation: continuation, success: next)
}
}?.resume()
func finishAll() {
let (sends, nexts) = state.withCriticalRegion { state -> ([UnsafeContinuation<UnsafeContinuation<Element?, Never>?, Never>], Set<Awaiting>) in
if state.terminal {
return ([], [])
}
state.terminal = true
switch state.emission {
case .idle:
return ([], [])
case .pending(let nexts):
state.emission = .idle
return (nexts, [])
case .awaiting(let nexts):
state.emission = .idle
return ([], nexts)
}
}
for send in sends {
send.resume(returning: nil)
}
for next in nexts {
next.continuation?.resume(returning: nil)
}
}
func _send(_ element: Element) async {
await withTaskCancellationHandler {
finishAll()
} operation: {
let continuation: UnsafeContinuation<Element?, Never>? = await withUnsafeContinuation { continuation in
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Never>?, Never>? in
if state.terminal {
return UnsafeResumption(continuation: continuation, success: nil)
}
switch state.emission {
case .idle:
state.emission = .pending([continuation])
return nil
case .pending(var sends):
sends.append(continuation)
state.emission = .pending(sends)
return nil
case .awaiting(var nexts):
let next = nexts.removeFirst().continuation
if nexts.count == 0 {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
return UnsafeResumption(continuation: continuation, success: next)
}
}?.resume()
}
continuation?.resume(returning: element)
}
continuation?.resume(with: result)
}
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
/// If the channel is already finished then this returns immediately
public func send(_ element: Element) async {
await _send(.success(element))
await _send(element)
}
/// Send a finish to an awaiting iteration. This function will resume when the next call to `next()` is made.
/// If the channel is already finished then this returns immediately
public func finish() async {
await _send(.success(nil))
/// Send a finish to all awaiting iterations.
public func finish() {
finishAll()
}
/// Create an `Iterator` for iteration of an `AsyncChannel`
@@ -37,6 +37,7 @@ extension AsyncSequence {
/// error, `AsyncChunkedByGroupSequence` will rethrow that error immediately and discard
/// any current group.
///
/// let numbers = [10, 20, 30, 10, 40, 40, 10, 20].async
/// let chunks = numbers.chunked { $0 <= $1 }
/// for await numberChunk in chunks {
/// print(numberChunk)
@@ -31,25 +31,25 @@ extension AsyncSequence {
}
/// Creates an asynchronous sequence that creates chunks of a given `RangeReplaceableCollection` type of a given count or when an `AsyncTimerSequence` fires.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func chunks<C: Clock, Collected: RangeReplaceableCollection>(ofCount count: Int, or timer: AsyncTimerSequence<C>, into: Collected.Type) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
AsyncChunksOfCountOrSignalSequence(self, count: count, signal: timer)
}
/// Creates an asynchronous sequence that creates chunks of a given count or when an `AsyncTimerSequence` fires.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func chunks<C: Clock>(ofCount count: Int, or timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountOrSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
chunks(ofCount: count, or: timer, into: [Element].self)
}
/// Creates an asynchronous sequence that creates chunks of a given `RangeReplaceableCollection` type when an `AsyncTimerSequence` fires.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func chunked<C: Clock, Collected: RangeReplaceableCollection>(by timer: AsyncTimerSequence<C>, into: Collected.Type) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
AsyncChunksOfCountOrSignalSequence(self, count: nil, signal: timer)
}
/// Creates an asynchronous sequence that creates chunks when an `AsyncTimerSequence` fires.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func chunked<C: Clock>(by timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountOrSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
chunked(by: timer, into: [Element].self)
}
@@ -11,15 +11,15 @@
extension AsyncSequence {
/// Creates an asynchronous sequence that emits the latest element after a given quiescence period
/// has elapsed by using a spectified Clock.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
/// has elapsed by using a specified Clock.
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func debounce<C: Clock>(for interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncDebounceSequence<Self, C> {
AsyncDebounceSequence(self, interval: interval, tolerance: tolerance, clock: clock)
}
/// Creates an asynchronous sequence that emits the latest element after a given quiescence period
/// has elapsed.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func debounce(for interval: Duration, tolerance: Duration? = nil) -> AsyncDebounceSequence<Self, ContinuousClock> {
debounce(for: interval, tolerance: tolerance, clock: .continuous)
}
@@ -27,7 +27,7 @@ extension AsyncSequence {
/// An `AsyncSequence` that emits the latest element after a given quiescence period
/// has elapsed.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable
where Base.AsyncIterator: Sendable, Base.Element: Sendable, Base: Sendable {
let base: Base
@@ -43,7 +43,7 @@ public struct AsyncDebounceSequence<Base: AsyncSequence, C: Clock>: Sendable
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncDebounceSequence: AsyncSequence {
public typealias Element = Base.Element
@@ -22,10 +22,10 @@ extension Sequence {
/// An asynchronous sequence composed from a synchronous sequence.
///
/// Asynchronous lazy sequences can be used to interface existing or pre-calculated
/// data to interoperate with other asynchronous sequences and algoritms based on
/// data to interoperate with other asynchronous sequences and algorithms based on
/// asynchronous sequences.
///
/// This functions similarly to `LazySequence` by accessing elemetns sequentially
/// This functions similarly to `LazySequence` by accessing elements sequentially
/// in the iterator's `next()` method.
@frozen
public struct AsyncLazySequence<Base: Sequence>: AsyncSequence {
@@ -174,7 +174,7 @@ extension Merge2StateMachine.Either where Base1.Element == Base2.Element {
/// An asynchronous sequence of elements from two underlying asynchronous sequences
///
/// In a `AsyncMerge2Sequence` instance, the *i*th element is the *i*th element
/// resolved in sequential order out of the two underyling asynchronous sequences.
/// resolved in sequential order out of the two underlying asynchronous sequences.
/// Use the `merge(_:_:)` function to create an `AsyncMerge2Sequence`.
public struct AsyncMerge2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: AsyncSequence, Sendable
where
@@ -23,7 +23,7 @@ where
/// An asynchronous sequence of elements from three underlying asynchronous sequences
///
/// In a `AsyncMerge3Sequence` instance, the *i*th element is the *i*th element
/// resolved in sequential order out of the two underyling asynchronous sequences.
/// resolved in sequential order out of the two underlying asynchronous sequences.
/// Use the `merge(_:_:_:)` function to create an `AsyncMerge3Sequence`.
public struct AsyncMerge3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>: AsyncSequence, Sendable
where
@@ -206,7 +206,7 @@ where
return try await apply(task1, task2, nil)
// 2 terminal
// these can be permuted in place since they dont need to run two or more tasks at once
// these can be permuted in place since they don't need to run two or more tasks at once
case (.terminal, .terminal, .idle(var iterator3)):
do {
if let value = try await iterator3.next() {
@@ -11,19 +11,19 @@
extension AsyncSequence {
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func throttle<C: Clock, Reduced>(for interval: C.Instant.Duration, clock: C, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> AsyncThrottleSequence<Self, C, Reduced> {
AsyncThrottleSequence(self, interval: interval, clock: clock, reducing: reducing)
}
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func throttle<Reduced>(for interval: Duration, reducing: @Sendable @escaping (Reduced?, Element) async -> Reduced) -> AsyncThrottleSequence<Self, ContinuousClock, Reduced> {
throttle(for: interval, clock: .continuous, reducing: reducing)
}
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func throttle<C: Clock>(for interval: C.Instant.Duration, clock: C, latest: Bool = true) -> AsyncThrottleSequence<Self, C, Element> {
throttle(for: interval, clock: clock) { previous, element in
if latest {
@@ -35,14 +35,14 @@ extension AsyncSequence {
}
/// Create a rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func throttle(for interval: Duration, latest: Bool = true) -> AsyncThrottleSequence<Self, ContinuousClock, Element> {
throttle(for: interval, clock: .continuous, latest: latest)
}
}
/// A rate-limited `AsyncSequence` by emitting values at most every specified interval.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
let base: Base
let interval: C.Instant.Duration
@@ -57,13 +57,14 @@ public struct AsyncThrottleSequence<Base: AsyncSequence, C: Clock, Reduced> {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncThrottleSequence: AsyncSequence {
public typealias Element = Reduced
/// The iterator for an `AsyncThrottleSequence` instance.
public struct Iterator: AsyncIteratorProtocol {
var base: Base.AsyncIterator
var last: C.Instant?
let interval: C.Instant.Duration
let clock: C
let reducing: @Sendable (Reduced?, Base.Element) async -> Reduced
@@ -77,13 +78,15 @@ extension AsyncThrottleSequence: AsyncSequence {
public mutating func next() async rethrows -> Reduced? {
var reduced: Reduced?
let start = clock.now
let start = last ?? clock.now
repeat {
guard let element = try await base.next() else {
return nil
}
let reduction = await reducing(reduced, element)
if start.duration(to: clock.now) >= interval {
let now = clock.now
if start.duration(to: now) >= interval || last == nil {
last = now
return reduction
} else {
reduced = reduction
@@ -97,8 +100,8 @@ extension AsyncThrottleSequence: AsyncSequence {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncThrottleSequence: Sendable where Base: Sendable, Element: Sendable { }
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncThrottleSequence.Iterator: Sendable where Base.AsyncIterator: Sendable { }
@@ -88,7 +88,11 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
switch self {
case .awaiting(var awaiting):
let continuation = awaiting.remove(Awaiting(placeholder: generation))?.continuation
self = .awaiting(awaiting)
if awaiting.isEmpty {
self = .idle
} else {
self = .awaiting(awaiting)
}
return continuation
case .idle:
self = .awaiting([Awaiting(cancelled: generation)])
@@ -125,7 +129,12 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
func next(_ generation: Int) async throws -> Element? {
return try await withUnsafeThrowingContinuation { continuation in
var cancelled = false
var terminal = false
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
if state.terminal {
terminal = true
return nil
}
switch state.emission {
case .idle:
state.emission = .awaiting([Awaiting(generation: generation, continuation: continuation)])
@@ -143,50 +152,80 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
nexts.remove(Awaiting(placeholder: generation))
cancelled = true
}
state.emission = .awaiting(nexts)
if nexts.isEmpty {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
return nil
}
}?.resume()
if cancelled {
if cancelled || terminal {
continuation.resume(returning: nil)
}
}
}
func _send(_ result: Result<Element?, Error>) async {
let continuation: UnsafeContinuation<Element?, Error>? = await withUnsafeContinuation { continuation in
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
if state.terminal {
return UnsafeResumption(continuation: continuation, success: nil)
}
switch result {
case .success(let value):
if value == nil {
func finishAll() {
let (sends, nexts) = state.withCriticalRegion { state -> ([UnsafeContinuation<UnsafeContinuation<Element?, Error>?, Never>], Set<Awaiting>) in
if state.terminal {
return ([], [])
}
state.terminal = true
switch state.emission {
case .idle:
return ([], [])
case .pending(let nexts):
state.emission = .idle
return (nexts, [])
case .awaiting(let nexts):
state.emission = .idle
return ([], nexts)
}
}
for send in sends {
send.resume(returning: nil)
}
for next in nexts {
next.continuation?.resume(returning: nil)
}
}
func _send(_ result: Result<Element, Error>) async {
await withTaskCancellationHandler {
finishAll()
} operation: {
let continuation: UnsafeContinuation<Element?, Error>? = await withUnsafeContinuation { continuation in
state.withCriticalRegion { state -> UnsafeResumption<UnsafeContinuation<Element?, Error>?, Never>? in
if state.terminal {
return UnsafeResumption(continuation: continuation, success: nil)
}
if case .failure = result {
state.terminal = true
}
case .failure:
state.terminal = true
}
switch state.emission {
case .idle:
state.emission = .pending([continuation])
return nil
case .pending(var sends):
sends.append(continuation)
state.emission = .pending(sends)
return nil
case .awaiting(var nexts):
let next = nexts.removeFirst().continuation
if nexts.count == 0 {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
switch state.emission {
case .idle:
state.emission = .pending([continuation])
return nil
case .pending(var sends):
sends.append(continuation)
state.emission = .pending(sends)
return nil
case .awaiting(var nexts):
let next = nexts.removeFirst().continuation
if nexts.count == 0 {
state.emission = .idle
} else {
state.emission = .awaiting(nexts)
}
return UnsafeResumption(continuation: continuation, success: next)
}
return UnsafeResumption(continuation: continuation, success: next)
}
}?.resume()
}?.resume()
}
continuation?.resume(with: result.map { $0 as Element? })
}
continuation?.resume(with: result)
}
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
@@ -201,10 +240,9 @@ public final class AsyncThrowingChannel<Element: Sendable, Failure: Error>: Asyn
await _send(.failure(error))
}
/// Send a finish to an awaiting iteration. This function will resume when the next call to `next()` is made.
/// If the channel is already finished then this returns immediately
public func finish() async {
await _send(.success(nil))
/// Send a finish to all awaiting iterations.
public func finish() {
finishAll()
}
public func makeAsyncIterator() -> Iterator {
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
/// An `AsyncSequence` that produces elements at regular intervals.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
public typealias Element = C.Instant
@@ -71,7 +71,7 @@ public struct AsyncTimerSequence<C: Clock>: AsyncSequence {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncTimerSequence {
/// Create an `AsyncTimerSequence` with a given repeating interval.
public static func repeating(every interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncTimerSequence<C> {
@@ -79,7 +79,7 @@ extension AsyncTimerSequence {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncTimerSequence where C == SuspendingClock {
/// Create an `AsyncTimerSequence` with a given repeating interval.
public static func repeating(every interval: Duration, tolerance: Duration? = nil) -> AsyncTimerSequence<SuspendingClock> {
@@ -87,8 +87,8 @@ extension AsyncTimerSequence where C == SuspendingClock {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncTimerSequence: Sendable { }
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncTimerSequence.Iterator: Sendable { }
-12
View File
@@ -1,12 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@_exported import ClockShims
+1 -1
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
// This is a hack around the fact that we dont have generic effects
// This is a hack around the fact that we don't have generic effects
// alternatively in the use cases we would want `rethrows(unsafe)`
// or something like that to avoid this nifty hack...
@@ -14,10 +14,10 @@ import AsyncAlgorithms
import AsyncSequenceValidation
extension XCTestCase {
func recordFailure(_ description: String, detail: String? = nil, system: Bool = false, at location: AsyncSequenceValidation.SourceLocation) {
func recordFailure(_ description: String, system: Bool = false, at location: AsyncSequenceValidation.SourceLocation) {
#if canImport(Darwin)
let context = XCTSourceCodeContext(location: XCTSourceCodeLocation(filePath: location.file.description, lineNumber: Int(location.line)))
let issue = XCTIssue(type: system ? .system : .assertionFailure, compactDescription: description, detailedDescription: detail, sourceCodeContext: context, associatedError: nil, attachments: [])
let issue = XCTIssue(type: system ? .system : .assertionFailure, compactDescription: description, detailedDescription: nil, sourceCodeContext: context, associatedError: nil, attachments: [])
record(issue)
#else
XCTFail(description, file: location.file, line: location.line)
@@ -26,25 +26,17 @@ extension XCTestCase {
func validate<Test: AsyncSequenceValidationTest, Theme: AsyncSequenceValidationTheme>(theme: Theme, expectedFailures: Set<String>, @AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test, file: StaticString = #file, line: UInt = #line) {
var expectations = expectedFailures
var result: AsyncSequenceValidationDiagram.ExpectationResult?
var failures = [AsyncSequenceValidationDiagram.ExpectationFailure]()
let baseLoc = AsyncSequenceValidation.SourceLocation(file: file, line: line)
var accountedFailures = [AsyncSequenceValidationDiagram.ExpectationFailure]()
do {
let (result, failures) = try AsyncSequenceValidationDiagram.test(theme: theme, build)
var detail: String?
if failures.count > 0 {
detail = """
Expected
\(result.reconstituteExpected(theme: theme))
Actual
\(result.reconstituteActual(theme: theme))
"""
print("Expected")
print(result.reconstituteExpected(theme: theme))
print("Actual")
print(result.reconstituteActual(theme: theme))
}
(result, failures) = try AsyncSequenceValidationDiagram.test(theme: theme, build)
for failure in failures {
if expectations.remove(failure.description) == nil {
recordFailure(failure.description, detail: detail, at: failure.specification?.location ?? baseLoc)
recordFailure(failure.description, at: failure.specification?.location ?? baseLoc)
} else {
accountedFailures.append(failure)
}
}
} catch {
@@ -52,6 +44,18 @@ extension XCTestCase {
recordFailure("\(error)", system: true, at: (error as? SourceFailure)?.location ?? baseLoc)
}
}
// If no failures were expected and the result reconstitues to something different
// than what was expected, dump that out as a failure for easier diagnostics, this
// likely should be done via attachments but that does not display inline code
// nicely. Ideally we would want to have this display as a runtime warning but those
// do not have source line attribution; for now XCTFail is good enough.
if let result = result, expectedFailures.count == 0 {
let expected = result.reconstituteExpected(theme: theme)
let actual = result.reconstituteActual(theme: theme)
if expected != actual {
XCTFail("Validation failure:\nExpected:\n\(expected)\nActual:\n\(actual)", file: file, line: line)
}
}
// any remaining expectations are failures that were expected but did not happen
for expectation in expectations {
XCTFail("Expected failure: \(expectation) did not occur.", file: file, line: line)
@@ -0,0 +1,14 @@
# ``AsyncSequenceValidation``
## Overview
Testing is a critical area of focus for any package to make it robust, catch bugs, and explain the expected behaviors in a documented manner. Testing things that are asynchronous can be difficult, testing things that are asynchronous multiple times can be even more difficult.
Types that implement `AsyncSequence` can often be described in deterministic actions given particular inputs. For the inputs, the events can be described as a discrete set: values, errors being thrown, the terminal state of returning a `nil` value from the iterator, or advancing in time and not doing anything. Likewise, the expected output has a discrete set of events: values, errors being caught, the terminal state of receiving a `nil` value from the iterator, or advancing in time and not doing anything.
## Topics
### Getting Started
- <doc:Validation>
@@ -11,7 +11,7 @@
import _CAsyncSequenceValidationSupport
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
@resultBuilder
public struct AsyncSequenceValidationDiagram : Sendable {
public struct Component<T> {
+2 -2
View File
@@ -11,7 +11,7 @@
import AsyncAlgorithms
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram {
public struct Clock {
let queue: WorkQueue
@@ -22,7 +22,7 @@ extension AsyncSequenceValidationDiagram {
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram.Clock: Clock {
public struct Step: DurationProtocol, Hashable, CustomStringConvertible {
internal var rawValue: Int
+1 -1
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram {
struct Failure: Error, Equatable { }
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
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: .zero)
var now = Clock.Instant(when: .steps(1)) // adjust for the offset index
var reconstituted = ""
while now <= end {
if let results = events[now] {
+1 -1
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram {
public struct Specification: Sendable {
public let specification: String
+1 -1
View File
@@ -11,7 +11,7 @@
import _CAsyncSequenceValidationSupport
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
struct Job: Hashable, @unchecked Sendable {
let job: JobRef
@@ -20,7 +20,7 @@ import _CAsyncSequenceValidationSupport
#endif
#if canImport(Darwin)
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
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 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
final class TaskDriver {
let work: (TaskDriver) -> Void
let queue: WorkQueue
+3 -3
View File
@@ -19,7 +19,7 @@ internal func _swiftJobRun(
_ executor: UnownedSerialExecutor
) -> ()
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public protocol AsyncSequenceValidationTest: Sendable {
var inputs: [AsyncSequenceValidationDiagram.Specification] { get }
var output: AsyncSequenceValidationDiagram.Specification { get }
@@ -27,14 +27,14 @@ public protocol AsyncSequenceValidationTest: Sendable {
func test<C: Clock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram {
struct Test<Operation: AsyncSequence>: AsyncSequenceValidationTest, @unchecked Sendable where Operation.Element == String {
let inputs: [Specification]
let sequence: Operation
let output: Specification
func test<C: ClockShims.Clock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
func test<C: _Concurrency.Clock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
var iterator = sequence.makeAsyncIterator()
do {
for tick in activeTicks {
+3 -3
View File
@@ -9,21 +9,21 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public protocol AsyncSequenceValidationTheme {
func token(_ character: Character, inValue: Bool) -> AsyncSequenceValidationDiagram.Token
func description(for token: AsyncSequenceValidationDiagram.Token) -> String
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationTheme where Self == AsyncSequenceValidationDiagram.ASCIITheme {
public static var ascii: AsyncSequenceValidationDiagram.ASCIITheme {
return AsyncSequenceValidationDiagram.ASCIITheme()
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
extension AsyncSequenceValidationDiagram {
public enum Token: Sendable {
case step
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
struct WorkQueue: Sendable {
enum Item: CustomStringConvertible, Comparable {
case blocked(Token, AsyncSequenceValidationDiagram.Clock.Instant, UnsafeContinuation<Void, Error>)
@@ -144,7 +144,7 @@ struct WorkQueue: Sendable {
items.append(queue.removeFirst())
}
queues[job] = queue
// if there is nothing left in this queue then dont bother with it anymore
// if there is nothing left in this queue then don't bother with it anymore
if queue.count == 0 {
jobsToRemove.insert(jobIndex)
}
-76
View File
@@ -1,76 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// A mechanism in which to measure time, and delay work until a given point
/// in time.
///
/// Types that conform to the `Clock` protocol define a concept of "now" which
/// is the specific instant in time that property is accessed. Any pair of calls
/// to the `now` property may have a minimum duration between them - this
/// minimum resolution is exposed by the `minimumResolution` property to inform
/// any user of the type the expected granularity of accuracy.
///
/// One of the primary uses for clocks is to schedule task sleeping. This method
/// resumes the calling task after a given deadline has been met or passed with
/// a given tolerance value. The tolerance is expected as a leeway around the
/// deadline. The clock may reschedule tasks within the tolerance to ensure
/// efficient execution of resumptions by reducing potential operating system
/// wake-ups. If no tolerance is specified (i.e. nil is passed in) the sleep
/// function is expected to schedule with a default tolerance strategy.
///
/// For more information about specific clocks see `ContinuousClock` and
/// `SuspendingClock`.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public protocol Clock: Sendable {
associatedtype Instant: InstantProtocol
var now: Instant { get }
var minimumResolution: Instant.Duration { get }
func sleep(until deadline: Instant, tolerance: Instant.Duration?) async throws
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Clock {
/// Measure the elapsed time to execute a closure.
///
/// let clock = ContinuousClock()
/// let elapsed = clock.measure {
/// someWork()
/// }
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public func measure(_ work: () throws -> Void) rethrows -> Instant.Duration {
let start = now
try work()
let end = now
return start.duration(to: end)
}
/// Measure the elapsed time to execute an asynchronous closure.
///
/// let clock = ContinuousClock()
/// let elapsed = await clock.measure {
/// await someWork()
/// }
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public func measure(
_ work: () async throws -> Void
) async rethrows -> Instant.Duration {
let start = now
try await work()
let end = now
return start.duration(to: end)
}
}
-173
View File
@@ -1,173 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
#if canImport(Darwin)
@_implementationOnly import Darwin
#elseif canImport(Glibc)
@_implementationOnly import Glibc
#else
#error("Unsupported platform")
#endif
/// A clock that measures time that always increments but does not stop
/// incrementing while the system is asleep.
///
/// `ContinuousClock` can be considered as a stopwatch style time. The frame of
/// reference of the `Instant` may be bound to process launch, machine boot or
/// some other locally defined reference point. This means that the instants are
/// only comparable locally during the execution of a program.
///
/// This clock is suitable for high resolution measurements of execution.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public struct ContinuousClock {
/// A continuous point in time used for `ContinuousClock`.
public struct Instant: Codable, Sendable {
internal var _value: Duration
internal init(_value: Duration) {
self._value = _value
}
}
public init() { }
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Clock where Self == ContinuousClock {
/// A clock that measures time that always increments but does not stop
/// incrementing while the system is asleep.
///
/// try await Task.sleep(until: .now + .seconds(3), clock: .continuous)
///
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public static var continuous: ContinuousClock { return ContinuousClock() }
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension ContinuousClock: Clock {
/// The current continuous instant.
public var now: ContinuousClock.Instant {
ContinuousClock.now
}
/// The minimum non-zero resolution between any two calls to `now`.
public var minimumResolution: Duration {
var ts = timespec()
#if canImport(Darwin)
clock_getres(CLOCK_MONOTONIC, &ts)
#elseif canImport(Glibc)
clock_getres(CLOCK_BOOTTIME, &ts)
#endif
return .seconds(ts.tv_sec) + .nanoseconds(ts.tv_nsec)
}
/// The current continuous instant.
public static var now: ContinuousClock.Instant {
var ts = timespec()
#if canImport(Darwin)
clock_gettime(CLOCK_MONOTONIC, &ts)
#elseif canImport(Glibc)
clock_gettime(CLOCK_BOOTTIME, &ts)
#endif
return ContinuousClock.Instant(_value:
.seconds(ts.tv_sec) + .nanoseconds(ts.tv_nsec))
}
/// Suspend task execution until a given deadline within a tolerance.
/// If no tolerance is specified then the system may adjust the deadline
/// to coalesce CPU wake-ups to more efficiently process the wake-ups in
/// a more power efficient manner.
///
/// If the task is canceled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
public func sleep(
until deadline: Instant, tolerance: Duration? = nil
) async throws {
let duration = deadline - .now
let (seconds, attoseconds) = duration.components
let nanoseconds = attoseconds / 1_000_000_000 + seconds * 1_000_000_000
if nanoseconds > 0 {
try await Task.sleep(nanoseconds: UInt64(nanoseconds))
}
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension ContinuousClock.Instant: InstantProtocol {
public static var now: ContinuousClock.Instant { ContinuousClock.now }
public func advanced(by duration: Duration) -> ContinuousClock.Instant {
return ContinuousClock.Instant(_value: _value + duration)
}
public func duration(to other: ContinuousClock.Instant) -> Duration {
other._value - _value
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
public static func == (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Bool {
return lhs._value == rhs._value
}
public static func < (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Bool {
return lhs._value < rhs._value
}
@_alwaysEmitIntoClient
@inlinable
public static func + (
_ lhs: ContinuousClock.Instant, _ rhs: Duration
) -> ContinuousClock.Instant {
lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func += (
_ lhs: inout ContinuousClock.Instant, _ rhs: Duration
) {
lhs = lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (
_ lhs: ContinuousClock.Instant, _ rhs: Duration
) -> ContinuousClock.Instant {
lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func -= (
_ lhs: inout ContinuousClock.Instant, _ rhs: Duration
) {
lhs = lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Duration {
rhs.duration(to: lhs)
}
}
-318
View File
@@ -1,318 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A representation of high precision time.
///
/// `Duration` represents an elapsed time value with high precision in an
/// integral form. It may be used for measurements of varying clock sources. In
/// those cases it represents the elapsed time measured by that clock.
/// Calculations using `Duration` may span from a negative value to a positive
/// value and have a suitable range to at least cover attosecond scale for both
/// small elapsed durations like sub-second precision to durations that span
/// centuries.
///
/// Typical construction of `Duration` values should be created via the
/// static methods for specific time values.
///
/// var d: Duration = .seconds(3)
/// d += .milliseconds(33)
/// print(d) // 3.033 seconds
///
/// `Duration` itself does not ferry any additional information other than the
/// temporal measurement component; specifically leap seconds should be
/// represented as an additional accessor since that is specific only to certain
/// clock implementations.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@frozen
public struct Duration: Sendable {
/// The low 64 bits of a 128-bit signed integer value counting attoseconds.
@usableFromInline
internal var _low: UInt64
/// The high 64 bits of a 128-bit signed integer value counting attoseconds.
@usableFromInline
internal var _high: Int64
@inlinable
internal init(_high: Int64, low: UInt64) {
self._low = low
self._high = _high
}
internal init(_attoseconds: _Int128) {
self.init(_high: _attoseconds.high, low: _attoseconds.low)
}
/// Construct a `Duration` by adding attoseconds to a seconds value.
///
/// This is useful for when an external decomposed components of a `Duration`
/// has been stored and needs to be reconstituted. Since the values are added
/// no precondition is expressed for the attoseconds being limited to 1e18.
///
/// let d1 = Duration(
/// secondsComponent: 3,
/// attosecondsComponent: 123000000000000000)
/// print(d1) // 3.123 seconds
///
/// let d2 = Duration(
/// secondsComponent: 3,
/// attosecondsComponent: -123000000000000000)
/// print(d2) // 2.877 seconds
///
/// let d3 = Duration(
/// secondsComponent: -3,
/// attosecondsComponent: -123000000000000000)
/// print(d3) // -3.123 seconds
///
/// - Parameters:
/// - secondsComponent: The seconds component portion of the `Duration`
/// value.
/// - attosecondsComponent: The attosecond component portion of the
/// `Duration` value.
public init(secondsComponent: Int64, attosecondsComponent: Int64) {
self = Duration.seconds(secondsComponent) +
Duration(_attoseconds: _Int128(attosecondsComponent))
}
internal var _attoseconds: _Int128 {
_Int128(high: _high, low: _low)
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration {
/// The composite components of the `Duration`.
///
/// This is intended for facilitating conversions to existing time types. The
/// attoseconds value will not exceed 1e18 or be lower than -1e18.
public var components: (seconds: Int64, attoseconds: Int64) {
let (seconds, attoseconds) = _attoseconds.dividedBy1e18()
return (Int64(seconds), Int64(attoseconds))
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration {
/// Construct a `Duration` given a number of seconds represented as a
/// `BinaryInteger`.
///
/// let d: Duration = .seconds(77)
///
/// - Returns: A `Duration` representing a given number of seconds.
public static func seconds<T: BinaryInteger>(_ seconds: T) -> Duration {
return Duration(_attoseconds:
_Int128(seconds).multiplied(by: 1_000_000_000_000_000_000 as UInt64))
}
/// Construct a `Duration` given a number of seconds represented as a
/// `Double` by converting the value into the closest attosecond scale value.
///
/// let d: Duration = .seconds(22.93)
///
/// - Returns: A `Duration` representing a given number of seconds.
public static func seconds(_ seconds: Double) -> Duration {
return Duration(_attoseconds: _Int128(seconds * 1_000_000_000_000_000_000))
}
/// Construct a `Duration` given a number of milliseconds represented as a
/// `BinaryInteger`.
///
/// let d: Duration = .milliseconds(645)
///
/// - Returns: A `Duration` representing a given number of milliseconds.
public static func milliseconds<T: BinaryInteger>(
_ milliseconds: T
) -> Duration {
return Duration(_attoseconds:
_Int128(milliseconds).multiplied(by: 1_000_000_000_000_000 as UInt64))
}
/// Construct a `Duration` given a number of seconds milliseconds as a
/// `Double` by converting the value into the closest attosecond scale value.
///
/// let d: Duration = .milliseconds(88.3)
///
/// - Returns: A `Duration` representing a given number of milliseconds.
public static func milliseconds(_ milliseconds: Double) -> Duration {
return Duration(_attoseconds:
_Int128(milliseconds * 1_000_000_000_000_000))
}
/// Construct a `Duration` given a number of microseconds represented as a
/// `BinaryInteger`.
///
/// let d: Duration = .microseconds(12)
///
/// - Returns: A `Duration` representing a given number of microseconds.
public static func microseconds<T: BinaryInteger>(
_ microseconds: T
) -> Duration {
return Duration(_attoseconds:
_Int128(microseconds).multiplied(by: 1_000_000_000_000 as UInt64))
}
/// Construct a `Duration` given a number of seconds microseconds as a
/// `Double` by converting the value into the closest attosecond scale value.
///
/// let d: Duration = .microseconds(382.9)
///
/// - Returns: A `Duration` representing a given number of microseconds.
public static func microseconds(_ microseconds: Double) -> Duration {
return Duration(_attoseconds:
_Int128(microseconds * 1_000_000_000_000))
}
/// Construct a `Duration` given a number of nanoseconds represented as a
/// `BinaryInteger`.
///
/// let d: Duration = .nanoseconds(1929)
///
/// - Returns: A `Duration` representing a given number of nanoseconds.
public static func nanoseconds<T: BinaryInteger>(
_ nanoseconds: T
) -> Duration {
return Duration(_attoseconds:
_Int128(nanoseconds).multiplied(by: 1_000_000_000))
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let high = try container.decode(Int64.self)
let low = try container.decode(UInt64.self)
self.init(_high: high, low: low)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(_high)
try container.encode(_low)
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(_attoseconds)
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: Equatable {
public static func == (_ lhs: Duration, _ rhs: Duration) -> Bool {
return lhs._attoseconds == rhs._attoseconds
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: Comparable {
public static func < (_ lhs: Duration, _ rhs: Duration) -> Bool {
return lhs._attoseconds < rhs._attoseconds
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: AdditiveArithmetic {
public static var zero: Duration { Duration(_attoseconds: 0) }
public static func + (_ lhs: Duration, _ rhs: Duration) -> Duration {
return Duration(_attoseconds: lhs._attoseconds + rhs._attoseconds)
}
public static func - (_ lhs: Duration, _ rhs: Duration) -> Duration {
return Duration(_attoseconds: lhs._attoseconds - rhs._attoseconds)
}
public static func += (_ lhs: inout Duration, _ rhs: Duration) {
lhs = lhs + rhs
}
public static func -= (_ lhs: inout Duration, _ rhs: Duration) {
lhs = lhs - rhs
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration {
public static func / (_ lhs: Duration, _ rhs: Double) -> Duration {
return Duration(_attoseconds:
_Int128(Double(lhs._attoseconds) / rhs))
}
public static func /= (_ lhs: inout Duration, _ rhs: Double) {
lhs = lhs / rhs
}
public static func / <T: BinaryInteger>(
_ lhs: Duration, _ rhs: T
) -> Duration {
Duration(_attoseconds: lhs._attoseconds / _Int128(rhs))
}
public static func /= <T: BinaryInteger>(_ lhs: inout Duration, _ rhs: T) {
lhs = lhs / rhs
}
public static func / (_ lhs: Duration, _ rhs: Duration) -> Double {
Double(lhs._attoseconds) / Double(rhs._attoseconds)
}
public static func * (_ lhs: Duration, _ rhs: Double) -> Duration {
Duration(_attoseconds: _Int128(Double(lhs._attoseconds) * rhs))
}
public static func * <T: BinaryInteger>(
_ lhs: Duration, _ rhs: T
) -> Duration {
Duration(_attoseconds: lhs._attoseconds * _Int128(rhs))
}
public static func *= <T: BinaryInteger>(_ lhs: inout Duration, _ rhs: T) {
lhs = lhs * rhs
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: CustomStringConvertible {
public var description: String {
return (Double(_attoseconds) / 1e18).description + " seconds"
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Duration: DurationProtocol { }
-35
View File
@@ -1,35 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that defines a duration for a given `InstantProtocol` type.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public protocol DurationProtocol: Comparable, AdditiveArithmetic, Sendable {
static func / (_ lhs: Self, _ rhs: Int) -> Self
static func /= (_ lhs: inout Self, _ rhs: Int)
static func * (_ lhs: Self, _ rhs: Int) -> Self
static func *= (_ lhs: inout Self, _ rhs: Int)
static func / (_ lhs: Self, _ rhs: Self) -> Double
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DurationProtocol {
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public static func /= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs / rhs
}
public static func *= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs * rhs
}
}
-54
View File
@@ -1,54 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// A type that defines a specific point in time for a given `Clock`.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public protocol InstantProtocol: Comparable, Hashable, Sendable {
associatedtype Duration: DurationProtocol
func advanced(by duration: Duration) -> Self
func duration(to other: Self) -> Duration
}
/*
disabled for now - this perturbs operator resolution
extension InstantProtocol {
@_alwaysEmitIntoClient
@inlinable
public static func + (_ lhs: Self, _ rhs: Duration) -> Self {
lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func += (_ lhs: inout Self, _ rhs: Duration) {
lhs = lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (_ lhs: Self, _ rhs: Duration) -> Self {
lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func -= (_ lhs: inout Self, _ rhs: Duration) {
lhs = lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (_ lhs: Self, _ rhs: Self) -> Duration {
rhs.duration(to: lhs)
}
}
*/
File diff suppressed because it is too large. Load diff
-162
View File
@@ -1,162 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
#if canImport(Darwin)
@_implementationOnly import Darwin
#elseif canImport(Glibc)
@_implementationOnly import Glibc
#else
#error("Unsupported platform")
#endif
/// A clock that measures time that always increments but stops incrementing
/// while the system is asleep.
///
/// `SuspendingClock` can be considered as a system awake time clock. The frame
/// of reference of the `Instant` may be bound machine boot or some other
/// locally defined reference point. This means that the instants are
/// only comparable on the same machine in the same booted session.
///
/// This clock is suitable for high resolution measurements of execution.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public struct SuspendingClock {
public struct Instant: Codable, Sendable {
internal var _value: Duration
internal init(_value: Duration) {
self._value = _value
}
}
public init() { }
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Clock where Self == SuspendingClock {
/// A clock that measures time that always increments but stops incrementing
/// while the system is asleep.
///
/// try await Task.sleep(until: .now + .seconds(3), clock: .suspending)
///
public static var suspending: SuspendingClock { return SuspendingClock() }
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension SuspendingClock: Clock {
/// The current instant accounting for machine suspension.
public var now: SuspendingClock.Instant {
SuspendingClock.now
}
/// The current instant accounting for machine suspension.
public static var now: SuspendingClock.Instant {
var ts = timespec()
#if canImport(Darwin)
clock_gettime(CLOCK_UPTIME_RAW, &ts)
#elseif canImport(Glibc)
clock_gettime(CLOCK_MONOTONIC_RAW, &ts)
#endif
return SuspendingClock.Instant(_value:
.seconds(ts.tv_sec) + .nanoseconds(ts.tv_nsec))
}
/// The minimum non-zero resolution between any two calls to `now`.
public var minimumResolution: Duration {
var ts = timespec()
#if canImport(Darwin)
clock_getres(CLOCK_UPTIME_RAW, &ts)
#elseif canImport(Glibc)
clock_getres(CLOCK_MONOTONIC, &ts)
#endif
return .seconds(ts.tv_sec) + .nanoseconds(ts.tv_nsec)
}
/// Suspend task execution until a given deadline within a tolerance.
/// If no tolerance is specified then the system may adjust the deadline
/// to coalesce CPU wake-ups to more efficiently process the wake-ups in
/// a more power efficient manner.
///
/// If the task is canceled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
public func sleep(
until deadline: Instant, tolerance: Duration? = nil
) async throws {
let duration = deadline - .now
let (seconds, attoseconds) = duration.components
let nanoseconds = attoseconds / 1_000_000_000 + seconds * 1_000_000_000
if nanoseconds > 0 {
try await Task.sleep(nanoseconds: UInt64(nanoseconds))
}
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension SuspendingClock.Instant: InstantProtocol {
public static var now: SuspendingClock.Instant { SuspendingClock().now }
public func advanced(by duration: Duration) -> SuspendingClock.Instant {
SuspendingClock.Instant(_value: _value + duration)
}
public func duration(to other: SuspendingClock.Instant) -> Duration {
other._value - _value
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
public static func == (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Bool {
return lhs._value == rhs._value
}
public static func < (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Bool {
return lhs._value < rhs._value
}
public static func + (
_ lhs: SuspendingClock.Instant, _ rhs: Duration
) -> SuspendingClock.Instant {
lhs.advanced(by: rhs)
}
public static func += (
_ lhs: inout SuspendingClock.Instant, _ rhs: Duration
) {
lhs = lhs.advanced(by: rhs)
}
public static func - (
_ lhs: SuspendingClock.Instant, _ rhs: Duration
) -> SuspendingClock.Instant {
lhs.advanced(by: .zero - rhs)
}
public static func -= (
_ lhs: inout SuspendingClock.Instant, _ rhs: Duration
) {
lhs = lhs.advanced(by: .zero - rhs)
}
public static func - (
_ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant
) -> Duration {
rhs.duration(to: lhs)
}
}
-23
View File
@@ -1,23 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Task where Success == Never, Failure == Never {
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@_disfavoredOverload
public static func sleep<C: Clock>(
until deadine: C.Instant,
tolerance: C.Instant.Duration? = nil,
clock: C
) async throws {
try await clock.sleep(until: deadine, tolerance: tolerance)
}
}
@@ -15,13 +15,13 @@ import AsyncAlgorithms
#if canImport(Darwin)
final class TestThroughput: XCTestCase {
func test_chain2() async {
await measureSequenceThroughput(output: 1) {
chain($0, [].async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2) {
chain($0, $1)
}
}
func test_chain3() async {
await measureSequenceThroughput(output: 1) {
chain($0, [].async, [].async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2, thirdOutput: 3) {
chain($0, $1, $2)
}
}
func test_compacted() async {
@@ -40,13 +40,13 @@ final class TestThroughput: XCTestCase {
}
}
func test_merge2() async {
await measureSequenceThroughput(output: 1) {
merge($0, (0..<10).async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2) {
merge($0, $1)
}
}
func test_merge3() async {
await measureSequenceThroughput(output: 1) {
merge($0, (0..<10).async, (0..<10).async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2, thirdOutput: 3) {
merge($0, $1, $2)
}
}
func test_removeDuplicates() async {
@@ -55,13 +55,13 @@ final class TestThroughput: XCTestCase {
}
}
func test_zip2() async {
await measureSequenceThroughput(output: 1) {
zip($0, Indefinite(value: 2).async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2) {
zip($0, $1)
}
}
func test_zip3() async {
await measureSequenceThroughput(output: 1) {
zip($0, Indefinite(value: 2).async, Indefinite(value: 3).async)
await measureSequenceThroughput(firstOutput: 1, secondOutput: 2, thirdOutput: 3) {
zip($0, $1, $2)
}
}
}
@@ -17,19 +17,12 @@ import Foundation
public struct InfiniteAsyncSequence<Value: Sendable>: AsyncSequence, Sendable {
public typealias Element = Value
let value: Value
let duration: Double
public struct AsyncIterator : AsyncIteratorProtocol, Sendable {
@usableFromInline
let value: Value
@usableFromInline
let duration: Double
@usableFromInline
var start: Double? = nil
@inlinable
public mutating func next() async throws -> Element? {
guard !Task.isCancelled else {
@@ -39,7 +32,7 @@ public struct InfiniteAsyncSequence<Value: Sendable>: AsyncSequence, Sendable {
}
}
public func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(value: value, duration: duration)
return AsyncIterator(value: value)
}
}
@@ -68,7 +61,7 @@ extension XCTestCase {
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let infSeq = InfiniteAsyncSequence(value: output(), duration: sampleTime)
let infSeq = InfiniteAsyncSequence(value: output())
let seq = sequenceBuilder(infSeq)
let exp = self.expectation(description: "Finished")
@@ -87,6 +80,57 @@ extension XCTestCase {
}
}
public func measureSequenceThroughput<S: AsyncSequence, Output>(firstOutput: @autoclosure () -> Output, secondOutput: @autoclosure () -> Output, _ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>) -> S) async where S: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let firstInfSeq = InfiniteAsyncSequence(value: firstOutput())
let secondInfSeq = InfiniteAsyncSequence(value: secondOutput())
let seq = sequenceBuilder(firstInfSeq, secondInfSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
for try await _ in seq {
eventCount += 1
}
metric.eventCount = eventCount
exp.fulfill()
return eventCount
}
usleep(UInt32(sampleTime * Double(USEC_PER_SEC)))
iterTask.cancel()
self.wait(for: [exp], timeout: sampleTime * 2)
}
}
public func measureSequenceThroughput<S: AsyncSequence, Output>(firstOutput: @autoclosure () -> Output, secondOutput: @autoclosure () -> Output, thirdOutput: @autoclosure () -> Output, _ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>) -> S) async where S: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let firstInfSeq = InfiniteAsyncSequence(value: firstOutput())
let secondInfSeq = InfiniteAsyncSequence(value: secondOutput())
let thirdInfSeq = InfiniteAsyncSequence(value: thirdOutput())
let seq = sequenceBuilder(firstInfSeq, secondInfSeq, thirdInfSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
for try await _ in seq {
eventCount += 1
}
metric.eventCount = eventCount
exp.fulfill()
return eventCount
}
usleep(UInt32(sampleTime * Double(USEC_PER_SEC)))
iterTask.cancel()
self.wait(for: [exp], timeout: sampleTime * 2)
}
}
public func measureSequenceThroughput<S: AsyncSequence, Source: AsyncSequence>( source: Source, _ sequenceBuilder: (Source) -> S) async where S: Sendable, Source: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
@@ -0,0 +1,60 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@preconcurrency import XCTest
import AsyncAlgorithms
final class TestAdjacentPairs: XCTestCase {
func test_adjacentPairs() async {
let source = 1...5
let expected = [(1,2), (2,3), (3,4), (4,5)]
let sequence = source.async.adjacentPairs()
var actual: [(Int, Int)] = []
for await item in sequence {
actual.append(item)
}
XCTAssertEqual(expected, actual)
}
func test_empty() async {
let source = 0..<1
let expected: [(Int, Int)] = []
let sequence = source.async.adjacentPairs()
var actual: [(Int, Int)] = []
for await item in sequence {
actual.append(item)
}
XCTAssertEqual(expected, actual)
}
func test_cancellation() async {
let source = Indefinite(value: 0)
let sequence = source.async.adjacentPairs()
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var firstIteration = false
for await _ in sequence {
if !firstIteration {
firstIteration = true
iterated.fulfill()
}
}
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
}
}
+194 -23
View File
@@ -13,13 +13,16 @@
import AsyncAlgorithms
final class TestChannel: XCTestCase {
func test_channel() async {
func test_asyncChannel_delivers_values_when_two_producers_and_two_consumers() async {
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
let expected = Set([sentFromProducer1, sentFromProducer2])
let channel = AsyncChannel<String>()
Task {
await channel.send("test1")
await channel.send(sentFromProducer1)
}
Task {
await channel.send("test2")
await channel.send(sentFromProducer2)
}
let t: Task<String?, Never> = Task {
@@ -28,13 +31,17 @@ final class TestChannel: XCTestCase {
return value
}
var iterator = channel.makeAsyncIterator()
let value = await iterator.next()
let other = await t.value
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
let (collectedFromConsumer1, collectedFromConsumer2) = (await t.value, await iterator.next())
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
XCTAssertEqual(collected, expected)
}
func test_throwing_channel() async throws {
func test_asyncThrowingChannel_delivers_values_when_two_producers_and_two_consumers() async throws {
let (sentFromProducer1, sentFromProducer2) = ("test1", "test2")
let expected = Set([sentFromProducer1, sentFromProducer2])
let channel = AsyncThrowingChannel<String, Error>()
Task {
await channel.send("test1")
@@ -49,13 +56,14 @@ final class TestChannel: XCTestCase {
return value
}
var iterator = channel.makeAsyncIterator()
let value = try await iterator.next()
let other = try await t.value
let (collectedFromConsumer1, collectedFromConsumer2) = (try await t.value, try await iterator.next())
let collected = Set([collectedFromConsumer1, collectedFromConsumer2])
XCTAssertEqual(Set([value, other]), Set(["test1", "test2"]))
XCTAssertEqual(collected, expected)
}
func test_throwing() async {
func test_asyncThrowingChannel_throws_when_fail_is_called() async {
let channel = AsyncThrowingChannel<String, Error>()
Task {
await channel.fail(Failure())
@@ -63,37 +71,170 @@ final class TestChannel: XCTestCase {
var iterator = channel.makeAsyncIterator()
do {
let _ = try await iterator.next()
XCTFail()
XCTFail("The AsyncThrowingChannel should have thrown")
} catch {
XCTAssertEqual(error as? Failure, Failure())
}
}
func test_send_finish() async {
func test_asyncChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called() async {
let channel = AsyncChannel<String>()
let complete = ManagedCriticalState(false)
let finished = expectation(description: "finished")
Task {
await channel.finish()
channel.finish()
complete.withCriticalRegion { $0 = true }
finished.fulfill()
}
XCTAssertFalse(complete.withCriticalRegion { $0 })
let value = ManagedCriticalState<String?>(nil)
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
let received = expectation(description: "received")
received.expectedFulfillmentCount = 2
let pastEnd = expectation(description: "pastEnd")
pastEnd.expectedFulfillmentCount = 2
Task {
var iterator = channel.makeAsyncIterator()
let ending = await iterator.next()
value.withCriticalRegion { $0 = ending }
valueFromConsumer1.withCriticalRegion { $0 = ending }
received.fulfill()
let item = await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
Task {
var iterator = channel.makeAsyncIterator()
let ending = await iterator.next()
valueFromConsumer2.withCriticalRegion { $0 = ending }
received.fulfill()
let item = await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
wait(for: [finished, received], timeout: 1.0)
XCTAssertTrue(complete.withCriticalRegion { $0 })
XCTAssertEqual(value.withCriticalRegion { $0 }, nil)
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
wait(for: [pastEnd], timeout: 1.0)
let additionalSend = expectation(description: "additional send")
Task {
await channel.send("test")
additionalSend.fulfill()
}
wait(for: [additionalSend], timeout: 1.0)
}
func test_asyncChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called2() async throws {
let channel = AsyncChannel<String>()
let complete = ManagedCriticalState(false)
let finished = expectation(description: "finished")
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
let received = expectation(description: "received")
received.expectedFulfillmentCount = 2
let pastEnd = expectation(description: "pastEnd")
pastEnd.expectedFulfillmentCount = 2
Task(priority: .high) {
var iterator = channel.makeAsyncIterator()
let ending = await iterator.next()
valueFromConsumer1.withCriticalRegion { $0 = ending }
received.fulfill()
let item = await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
Task(priority: .high) {
var iterator = channel.makeAsyncIterator()
let ending = await iterator.next()
valueFromConsumer2.withCriticalRegion { $0 = ending }
received.fulfill()
let item = await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
try await Task.sleep(nanoseconds: 1_000_000_000)
Task(priority: .low) {
channel.finish()
complete.withCriticalRegion { $0 = true }
finished.fulfill()
}
wait(for: [finished, received], timeout: 1.0)
XCTAssertTrue(complete.withCriticalRegion { $0 })
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
wait(for: [pastEnd], timeout: 1.0)
let additionalSend = expectation(description: "additional send")
Task {
await channel.send("test")
additionalSend.fulfill()
}
wait(for: [additionalSend], timeout: 1.0)
}
func test_asyncThrowingChannel_ends_alls_iterators_and_discards_additional_sent_values_when_finish_is_called() async {
let channel = AsyncThrowingChannel<String, Error>()
let complete = ManagedCriticalState(false)
let finished = expectation(description: "finished")
Task {
channel.finish()
complete.withCriticalRegion { $0 = true }
finished.fulfill()
}
let valueFromConsumer1 = ManagedCriticalState<String?>(nil)
let valueFromConsumer2 = ManagedCriticalState<String?>(nil)
let received = expectation(description: "received")
received.expectedFulfillmentCount = 2
let pastEnd = expectation(description: "pastEnd")
pastEnd.expectedFulfillmentCount = 2
Task {
var iterator = channel.makeAsyncIterator()
let ending = try await iterator.next()
valueFromConsumer1.withCriticalRegion { $0 = ending }
received.fulfill()
let item = try await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
Task {
var iterator = channel.makeAsyncIterator()
let ending = try await iterator.next()
valueFromConsumer2.withCriticalRegion { $0 = ending }
received.fulfill()
let item = try await iterator.next()
XCTAssertNil(item)
pastEnd.fulfill()
}
wait(for: [finished, received], timeout: 1.0)
XCTAssertTrue(complete.withCriticalRegion { $0 })
XCTAssertEqual(valueFromConsumer1.withCriticalRegion { $0 }, nil)
XCTAssertEqual(valueFromConsumer2.withCriticalRegion { $0 }, nil)
wait(for: [pastEnd], timeout: 1.0)
let additionalSend = expectation(description: "additional send")
Task {
@@ -103,7 +244,7 @@ final class TestChannel: XCTestCase {
wait(for: [additionalSend], timeout: 1.0)
}
func test_cancellation() async {
func test_asyncChannel_ends_iterator_when_task_is_cancelled() async {
let channel = AsyncChannel<String>()
let ready = expectation(description: "ready")
let task: Task<String?, Never> = Task {
@@ -116,8 +257,8 @@ final class TestChannel: XCTestCase {
let value = await task.value
XCTAssertNil(value)
}
func test_cancellation_throwing() async throws {
func test_asyncThrowingChannel_ends_iterator_when_task_is_cancelled() async throws {
let channel = AsyncThrowingChannel<String, Error>()
let ready = expectation(description: "ready")
let task: Task<String?, Error> = Task {
@@ -130,4 +271,34 @@ final class TestChannel: XCTestCase {
let value = try await task.value
XCTAssertNil(value)
}
func test_asyncChannel_resumes_send_when_task_is_cancelled() async {
let channel = AsyncChannel<Int>()
let notYetDone = expectation(description: "not yet done")
notYetDone.isInverted = true
let done = expectation(description: "done")
let task = Task {
await channel.send(1)
notYetDone.fulfill()
done.fulfill()
}
wait(for: [notYetDone], timeout: 0.1)
task.cancel()
wait(for: [done], timeout: 1.0)
}
func test_asyncThrowingChannel_resumes_send_when_task_is_cancelled() async {
let channel = AsyncThrowingChannel<Int, Error>()
let notYetDone = expectation(description: "not yet done")
notYetDone.isInverted = true
let done = expectation(description: "done")
let task = Task {
await channel.send(1)
notYetDone.fulfill()
done.fulfill()
}
wait(for: [notYetDone], timeout: 0.1)
task.cancel()
wait(for: [done], timeout: 1.0)
}
}
@@ -12,7 +12,7 @@
import XCTest
import AsyncAlgorithms
final class TestRangeReplacableCollection: XCTestCase {
final class TestRangeReplaceableCollection: XCTestCase {
func test_String() async {
let source = "abc"
let expected = source
@@ -49,7 +49,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdefghijk|"
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
"-b-d-f-h-j-|"
"a-c-e-g-i-k|"
}
}
@@ -57,7 +57,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdefghijk|"
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
"-a-c-e-g-i-|"
"a-b-d-f-h-j|"
}
}
@@ -65,7 +65,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdefghijk|"
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock)
"--c--f--i--|"
"a--d--g--j-|"
}
}
@@ -73,7 +73,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdefghijk|"
$0.inputs[0].throttle(for: .steps(3), clock: $0.clock, latest: false)
"--a--d--g--|"
"a--b--e--h-|"
}
}
@@ -81,7 +81,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdef^hijk|"
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock)
"-b-d-f^"
"a-c-e-^"
}
}
@@ -89,7 +89,7 @@ final class TestThrottle: XCTestCase {
validate {
"abcdef^hijk|"
$0.inputs[0].throttle(for: .steps(2), clock: $0.clock, latest: false)
"-a-c-e^"
"a-b-d-^"
}
}
@@ -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)
"---b---d---f---h---j---|"
"-a---c---e---g---i---k-|"
}
}
}
@@ -12,6 +12,7 @@
import XCTest
import AsyncAlgorithms
import AsyncSequenceValidation
@testable import AsyncAlgorithms_XCTest
final class TestValidationDiagram: XCTestCase {
func test_diagram() {
+89 -42
View File
@@ -13,111 +13,129 @@
import AsyncAlgorithms
final class TestZip2: XCTestCase {
func test_zip() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let expected = Array(zip(a, b))
let actual = await Array(zip(a.async, b.async))
XCTAssertEqual(expected, actual)
}
func test_zip_first_longer() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
let a = [1, 2, 3, 4, 5]
let b = ["a", "b", "c"]
let expected = Array(zip(a, b))
let actual = await Array(zip(a.async, b.async))
XCTAssertEqual(expected, actual)
}
func test_zip_second_longer() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c", "d", "e"]
let expected = Array(zip(a, b))
let actual = await Array(zip(a.async, b.async))
XCTAssertEqual(expected, actual)
}
func test_iterate_past_end() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let sequence = zip(a.async, b.async)
var iterator = sequence.makeAsyncIterator()
let expected = Array(zip(a, b))
var collected = [(Int, String)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_iterate_past_end_first_longer() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
let a = [1, 2, 3, 4, 5]
let b = ["a", "b", "c"]
let sequence = zip(a.async, b.async)
var iterator = sequence.makeAsyncIterator()
let expected = Array(zip(a, b))
var collected = [(Int, String)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_iterate_past_end_second_longer() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c", "d", "e"]
let sequence = zip(a.async, b.async)
var iterator = sequence.makeAsyncIterator()
let expected = Array(zip(a, b))
var collected = [(Int, String)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a"), (2, "b"), (3, "c")], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_first_throwing() async throws {
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let sequence = zip(a.async.map { try throwOn(2, $0) }, b.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a")]
var collected = [(Int, String)]()
do {
while let item = try await iterator.next() {
collected.append(item)
}
XCTFail()
XCTFail("Zipped sequence should throw after one collected element")
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([(1, "a")], collected)
XCTAssertEqual(expected, collected)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_second_throwing() async throws {
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let sequence = zip(a.async, b.async.map { try throwOn("b", $0) })
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a")]
var collected = [(Int, String)]()
do {
while let item = try await iterator.next() {
collected.append(item)
}
XCTFail()
XCTFail("Zipped sequence should throw after one collected element")
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([(1, "a")], collected)
XCTAssertEqual(expected, collected)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_cancellation() async {
func test_zip_finishes_when_iteration_task_is_cancelled() async {
let source1 = Indefinite(value: "test1")
let source2 = Indefinite(value: "test2")
let sequence = zip(source1.async, source2.async)
@@ -143,159 +161,188 @@ final class TestZip2: XCTestCase {
}
final class TestZip3: XCTestCase {
func test_zip() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_all_sequences_have_same_size() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
let actual = await Array(zip(a.async, b.async, c.async))
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
XCTAssertEqual(expected, actual)
}
func test_zip_first_longer() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_first_is_longer() async {
let a = [1, 2, 3, 4, 5]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
let actual = await Array(zip(a.async, b.async, c.async))
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
XCTAssertEqual(expected, actual)
}
func test_zip_second_longer() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_second_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c", "d", "e"]
let c = [1, 2, 3]
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
let actual = await Array(zip(a.async, b.async, c.async))
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
XCTAssertEqual(expected, actual)
}
func test_zip_third_longer() async {
func test_zip_makes_sequence_equivalent_to_synchronous_zip_when_third_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3, 4, 5]
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
let actual = await Array(zip(a.async, b.async, c.async))
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], actual)
XCTAssertEqual(expected, actual)
}
func test_iterate_past_end() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_all_sequences_have_same_size() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let sequence = zip(a.async, b.async, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
var collected = [(Int, String, Int)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_iterate_past_end_first_longer() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_first_is_longer() async {
let a = [1, 2, 3, 4, 5]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let sequence = zip(a.async, b.async, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
var collected = [(Int, String, Int)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_iterate_past_end_second_longer() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_second_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c", "d", "e"]
let c = [1, 2, 3]
let sequence = zip(a.async, b.async, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
var collected = [(Int, String, Int)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_iterate_past_end_third_longer() async {
func test_zip_produces_nil_next_element_when_iteration_is_finished_and_third_is_longer() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3, 4, 5]
let sequence = zip(a.async, b.async, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1), (2, "b", 2), (3, "c", 3)]
var collected = [(Int, String, Int)]()
while let item = await iterator.next() {
collected.append(item)
}
XCTAssertEqual([(1, "a", 1), (2, "b", 2), (3, "c", 3)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_first_throwing() async throws {
func test_zip_produces_one_element_and_throws_when_first_produces_one_element_and_throws() async throws {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let sequence = zip(a.async.map { try throwOn(2, $0) }, b.async, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1)]
var collected = [(Int, String, Int)]()
do {
while let item = try await iterator.next() {
collected.append(item)
}
XCTFail()
XCTFail("Zipped sequence should throw after one collected element")
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([(1, "a", 1)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_second_throwing() async throws {
func test_zip_produces_one_element_and_throws_when_second_produces_one_element_and_throws() async throws {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let sequence = zip(a.async, b.async.map { try throwOn("b", $0) }, c.async)
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1)]
var collected = [(Int, String, Int)]()
do {
while let item = try await iterator.next() {
collected.append(item)
}
XCTFail()
XCTFail("Zipped sequence should throw after one collected element")
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([(1, "a", 1)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_third_throwing() async throws {
func test_zip_produces_one_element_and_throws_when_third_produces_one_element_and_throws() async throws {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
let c = [1, 2, 3]
let sequence = zip(a.async, b.async, c.async.map { try throwOn(2, $0) })
var iterator = sequence.makeAsyncIterator()
let expected = [(1, "a", 1)]
var collected = [(Int, String, Int)]()
do {
while let item = try await iterator.next() {
collected.append(item)
}
XCTFail()
XCTFail("Zipped sequence should throw after one collected element")
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([(1, "a", 1)], collected)
XCTAssertEqual(expected, collected)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_cancellation() async {
func test_zip_finishes_when_iteration_task_is_cancelled() async {
let source1 = Indefinite(value: "test1")
let source2 = Indefinite(value: "test2")
let source3 = Indefinite(value: "test3")
+71
View File
@@ -0,0 +1,71 @@
#!/bin/bash
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2022 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for Swift project authors
#
# Updates the GitHub Pages documentation site thats published from the 'docs'
# subdirectory in the 'gh-pages' branch of this repository.
#
# This script should be run by someone with commit access to the 'gh-pages' branch
# at a regular frequency so that the documentation content on the GitHub Pages site
# is up-to-date with the content in this repo.
#
export BUILDING_FOR_DOCUMENTATION_GENERATION=1
set -eu
# A `realpath` alternative using the default C implementation.
filepath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
SWIFT_ASYNC_ALGORITHMS_ROOT="$(dirname $(dirname $(filepath $0)))"
ASYNC_ALGORITHMS_BUILD_DIR="$SWIFT_ASYNC_ALGORITHMS_ROOT"/.build/async-algorithms-gh-pages-build
# Set current directory to the repository root
cd "$SWIFT_ASYNC_ALGORITHMS_ROOT"
# Use git worktree to checkout the gh-pages branch of this repository in a gh-pages sub-directory
git fetch
git worktree add --checkout gh-pages origin/gh-pages
# Pretty print DocC JSON output so that it can be consistently diffed between commits
export DOCC_JSON_PRETTYPRINT="YES"
# Generate documentation for the 'AsyncAlgorithms' target and output it
# to the /docs subdirectory in the gh-pages worktree directory.
swift package \
--allow-writing-to-directory "$SWIFT_ASYNC_ALGORITHMS_ROOT/gh-pages/docs" \
generate-documentation \
--target AsyncAlgorithms \
--disable-indexing \
--transform-for-static-hosting \
--hosting-base-path swift-async-algorithms \
--output-path "$SWIFT_ASYNC_ALGORITHMS_ROOT/gh-pages/docs"
# Save the current commit we've just built documentation from in a variable
CURRENT_COMMIT_HASH=`git rev-parse --short HEAD`
# Commit and push our changes to the gh-pages branch
cd gh-pages
git add docs
if [ -n "$(git status --porcelain)" ]; then
echo "Documentation changes found. Commiting the changes to the 'gh-pages' branch and pushing to origin."
git commit -m "Update GitHub Pages documentation site to $CURRENT_COMMIT_HASH"
git push origin HEAD:gh-pages
else
# No changes found, nothing to commit.
echo "No documentation changes found."
fi
# Delete the git worktree we created
cd ..
git worktree remove gh-pages