Light edit on guides and sequence source docs (rdar://90176127) (#86)

* Light-touch edit on existing guides.

* Light edit on the sequences' source docs.

Co-authored-by: Chris Adamson <cadamson@apple.com>
This commit is contained in:
Chris AdamsonandChris Adamson authored and GitHub committed 2022-03-17 15:14:34 -07:00
1 parent 571bfd1a60
commit 5ac8bb4d07
17 files changed
+95 -78

No files matched your search

+4 -4
View File
@@ -40,13 +40,13 @@ public struct AsyncBufferedByteIterator: AsyncIteratorProtocol, Sendable {
}
```
For each invocation of `next` the iterator will check if a buffer has been filled. If the buffer is filled with some amount of bytes a fast path is taken to directly return a byte out of that buffer. If the buffer is not filled then the read function is invoked to acquire the next filled buffer and then it takes a byte out of that buffer.
For each invocation of `next`, the iterator will check if a buffer has been filled. If the buffer is filled with some amount of bytes, a fast path is taken to directly return a byte out of that buffer. If the buffer is not filled, the read function is invoked to acquire the next filled buffer, at which point it takes a byte out of that buffer.
If the read function returns 0 indicating it read no more bytes the iterator is claimed to be finished and no additional invocations to the read function are made.
If the read function returns `0`, indicating it didn't read any more bytes, the iterator is decided to be finished and no additional invocations to the read function are made.
If the read function throws the error will be thrown by the iteration. Subsequent invocations to the iterator will return nil without invoking the read function.
If the read function throws, the error will be thrown by the iteration. Subsequent invocations to the iterator will then return `nil` without invoking the read function.
During the iteration if the task is cancelled the iteration will check the cancellation only in passes where the read function is invoked and will throw a `CancellationError`.
If the task is cancelled during the iteration, the iteration will check the cancellation only in passes where the read function is invoked, and will throw a `CancellationError`.
### Naming
+5 -5
View File
@@ -20,11 +20,11 @@ for try await line in lines {
}
```
The above example shows how two `AsyncSequence` types can be chained together. In this case it prepends a preamble to the lines content of the file.
The above example shows how two `AsyncSequence` types can be chained together. In this case it prepends a preamble to the `lines` content of the file.
## Detailed Design
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.
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 chain<Base1: AsyncSequence, Base2: AsyncSequence>(_ s1: Base1, _ s2: Base2) -> AsyncChain2Sequence<Base1, Base2> where Base1.Element == Base2.Element
@@ -62,12 +62,12 @@ 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.
When any of the asynchronous sequences being chained together come to their end of iteration the `AsyncChainSequence` iteration proceeds on to the next asynchronous sequence. When the last asynchronous sequence reaches the end of iteration the `AsyncChainSequence` then ends its iteration. At any point in time if one of the comprising asynchronous sequences ever throw an error during iteration the resulting `AsyncChainSequence` iteration will throw that error and end iteration.
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.
The throwing behavior of `AsyncChainSequence` is that it will throw when any of its comprising bases throw, and will not throw when all of its comprising bases do not throw.
At any point in time, if one of the comprising asynchronous sequences throws an error during iteration, the resulting `AsyncChainSequence` iteration will throw that error and end iteration. The throwing behavior of `AsyncChainSequence` is that it will throw when any of its comprising bases throw, and will not throw when all of its comprising bases do not throw.
### Naming
This function's and type's name match the term of art used in other languages and libraries.
This combinator function is a direct analog to the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md).
This combinator function is a direct analog to the synchronous version [defined in the Swift Algorithms package](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md).
+5 -5
View File
@@ -25,7 +25,7 @@ Given some sample inputs the following combined events can be expected.
## Detailed Design
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.
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 combineLatest<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncCombineLatest2Sequence<Base1, Base2>
@@ -62,13 +62,13 @@ public struct AsyncCombineLatest3Sequence<Base1: AsyncSequence, Base2: AsyncSequ
```
The `combineLatest(_:...)` function takes two or more asynchronous sequences as arguments with the resulting `AsyncCombineLatestSequence` which is an asynchronous sequence.
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 it means that 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 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 elemnts 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 base the terminal state of the `AsyncCombineLatestSequence` iteration will only be reached when all of the base iterations reach a terminal state.
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.
The throwing behavior of `AsyncCombineLatestSequence` is that if any of the bases throw then the composed asynchronous sequence then throws on its iteration. If at any point (within the first or afterwards) an error is thrown by any base, the other iterations are cancelled and the thrown error is immediately thrown to the consuming iteration.
The throwing behavior of `AsyncCombineLatestSequence` is that if any of the bases throw, then the composed asynchronous sequence throws on its iteration. If at any point (within the first iteration or afterwards), an error is thrown by any base, the other iterations are cancelled and the thrown error is immediately thrown to the consuming iteration.
### Naming
+4 -4
View File
@@ -3,7 +3,7 @@
[[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncInterspersedSequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestInterspersed.swift)]
Place a given value in between each element of the asynchronous sequence.
Places a given value in between each element of the asynchronous sequence.
```swift
let numbers = [1, 2, 3].async.interspersed(with: 0)
@@ -32,9 +32,9 @@ extension AsyncSequence {
The new `AsyncInterspersedSequence` type represents the asynchronous sequence
when the separator is inserted between each element.
When the base asynchronous sequence can throw on iteration `AsyncInterspersedSequence`
will throw on iteration; when the base does not throw then the iteration of
`AsyncInterspersedSequence` does not.
When the base asynchronous sequence can throw on iteration, `AsyncInterspersedSequence`
will throw on iteration. When the base does not throw, the iteration of
`AsyncInterspersedSequence` does not throw either.
`AsyncInterspersedSequence` is conditionally `Sendable` when the base asynchronous
sequence is `Sendable` and the element is also `Sendable`.
+2 -2
View File
@@ -3,7 +3,7 @@
[[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncLazySequence.swift) |
[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestLazy.swift)]
Converts a non asynchronous sequence into an asynchronous one.
Converts a non-asynchronous sequence into an asynchronous one.
This operation is available for all `Sequence` types.
@@ -17,7 +17,7 @@ to combine with other `AsyncSequence` types to provide well known sources of dat
## Detailed Design
The `.async` property is returns an `AsyncLazySequence` that is generic upon the base `Sequence` it was constructed from.
The `.async` property returns an `AsyncLazySequence` that is generic upon the base `Sequence` it was constructed from.
```swift
extension Sequence {
+6 -6
View File
@@ -25,7 +25,7 @@ Given some sample inputs the following merged events can be expected.
## Detailed Design
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.
This function family and the associated family of return types are prime candidates for variadic generics. Until that proposal is accepted, these will be implemented in terms of two- and three-base sequence cases.
```swift
public func merge<Base1: AsyncSequence, Base2: AsyncSequence>(_ base1: Base1, _ base2: Base2) -> AsyncMerge2Sequence<Base1, Base2>
@@ -64,17 +64,17 @@ public struct AsyncMerge3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Ba
```
The `merge(_:...)` function takes two or more asynchronous sequences as arguments with the resulting `AsyncMergeSequence` which is an asynchronous sequence.
The `merge(_:...)` function takes two or more asynchronous sequences as arguments and produces an `AsyncMergeSequence` which is an asynchronous sequence.
Since the bases comprising the `AsyncMergeSequence` must be iterated concurrently to produce the latest value it means that those sequences must be able to be sent to child tasks. This means that a prerequisite of the bases must be that the base asynchronous sequences, their iterators, and the elements they produce must be `Sendable`.
Since the bases comprising the `AsyncMergeSequence` must be iterated concurrently to produce the latest value, those sequences must be able to be sent to child tasks. This means that a prerequisite of the bases must be that the base asynchronous sequences, their iterators, and the elements they produce must be `Sendable`.
When iterating a `AsyncMergeSequence` it becomes terminal when all of the base asynchronous sequences are terminal; meaning there is no more potential of any elements being produced.
When iterating a `AsyncMergeSequence`, the sequence terminates when all of the base asynchronous sequences terminate, since this means there is no potential for any further elements to be produced.
The throwing behavior of `AsyncMergeSequence` is that if any of the bases throw then the composed asynchronous sequence then throws on its iteration. If at any point an error is thrown by any base, the other iterations are cancelled and the thrown error is immediately thrown to the consuming iteration.
The throwing behavior of `AsyncMergeSequence` is that if any of the bases throw, then the composed asynchronous sequence throws on its iteration. If at any point an error is thrown by any base, the other iterations are cancelled and the thrown error is immediately thrown to the consuming iteration.
### Naming
Since the inherent behavior of `merge(_:...)` merges values from multiple streams into a singular asynchronous sequence the naming is intended to be quite literal. There are precedent terms of art in other frameworks and libraries (listed in the comparison section). Other naming takes the form of "withLatestFrom". This was disregarded since the "with" prefix is often most associated with the passing of a closure and some sort of contextual concept; `withUnsafePointer` or `withUnsafeContinuation` are prime examples.
Since the inherent behavior of `merge(_:...)` merges values from multiple streams into a singular asynchronous sequence, the naming is intended to be quite literal. There are precedent terms of art in other frameworks and libraries (listed in the comparison section). Other naming takes the form of "withLatestFrom". This was disregarded since the "with" prefix is often most associated with the passing of a closure and some sort of contextual concept; `withUnsafePointer` or `withUnsafeContinuation` are prime examples.
### Comparison with other libraries
+30 -20
View File
@@ -5,9 +5,9 @@
## Introduction
Testing is a critical are 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.
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, 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.
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.
## Proposed Solution
@@ -23,7 +23,7 @@ validate {
This syntax can be accomplished with a confluence of utilizing some of the advanced features of XCTest, the concurrency runtime, and result builders. The diagram as listed flows as if each event that would propagate is an event flowing along a column but also it shows the expression progressed over time; describing each event.
By utilizing result builders this same function can accommodate more than one input specification for testing things like `merge`.
By utilizing result builders, this same function can accommodate more than one input specification for testing things like `merge`.
```swift
validate {
@@ -34,7 +34,7 @@ validate {
}
```
Normally testing a function like `merge` would result in either limited expectations or be stochastic in nature. Those approaches are to account for the potential ordering not being deterministic. By taking the approach to have explicit ordering of time defined by the diagram it allows for the test to be predictable. That determinism is sourced directly from the input sequences and the expected correlative output sequence. In short, the syntax of the test inputs and expectations make the execution reliable.
Normally testing a function like `merge` would result in either limited expectations or be stochastic in nature. Those approaches are to account for the potential ordering not being deterministic. Taking the approach of having explicit ordering of time defined by the diagram allows for the test to be predictable. That determinism is sourced directly from the input sequences and the expected correlative output sequence. In short, the syntax of the test inputs and expectations make the execution reliable.
The syntax is trivially parsable (and consequently customizable). By default, the events require only a limited subset of characters for control; such as the advancing in time `-`, or the termination of a sequence by returning nil `|`. However some events may produce strings greater than just one character, other events may happen at the same time, and there is also the cancellation event. This all culminates into a test theme definition of:
@@ -51,7 +51,7 @@ The syntax is trivially parsable (and consequently customizable). By default, th
Because some events may take up more than one character and the alignment is important to the visual progression of events, spaces are not counted as part of the parsed events. A space means that no time is advanced and not event is produced or expected. This means that the string `"a - -b- -"` is equivalent to `"a--b--"`.
Defining a custom theme can then be trivial since the list of expected interactions are well known. For example an emoji based diagram can be easily constructed:
Defining a custom theme can then be trivial, since the list of expected interactions are well known. For example an emoji based diagram can be easily constructed:
```swift
struct EmojiTokens: AsyncSequenceValidationTheme {
@@ -78,7 +78,7 @@ validate(theme: EmojiTokens()) {
## Detailed Design
The public interface for this system comes in two parts - the `AsyncSequenceValidationDiagram` subsystem and the `XCTest` extensions. The most commonly interacted with and most approachable portion is the `XCTest` extension.
The public interface for this system comes in two parts: the `AsyncSequenceValidationDiagram` subsystem and the `XCTest` extensions. The most commonly interacted-with and most approachable portion is the `XCTest` extension.
```swift
extension XCTestCase {
@@ -88,7 +88,7 @@ extension XCTestCase {
}
```
These two methods break down to usage like some of the previously used examples; however the reality of how it works is perhaps the more important portion. For example the code listed below has some interesting points of interest worth mentioning.
These two methods break down to usage like some of the previously used examples. However, the reality of how it works is perhaps the more important portion. For example, the code listed below has some points of interest worth mentioning.
```swift
validate {
@@ -98,13 +98,15 @@ validate {
}
```
The progression of the input sequence can be derived from the `$0.inputs[0]`. This is an `AsyncSequence` with the `Element` type of `String` which at the given input emits an `"a"` at tick 0, a `"b"` at tick 3, a `"c"` at tick 6 and a finish event at tick 10. The output of the middle expression `$0.inputs[0].map { item in await Task { item.capitalized }.value }` is expected to emit an `"A"` at tick 0, a `"B"` at tick 3, a `"C"` at tick 6 and a finish event at tick 10. However careful readers may immediately recognize that the `map` function is asynchronous and schedules work on a separate task. Normally this would pose a distinct hazard at deterministic testing for timing of events, however the `validate` utilizes a specialized hook into the Swift concurrency runtime to schedule the events stepwise and deterministically. This works in a two-fold manner; first it uses a custom `Clock` to schedule events, but also ties that clock into a task driver that ensures enqueued jobs are executed in lock step with that clock.
The progression of the input sequence can be derived from the `$0.inputs[0]`. This is an `AsyncSequence` with the `Element` type of `String` which at the given input emits an `"a"` at tick 0, a `"b"` at tick 3, a `"c"` at tick 6 and a finish event at tick 10. The output of the middle expression `$0.inputs[0].map { item in await Task { item.capitalized }.value }` is expected to emit an `"A"` at tick 0, a `"B"` at tick 3, a `"C"` at tick 6 and a finish event at tick 10.
The underpinnings to make that work are the actual `AsyncSequenceValidationDiagram` subsystem. The XCTest interface does offer a considerably more simple surface area so the diagrams, for approachability, will be broken down into a few key sections. Those sections are the result builder, the diagram clock, the inputs, themes, and expectations/tests.
Careful readers may immediately recognize that the `map` function is asynchronous and schedules work on a separate task. Normally, this would pose a distinct hazard to deterministic testing for timing of events. However, the `validate` utilizes a specialized hook into the Swift concurrency runtime to schedule the events stepwise and deterministically. This works in a two-fold manner: first, it uses a custom `Clock` to schedule events. Second, it ties that clock into a task driver that ensures enqueued jobs are executed in lockstep with that clock.
The underpinnings to make that work are the actual `AsyncSequenceValidationDiagram` subsystem. The `XCTest` interface does offer a considerably more simple surface area so the diagrams will be broken down into a few key sections for approachability. Those sections are the result builder, the diagram clock, the inputs, themes, and expectations/tests.
### Result Builder
The result builder syntax allows for simple and concise diagrams to be built. Those diagrams can come in a few forms, ranging from no inputs to three inputs (it is worth noting the implementation is not limited to just three inputs and can easily be expanded to more as we deem it needed). The builder itself uses the multiple parameter build block functions to ensure the proper ordering if inputs, tested sequences, and outputs.
The result builder syntax allows for simple and concise diagrams to be built. Those diagrams can come in a few forms, ranging from no inputs to three inputs. It is worth noting the implementation is not limited to just three inputs and can easily be expanded to more as we deem it needed. The builder itself uses the multiple parameter build block functions to ensure the proper ordering of inputs, tested sequences, and outputs.
```swift
@resultBuilder
@@ -140,11 +142,15 @@ public struct AsyncSequenceValidationDiagram : Sendable {
}
```
The `AsyncSequenceValidationTest`, `InputList` and `Clock` will be covered in subsequent sections.
The `AsyncSequenceValidationTest`, `InputList`, and `Clock` will be covered in subsequent sections.
### Validation Diagram Clock
One of the key functionalities of the validation diagrams is being able to control time. For proper usage of this testing infrastructure all clock sources must be tied to the `AsyncSequenceValidationDiagram.Clock` that is exposed on the diagram itself. This is the heartbeat of how each columnar input and expectation are produced and consumed. It measures time in an integral manner of `steps`. One step being advanced per event symbol; in the default ASCII diagrams that means `-`, `;`, `|`, `^` and any character value event, or in the case of quoted values like `"'foo'"`, or in grouped events like `"[ab]"`.
One of the key functionalities of the validation diagrams is being able to control time. For proper usage of this testing infrastructure, all clock sources must be tied to the `AsyncSequenceValidationDiagram.Clock` that is exposed on the diagram itself. This is the heartbeat of how each columnar input and expectation are produced and consumed. It measures time in an integral manner of `steps`. One step is advanced per event symbol; in the default ASCII diagrams that means:
* `-`, `;`, `|`, `^`, and any character value event.
* Quoted values like `"'foo'"`.
* Grouped events like `"[ab]"`.
```swift
extension AsyncSequenceValidationDiagram {
@@ -185,7 +191,7 @@ Key notes: the `minimumResolution` of the `AsyncSequenceValidationDiagram.Clock`
### Inputs
The inputs to the validation diagram are lazily constructed with the input parameters built by the result builder syntax. The inputs are `Sendable` `AsyncSequence` conforming types that have their `Element` defined as `String`. The elements produced as defined by the input specification in the result builder. This means that on each tick that an element is defined the next function will resume to return that element (or nil or thrown error depending on the input specification). The `InputList` grants access to the defined inputs lazily.
The inputs to the validation diagram are lazily constructed with the input parameters built by the result builder syntax. The inputs are `Sendable` and `AsyncSequence` conforming types that have their `Element` defined as `String`. The elements are produced as defined by the input specification in the result builder. This means that on each tick that an element is defined, the `next` function will resume to return that element (or return `nil` or throw an error, depending on the input specification). The `InputList` grants access to the defined inputs lazily.
```swift
extension AsyncSequenceValidationDiagram {
@@ -222,7 +228,11 @@ Access to the validation diagram input list is done through calls such as `$0.in
| ` ` | `.skip` | Skip/Ignore | `"a b- |"` |
| | `.value` | Values. | `"ab-|"` |
There are some diagram inputs specifications that are not valid. The three cases are; a step being specified in a group, a nested group, and an unbalanced nesting. Respectively examples of these invalid cases are `"[a-]b|"`, `"[[ab]]|"`, and `"[ab|"`.
There are some diagram input specifications that are not valid. The three cases are:
* A step being specified in a group (`"[a-]b|"`).
* A nested group (`"[[ab]]|"`).
* An unbalanced nesting (`"[ab|"`).
```swift
public protocol AsyncSequenceValidationTheme {
@@ -258,7 +268,7 @@ extension AsyncSequenceValidationDiagram {
This set of interfaces are the primary mechanism in which the simplified XCTest extension rests upon.
Expectations defined by the domain specific language symbology can be roughly expressed as expected results and actual results (this notably avoids cancellation and steps since those are better expressed through the failure reporting system). The expectation failures can express the combination of these expected and actual values; showing when the expectation failure occurred and the kind of expectation failure that happened along with the payload of those actual and expected values.
Expectations defined by the domain specific language symbology can be roughly expressed as expected results and actual results. This notably avoids cancellation and steps, since those are better expressed through the failure reporting system. The expectation failures can express the combination of these expected and actual values. This can also show when the expectation failure occurred and the kind of expectation failure that happened, along with the payload of the actual and expected values.
```swift
extension AsyncSequenceValidationDiagram {
@@ -290,7 +300,7 @@ extension AsyncSequenceValidationDiagram {
}
```
The testing itself reduces down to two methods, one being a default theme parameter of `.ascii`. The test methods execute the validation diagram using a custom scheduling hook from the concurrency runtime such that all events are sequentially processed on a single cooperatively multitasking executed thread. That thread is responsible for ensuring the ordering of the events and the execution of each time delineation such that the order of emissions of any input events are sequential top to bottom: input 0 is emitted first, then input 1 etc. After the ordering of input events the jobs enqueued onto that task driver thread are executed in order of receipt. This ensures the overall order of execution is stable and deterministic but most importantly predictable.
The testing itself reduces down to two methods, one being a default theme parameter of `.ascii`. The test methods execute the validation diagram using a custom scheduling hook from the concurrency runtime such that all events are sequentially processed on a single cooperatively-multitasking executed thread. That thread is responsible for ensuring the ordering of the events and the execution of each time delineation such that the order of emissions of any input events are sequential top to bottom: input 0 is emitted first, then input 1, etc. After the ordering of input events, the jobs enqueued onto that task driver thread are executed in order of receipt. This ensures the overall order of execution is stable and deterministic but, most importantly, predictable.
```swift
public protocol AsyncSequenceValidationTest: Sendable {
@@ -314,19 +324,19 @@ extension AsyncSequenceValidationDiagram {
## Future Directions/Improvements
The emoji diagram theme could be made to be a built in system; it makes for really flashy slides/demos and is really easy to see what is going on (but at the cost of being slightly harder to type).
The emoji diagram theme could be made to be a built-in system. It makes for really flashy slides/demos and makes it really easy to see what is going on, but at the cost of being slightly harder to type.
The testing infrastructure could support with minor alteration testing iteration beyond the terminal cases (either errors being thrown from the iterator or past the first nil return value from `next`). This could help enforce some of the semantical expectations of `AsyncSequence`.
The testing infrastructure could support (with minor alteration) testing iteration beyond the terminal cases, either errors being thrown from the iterator or past the first `nil` return value from `next`. This could help enforce some of the semantical expectations of `AsyncSequence`.
In addition to hooking into the runtime for execution of jobs, the deferred execution of jobs could also be hooked so that a time scale conversion could be made such that any sleep using any clock could map directly to the validation diagram internal clock ticks.
The testing infrastructure could also have support for testing for values that do not have specified order for a given tick. Some race conditions from external systems not under the control of the concurrency runtime may not be accountable. If that were to be a consideration, unordered group tokens could be added. For example the symbols `{` and `}` could be used to represent a group that is unordered. However, since there are not any cases that this really seems useful for the swift-async-algorithms package this is not a priority at this time.
The testing infrastructure could also have support for testing for values that do not have specified order for a given tick. Some race conditions from external systems not under the control of the concurrency runtime may not be accountable. If that were to be a consideration, unordered group tokens could be added. For example the symbols `{` and `}` could be used to represent a group that is unordered. However, since there are not any cases where this really seems useful for the swift-async-algorithms package, this is not a priority at this time.
## Alternatives Considered
The validation diagram system could be retrofitted to accommodate other value types other than strings, however most use cases can easily be expressed in a readable form with minor adjustments to use strings.
The builder functions could pass in N-ary variants of the diagram to enforce the inputs to be specific instead of accessed via the lazy `InputList`. As we may potentially add additional numbers of inputs in the future this seems like a less maintainable implementation even though it may offer slightly more safety and only marginally better spelling; i.e. `$0.inputs[0]` versus `$0.input0` etc.
The builder functions could pass in N-ary variants of the diagram to enforce the inputs to be specific instead of accessed via the lazy `InputList`. As we may potentially add additional numbers of inputs in the future this seems like a less maintainable implementation even though it may offer slightly more safety and only marginally better spelling, i.e., `$0.inputs[0]` versus `$0.input0` etc.
## Credits/Inspiration
+5 -5
View File
@@ -25,7 +25,7 @@ Given some sample inputs the following zipped events can be expected.
## Detailed Design
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.
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>
@@ -64,17 +64,17 @@ public struct AsyncZip3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base
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 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 produce a terminal event by returning nil from their 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.
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 is throwing then the iteration of the `AsyncZipSequence` can throw. If no bases can throw then the `AsyncZipSequence` does not throw.
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 with the 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 caveat differential 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.
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 pretty common usage pattern however leaving a singular type for composition feels considerably more approachable.
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
@@ -13,10 +13,10 @@
/// of a common architecture for AsyncSequences of UInt8s (i.e. byte streams).
///
/// Bytes are read into an internal buffer of `capacity` bytes via the
/// `readFunction`. Invoking next returns bytes from the internal buffer until it's
/// `readFunction`. Invoking `next()` returns bytes from the internal buffer until it's
/// empty, and then suspends and awaits another invocation of `readFunction` to
/// refill. If `readFunction` returns 0 (indicating nothing was read), next() will
/// return nil from then on. Cancellation is checked before each invocation of
/// refill. If `readFunction` returns 0 (indicating nothing was read), `next()` will
/// return `nil` from then on. Cancellation is checked before each invocation of
/// `readFunction`, which means that many calls to `next()` will not check for
/// cancellation.
///
@@ -56,7 +56,7 @@ public struct AsyncBufferedByteIterator: AsyncIteratorProtocol, Sendable {
buffer = _AsyncBytesBuffer(capacity: capacity, readFunction: readFunction)
}
/// Reads a byte out of the buffer if available. When no bytes are available this will trigger a
/// Reads a byte out of the buffer if available. When no bytes are available, this will trigger
/// the read function to reload the buffer and then return the next byte from that buffer.
@inlinable @inline(__always)
public mutating func next() async throws -> UInt8? {
@@ -18,8 +18,8 @@ extension AsyncSequence {
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence.
/// - transform: A closure that combines the previously-reduced result and
/// the next element in the receiving asynchronous sequence, which it returns.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
@@ -37,8 +37,9 @@ extension AsyncSequence {
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence.
/// - transform: A closure that combines the previously-reduced result and
/// the next element in the receiving asynchronous sequence, mutating the
/// previous result instead of returning a value.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
@@ -13,7 +13,8 @@ extension AsyncSequence {
/// ```
///
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// result and the next element in the receiving sequence, and returns
/// the result.
/// - Returns: An asynchronous sequence of the reduced elements.
@inlinable
public func reductions(
@@ -10,21 +10,21 @@
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns an async sequence containing elements of this async sequence with
/// Returns an asynchronous sequence containing elements of this asynchronous sequence with
/// the given separator inserted in between each element.
///
/// Any value of the async sequence's element type can be used as the separator.
/// Any value of the asynchronous sequence's element type can be used as the separator.
///
/// - Parameter separator: Value to insert in between each of this async
/// - Parameter separator: The value to insert in between each of this async
/// sequence’s elements.
/// - Returns: The interspersed async sequence of elements.
/// - Returns: The interspersed asynchronous sequence of elements.
@inlinable
public func interspersed(with separator: Element) -> AsyncInterspersedSequence<Self> {
AsyncInterspersedSequence(self, separator: separator)
}
}
/// An async sequence that presents the elements of a base async sequence of
/// An asynchronous sequence that presents the elements of a base asynchronous sequence of
/// elements with a separator between each of those elements.
public struct AsyncInterspersedSequence<Base: AsyncSequence> {
@usableFromInline
@@ -43,7 +43,7 @@ public struct AsyncInterspersedSequence<Base: AsyncSequence> {
extension AsyncInterspersedSequence: AsyncSequence {
public typealias Element = Base.Element
/// The iterator for an `AsyncInterspersedSequence` async sequence.
/// The iterator for an `AsyncInterspersedSequence` asynchronous sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
internal enum State {
@@ -11,7 +11,7 @@
extension Sequence {
/// An asynchronous sequence containing the same elements as this sequence,
/// but on which operations, such as `map` and `filter`, are
/// but on which operations, such as `map` and `filter`, are
/// implemented asynchronously.
@inlinable
public var async: AsyncLazySequence<Self> {
@@ -26,7 +26,7 @@ extension Sequence {
/// asynchronous sequences.
///
/// This functions similarly to `LazySequence` by accessing elemetns sequentially
/// in the iterators next method.
/// in the iterator's `next()` method.
@frozen
public struct AsyncLazySequence<Base: Sequence>: AsyncSequence {
public typealias Element = Base.Element
@@ -11,7 +11,7 @@
extension AsyncSequence {
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given closure.
/// elements of the asynchronous sequence using the given error-throwing closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as an asynchronous sequence.
@@ -19,7 +19,8 @@ extension AsyncSequence {
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence.
/// the next element in the receiving asynchronous sequence and returns
/// the result. If the closure throws an error, the sequence throws.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
@@ -30,7 +31,7 @@ extension AsyncSequence {
}
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given closure.
/// elements of the asynchronous sequence using the given error-throwing closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as an asynchronous sequence.
@@ -38,7 +39,9 @@ extension AsyncSequence {
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence.
/// the next element in the receiving asynchronous sequence, mutating the
/// previous result instead of returning a value. If the closure throws an
/// error, the sequence throws.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
@@ -47,8 +50,8 @@ extension AsyncSequence {
}
}
/// An asynchronous sequence of applying a transform to the element of an asynchronous sequence and the
/// previously transformed result.
/// An asynchronous sequence of applying an error-throwing transform to the element of
/// an asynchronous sequence and the previously transformed result.
@frozen
public struct AsyncThrowingExclusiveReductionsSequence<Base: AsyncSequence, Element> {
@usableFromInline
@@ -1,6 +1,6 @@
extension AsyncSequence {
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given closure.
/// elements of the asynchronous sequence using the given error-throwing closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as an asynchronous sequence.
@@ -13,7 +13,8 @@ extension AsyncSequence {
/// ```
///
/// - Parameter transform: A closure that combines the previously reduced
/// result and the next element in the receiving sequence.
/// result and the next element in the receiving sequence. If the closure
/// throws an error, the sequence throws.
/// - Returns: An asynchronous sequence of the reduced elements.
@inlinable
public func reductions(
+2 -1
View File
@@ -44,7 +44,8 @@ extension Dictionary {
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
/// the final dictionary, or throws an error if building the dictionary
/// can't proceed.
@inlinable
public init<S: AsyncSequence>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) async throws -> Value) async rethrows where S.Element == (Key, Value) {
self.init()
@@ -12,7 +12,7 @@
extension RangeReplaceableCollection {
/// Creates a new instance of a collection containing the elements of an asynchronous sequence.
///
/// - Parameter surce: The asynchronous sequence of elements for the new collection.
/// - Parameter source: The asynchronous sequence of elements for the new collection.
@inlinable
public init<Source: AsyncSequence>(_ source: Source) async rethrows where Source.Element == Element {
self.init()