Compare commits

...
Author SHA1 Message Date
Mishal Shah 90e26aa898 [DO NOT MERGE] PR Test 2022-03-30 03:41:10 -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
35 changed files with 328 additions and 2314 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. -->
+49
View File
@@ -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).
+3 -3
View File
@@ -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.
+1 -1
View File
@@ -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
+2 -1
View File
@@ -1,5 +1,6 @@
| Type | Throws | Sendablity |
| Type | Throws | Sendability |
|-----------------------------------------------------|--------------|-------------|
| `AsyncAdjacentPairsSequence` | rethrows | Conditional |
| `AsyncBufferedByteIterator` | throws | Sendable |
| `AsyncBufferSequence` | rethrows | Conditional |
| `AsyncBufferSequence.Iterator` | rethrows | Conditional |
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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.
+1 -3
View File
@@ -12,14 +12,12 @@ 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"])
],
dependencies: [],
targets: [
.target(name: "AsyncAlgorithms", dependencies: ["ClockShims"]),
.target(name: "ClockShims"),
.target(name: "AsyncAlgorithms"),
.target(
name: "AsyncSequenceValidation",
dependencies: ["_CAsyncSequenceValidationSupport", "AsyncAlgorithms"]),
+18 -10
View File
@@ -1,5 +1,6 @@
# swift-async-algorithms
**Swift Async Algorithms** is an open-source package of asynchronous sequence and advanced algorithms that involve concurrency, along with their related types.
This package has three main goals:
@@ -14,7 +15,7 @@ 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
@@ -37,6 +38,7 @@ This package is the home for these APIs. Development and API design take place o
- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions.
#### Other useful asynchronous sequences
- [`adjacentPairs()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/AdjacentPairs.md): Collects tuples of adjacent elements.
- [`chunks(...)` and `chunked(...)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Chunked.md): Collect values into chunks.
- [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Compacted.md): Remove nil values from an asynchronous sequence.
- [`removeDuplicates()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/RemoveDuplicates.md): Remove sequentially adjacent duplicate values.
@@ -44,7 +46,7 @@ This package is the home for these APIs. Development and API design take place o
#### 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.
- [`debounce(for:tolerance:clock:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Debounce.md): Emit values after a quiescence period has been reached.
- [`throttle(for:clock:reducing:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Throttle.md): Ensure a minimum interval has elapsed between events.
- [`AsyncTimerSequence`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Timer.md): Emit the value of now at a given interval repeatedly.
@@ -86,27 +88,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 { }
@@ -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`.
@@ -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> {
+1 -1
View File
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
/// 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
@@ -11,7 +11,7 @@
extension AsyncSequence {
/// Creates an asynchronous sequence that emits the latest element after a given quiescence period
/// has elapsed by using a spectified Clock.
/// has elapsed by using a specified Clock.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public func debounce<C: Clock>(for interval: C.Instant.Duration, tolerance: C.Instant.Duration? = nil, clock: C) -> AsyncDebounceSequence<Self, C> {
AsyncDebounceSequence(self, interval: interval, tolerance: tolerance, clock: clock)
@@ -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() {
-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...
+1 -1
View File
@@ -34,7 +34,7 @@ extension AsyncSequenceValidationDiagram {
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 {
@@ -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
@@ -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,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)
}
}