mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-25 04:27:48 +00:00
Add sequences that chunk values into collections based on a variety of criteria (#55)
* Add sequences that chunk values into collections based on a variety of criteria * Factor out Merge2 logic so its termination behavior can be customized * Rewrite AsyncChunksOfCountAndTriggerSequence in terms of the newly configurable merge state machine * Name changes * Fixed tests * Enable chunked(byTime:) functions * Broken up into one file per sequence
This commit is contained in:
1 parent
eb0ddf54cc
commit
b8242c4a6b
7 files changed
+827
-115
No files matched your search
@@ -0,0 +1,96 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension AsyncSequence {
|
||||
|
||||
@inlinable
|
||||
public func chunked<Collected: RangeReplaceableCollection>(by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool, collectedInto: Collected.Type) -> AsyncChunkedByGroupSequence<Self, Collected> where Collected.Element == Element {
|
||||
AsyncChunkedByGroupSequence(self, grouping: belongInSameGroup)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func chunked(by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool) -> AsyncChunkedByGroupSequence<Self, [Element]> {
|
||||
chunked(by: belongInSameGroup, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct AsyncChunkedByGroupSequence<Base: AsyncSequence, Collected: RangeReplaceableCollection>: AsyncSequence where Collected.Element == Base.Element {
|
||||
public typealias Element = Collected
|
||||
|
||||
@frozen
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
|
||||
@usableFromInline
|
||||
var base: Base.AsyncIterator
|
||||
|
||||
@usableFromInline
|
||||
let grouping: @Sendable (Base.Element, Base.Element) -> Bool
|
||||
|
||||
@usableFromInline
|
||||
init(base: Base.AsyncIterator, grouping: @escaping @Sendable (Base.Element, Base.Element) -> Bool) {
|
||||
self.base = base
|
||||
self.grouping = grouping
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var hangingNext: Base.Element?
|
||||
|
||||
@inlinable
|
||||
public mutating func next() async rethrows -> Collected? {
|
||||
var firstOpt = hangingNext
|
||||
if firstOpt == nil {
|
||||
firstOpt = try await base.next()
|
||||
} else {
|
||||
hangingNext = nil
|
||||
}
|
||||
|
||||
guard let first = firstOpt else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var result: Collected = .init()
|
||||
result.append(first)
|
||||
|
||||
var prev = first
|
||||
while let next = try await base.next() {
|
||||
if grouping(prev, next) {
|
||||
result.append(next)
|
||||
prev = next
|
||||
} else {
|
||||
hangingNext = next
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
let base : Base
|
||||
|
||||
@usableFromInline
|
||||
let grouping : @Sendable (Base.Element, Base.Element) -> Bool
|
||||
|
||||
@inlinable
|
||||
init(_ base: Base, grouping: @escaping @Sendable (Base.Element, Base.Element) -> Bool) {
|
||||
self.base = base
|
||||
self.grouping = grouping
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
Iterator(base: base.makeAsyncIterator(), grouping: grouping)
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncChunkedByGroupSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
|
||||
extension AsyncChunkedByGroupSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable { }
|
||||
@@ -0,0 +1,99 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension AsyncSequence {
|
||||
|
||||
@inlinable
|
||||
public func chunked<Subject : Equatable, Collected: RangeReplaceableCollection>(on projection: @escaping @Sendable (Element) -> Subject, collectedInto: Collected.Type) -> AsyncChunkedOnProjectionSequence<Self, Subject, Collected> {
|
||||
AsyncChunkedOnProjectionSequence(self, projection: projection)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func chunked<Subject : Equatable>(on projection: @escaping @Sendable (Element) -> Subject) -> AsyncChunkedOnProjectionSequence<Self, Subject, [Element]> {
|
||||
chunked(on: projection, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct AsyncChunkedOnProjectionSequence<Base: AsyncSequence, Subject: Equatable, Collected: RangeReplaceableCollection>: AsyncSequence where Collected.Element == Base.Element {
|
||||
public typealias Element = (Subject, Collected)
|
||||
|
||||
@frozen
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
|
||||
@usableFromInline
|
||||
var base: Base.AsyncIterator
|
||||
|
||||
@usableFromInline
|
||||
let projection: @Sendable (Base.Element) -> Subject
|
||||
|
||||
@usableFromInline
|
||||
init(base: Base.AsyncIterator, projection: @escaping @Sendable (Base.Element) -> Subject) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var hangingNext: (Subject, Base.Element)?
|
||||
|
||||
@inlinable
|
||||
public mutating func next() async rethrows -> (Subject, Collected)? {
|
||||
var firstOpt = hangingNext
|
||||
if firstOpt == nil {
|
||||
let nextOpt = try await base.next()
|
||||
if let next = nextOpt {
|
||||
firstOpt = (projection(next), next)
|
||||
}
|
||||
} else {
|
||||
hangingNext = nil
|
||||
}
|
||||
|
||||
guard let first = firstOpt else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var result: Collected = .init()
|
||||
result.append(first.1)
|
||||
|
||||
while let next = try await base.next() {
|
||||
let subj = projection(next)
|
||||
if subj == first.0 {
|
||||
result.append(next)
|
||||
} else {
|
||||
hangingNext = (subj, next)
|
||||
break
|
||||
}
|
||||
}
|
||||
return (first.0, result)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
let base : Base
|
||||
|
||||
@usableFromInline
|
||||
let projection : @Sendable (Base.Element) -> Subject
|
||||
|
||||
@inlinable
|
||||
init(_ base: Base, projection: @escaping @Sendable (Base.Element) -> Subject) {
|
||||
self.base = base
|
||||
self.projection = projection
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
Iterator(base: base.makeAsyncIterator(), projection: projection)
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncChunkedOnProjectionSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
|
||||
extension AsyncChunkedOnProjectionSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable, Subject : Sendable { }
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension AsyncSequence {
|
||||
|
||||
public func chunked<Signal, Collected: RangeReplaceableCollection>(byCount count: Int, andSignal signal: Signal, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence<Self, Collected, Signal> where Collected.Element == Element {
|
||||
AsyncChunksOfCountAndSignalSequence(self, count: count, signal: signal)
|
||||
}
|
||||
|
||||
public func chunked<Signal>(byCount count: Int, andSignal signal: Signal) -> AsyncChunksOfCountAndSignalSequence<Self, [Element], Signal> {
|
||||
chunked(byCount: count, andSignal: signal, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
public func chunked<Signal, Collected: RangeReplaceableCollection>(bySignal signal: Signal, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence<Self, Collected, Signal> where Collected.Element == Element {
|
||||
AsyncChunksOfCountAndSignalSequence(self, count: nil, signal: signal)
|
||||
}
|
||||
|
||||
public func chunked<Signal>(bySignal signal: Signal) -> AsyncChunksOfCountAndSignalSequence<Self, [Element], Signal> {
|
||||
chunked(bySignal: signal, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
public func chunked<C: Clock, Collected: RangeReplaceableCollection>(byCount count: Int, andTime timer: AsyncTimerSequence<C>, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
|
||||
AsyncChunksOfCountAndSignalSequence(self, count: count, signal: timer)
|
||||
}
|
||||
|
||||
public func chunked<C: Clock>(byCount count: Int, andTime timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountAndSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
|
||||
chunked(byCount: count, andTime: timer, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
public func chunked<C: Clock, Collected: RangeReplaceableCollection>(byTime timer: AsyncTimerSequence<C>, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence<Self, Collected, AsyncTimerSequence<C>> where Collected.Element == Element {
|
||||
AsyncChunksOfCountAndSignalSequence(self, count: nil, signal: timer)
|
||||
}
|
||||
|
||||
public func chunked<C: Clock>(byTime timer: AsyncTimerSequence<C>) -> AsyncChunksOfCountAndSignalSequence<Self, [Element], AsyncTimerSequence<C>> {
|
||||
chunked(byTime: timer, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct AsyncChunksOfCountAndSignalSequence<Base: AsyncSequence, Collected: RangeReplaceableCollection, Signal: AsyncSequence>: AsyncSequence, Sendable where Collected.Element == Base.Element, Base: Sendable, Signal: Sendable, Base.AsyncIterator: Sendable, Signal.AsyncIterator: Sendable, Base.Element: Sendable, Signal.Element: Sendable {
|
||||
|
||||
public typealias Element = Collected
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol, Sendable {
|
||||
let count: Int?
|
||||
var state: Merge2StateMachine<Base, Signal>
|
||||
init(base: Base.AsyncIterator, count: Int?, signal: Signal.AsyncIterator) {
|
||||
self.count = count
|
||||
self.state = Merge2StateMachine(base, terminatesOnNil: true, signal)
|
||||
}
|
||||
|
||||
public mutating func next() async rethrows -> Collected? {
|
||||
var result : Collected?
|
||||
while let next = try await state.next() {
|
||||
switch next {
|
||||
case .first(let element):
|
||||
if result == nil {
|
||||
result = Collected()
|
||||
}
|
||||
result!.append(element)
|
||||
if result?.count == count {
|
||||
return result
|
||||
}
|
||||
case .second(_):
|
||||
if result != nil {
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
let base: Base
|
||||
let signal: Signal
|
||||
let count: Int?
|
||||
init(_ base: Base, count: Int?, signal: Signal) {
|
||||
if let count = count {
|
||||
precondition(count > 0)
|
||||
}
|
||||
|
||||
self.base = base
|
||||
self.count = count
|
||||
self.signal = signal
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
return Iterator(base: base.makeAsyncIterator(), count: count, signal: signal.makeAsyncIterator())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension AsyncSequence {
|
||||
|
||||
@inlinable
|
||||
public func chunks<Collected: RangeReplaceableCollection>(ofCount count: Int, collectedInto: Collected.Type) -> AsyncChunksOfCountSequence<Self, [Element]> where Collected.Element == Element {
|
||||
AsyncChunksOfCountSequence(self, count: count)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func chunks(ofCount count: Int) -> AsyncChunksOfCountSequence<Self, [Element]> {
|
||||
chunks(ofCount: count, collectedInto: [Element].self)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct AsyncChunksOfCountSequence<Base: AsyncSequence, Collected: RangeReplaceableCollection>: AsyncSequence where Collected.Element == Base.Element {
|
||||
public typealias Element = Collected
|
||||
|
||||
@frozen
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
|
||||
@usableFromInline
|
||||
var base: Base.AsyncIterator
|
||||
|
||||
@usableFromInline
|
||||
let count: Int
|
||||
|
||||
@usableFromInline
|
||||
init(base: Base.AsyncIterator, count: Int) {
|
||||
self.base = base
|
||||
self.count = count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() async rethrows -> Collected? {
|
||||
guard let first = try await base.next() else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var result: Collected = .init()
|
||||
result.append(first)
|
||||
|
||||
while let next = try await base.next() {
|
||||
result.append(next)
|
||||
if result.count == count {
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
let base : Base
|
||||
|
||||
@usableFromInline
|
||||
let count : Int
|
||||
|
||||
@inlinable
|
||||
init(_ base: Base, count: Int) {
|
||||
precondition(count > 0)
|
||||
self.base = base
|
||||
self.count = count
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeAsyncIterator() -> Iterator {
|
||||
Iterator(base: base.makeAsyncIterator(), count: count)
|
||||
}
|
||||
}
|
||||
|
||||
extension AsyncChunksOfCountSequence : Sendable where Base : Sendable, Base.Element : Sendable { }
|
||||
extension AsyncChunksOfCountSequence.Iterator : Sendable where Base.AsyncIterator : Sendable, Base.Element : Sendable { }
|
||||
@@ -19,6 +19,158 @@ where
|
||||
return AsyncMerge2Sequence(base1, base2)
|
||||
}
|
||||
|
||||
struct Merge2StateMachine<Base1: AsyncSequence, Base2: AsyncSequence>: Sendable where Base1.AsyncIterator: Sendable, Base2.AsyncIterator: Sendable, Base1.Element: Sendable, Base2.Element: Sendable {
|
||||
typealias Element1 = Base1.Element
|
||||
typealias Element2 = Base2.Element
|
||||
|
||||
let iter1TerminatesOnNil : Bool
|
||||
let iter2terminatesOnNil : Bool
|
||||
|
||||
enum Partial: @unchecked Sendable {
|
||||
case first(Result<Element1?, Error>, Base1.AsyncIterator)
|
||||
case second(Result<Element2?, Error>, Base2.AsyncIterator)
|
||||
}
|
||||
|
||||
enum Either {
|
||||
case first(Base1.Element)
|
||||
case second(Base2.Element)
|
||||
}
|
||||
|
||||
var state: (PartialIteration<Base1.AsyncIterator, Partial>, PartialIteration<Base2.AsyncIterator, Partial>)
|
||||
|
||||
init(_ iterator1: Base1.AsyncIterator, terminatesOnNil iter1TerminatesOnNil: Bool = false, _ iterator2: Base2.AsyncIterator, terminatesOnNil iter2terminatesOnNil: Bool = false) {
|
||||
self.iter1TerminatesOnNil = iter1TerminatesOnNil
|
||||
self.iter2terminatesOnNil = iter2terminatesOnNil
|
||||
state = (.idle(iterator1), .idle(iterator2))
|
||||
}
|
||||
|
||||
mutating func apply(_ task1: Task<Merge2StateMachine<Base1, Base2>.Partial, Never>?, _ task2: Task<Merge2StateMachine<Base1, Base2>.Partial, Never>?) async rethrows -> Either? {
|
||||
switch await Task.select([task1, task2].compactMap ({ $0 })).value {
|
||||
case .first(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.0.resolve(result, iterator) else {
|
||||
if iter1TerminatesOnNil {
|
||||
state.1.cancel()
|
||||
return nil
|
||||
}
|
||||
return try await next()
|
||||
}
|
||||
return .first(value)
|
||||
} catch {
|
||||
state.1.cancel()
|
||||
throw error
|
||||
}
|
||||
case .second(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.1.resolve(result, iterator) else {
|
||||
if iter2terminatesOnNil {
|
||||
state.0.cancel()
|
||||
return nil
|
||||
}
|
||||
return try await next()
|
||||
}
|
||||
return .second(value)
|
||||
} catch {
|
||||
state.0.cancel()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func first(_ iterator1: Base1.AsyncIterator) -> Task<Partial, Never> {
|
||||
Task {
|
||||
var iter = iterator1
|
||||
do {
|
||||
let value = try await iter.next()
|
||||
return .first(.success(value), iter)
|
||||
} catch {
|
||||
return .first(.failure(error), iter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func second(_ iterator2: Base2.AsyncIterator) -> Task<Partial, Never> {
|
||||
Task {
|
||||
var iter = iterator2
|
||||
do {
|
||||
let value = try await iter.next()
|
||||
return .second(.success(value), iter)
|
||||
} catch {
|
||||
return .second(.failure(error), iter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it or `nil` if no next element exists.
|
||||
mutating func next() async rethrows -> Either? {
|
||||
if Task.isCancelled {
|
||||
state.0.cancel()
|
||||
state.1.cancel()
|
||||
return nil
|
||||
}
|
||||
switch state {
|
||||
case (.idle(let iterator1), .idle(let iterator2)):
|
||||
let task1 = first(iterator1)
|
||||
let task2 = second(iterator2)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.idle(let iterator1), .pending(let task2)):
|
||||
let task1 = first(iterator1)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.pending(let task1), .idle(let iterator2)):
|
||||
let task2 = second(iterator2)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.idle(var iterator1), .terminal):
|
||||
do {
|
||||
if let value = try await iterator1.next() {
|
||||
state = (.idle(iterator1), .terminal)
|
||||
return .first(value)
|
||||
} else {
|
||||
state = (.terminal, .terminal)
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
state = (.terminal, .terminal)
|
||||
throw error
|
||||
}
|
||||
case (.terminal, .idle(var iterator2)):
|
||||
do {
|
||||
if let value = try await iterator2.next() {
|
||||
state = (.terminal, .idle(iterator2))
|
||||
return .second(value)
|
||||
} else {
|
||||
state = (.terminal, .terminal)
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
state = (.terminal, .terminal)
|
||||
throw error
|
||||
}
|
||||
case (.terminal, .pending(let task2)):
|
||||
return try await apply(nil, task2)
|
||||
case (.pending(let task1), .pending(let task2)):
|
||||
return try await apply(task1, task2)
|
||||
case (.pending(let task1), .terminal):
|
||||
return try await apply(task1, nil)
|
||||
case (.terminal, .terminal):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Merge2StateMachine.Either where Base1.Element == Base2.Element {
|
||||
var value : Base1.Element {
|
||||
switch self {
|
||||
case .first(let val):
|
||||
return val
|
||||
case .second(let val):
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An asynchronous sequence of elements from two underlying asynchronous sequences
|
||||
///
|
||||
/// In a `AsyncMerge2Sequence` instance, the *i*th element is the *i*th element
|
||||
@@ -33,122 +185,13 @@ where
|
||||
public typealias Element = Base1.Element
|
||||
/// An iterator for `AsyncMerge2Sequence`
|
||||
public struct Iterator: AsyncIteratorProtocol, Sendable {
|
||||
enum Partial: @unchecked Sendable {
|
||||
case first(Result<Element?, Error>, Base1.AsyncIterator)
|
||||
case second(Result<Element?, Error>, Base2.AsyncIterator)
|
||||
var state: Merge2StateMachine<Base1, Base2>
|
||||
init(_ base1: Base1.AsyncIterator, _ base2: Base2.AsyncIterator) {
|
||||
state = Merge2StateMachine(base1, base2)
|
||||
}
|
||||
|
||||
var state: (PartialIteration<Base1.AsyncIterator, Partial>, PartialIteration<Base2.AsyncIterator, Partial>)
|
||||
|
||||
init(_ iterator1: Base1.AsyncIterator, _ iterator2: Base2.AsyncIterator) {
|
||||
state = (.idle(iterator1), .idle(iterator2))
|
||||
}
|
||||
|
||||
mutating func apply(_ task1: Task<Partial, Never>?, _ task2: Task<Partial, Never>?) async rethrows -> Element? {
|
||||
switch await Task.select([task1, task2].compactMap { $0 }).value {
|
||||
case .first(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.0.resolve(result, iterator) else {
|
||||
return try await next()
|
||||
}
|
||||
return value
|
||||
} catch {
|
||||
state.1.cancel()
|
||||
throw error
|
||||
}
|
||||
case .second(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.1.resolve(result, iterator) else {
|
||||
return try await next()
|
||||
}
|
||||
return value
|
||||
} catch {
|
||||
state.0.cancel()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func first(_ iterator1: Base1.AsyncIterator) -> Task<Partial, Never> {
|
||||
Task {
|
||||
var iter = iterator1
|
||||
do {
|
||||
let value = try await iter.next()
|
||||
return .first(.success(value), iter)
|
||||
} catch {
|
||||
return .first(.failure(error), iter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func second(_ iterator2: Base2.AsyncIterator) -> Task<Partial, Never> {
|
||||
Task {
|
||||
var iter = iterator2
|
||||
do {
|
||||
let value = try await iter.next()
|
||||
return .second(.success(value), iter)
|
||||
} catch {
|
||||
return .second(.failure(error), iter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it or `nil` if no next element exists.
|
||||
|
||||
public mutating func next() async rethrows -> Element? {
|
||||
if Task.isCancelled {
|
||||
state.0.cancel()
|
||||
state.1.cancel()
|
||||
return nil
|
||||
}
|
||||
switch state {
|
||||
case (.idle(let iterator1), .idle(let iterator2)):
|
||||
let task1 = first(iterator1)
|
||||
let task2 = second(iterator2)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.idle(let iterator1), .pending(let task2)):
|
||||
let task1 = first(iterator1)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.pending(let task1), .idle(let iterator2)):
|
||||
let task2 = second(iterator2)
|
||||
state = (.pending(task1), .pending(task2))
|
||||
return try await apply(task1, task2)
|
||||
case (.idle(var iterator1), .terminal):
|
||||
do {
|
||||
if let value = try await iterator1.next() {
|
||||
state = (.idle(iterator1), .terminal)
|
||||
return value
|
||||
} else {
|
||||
state = (.terminal, .terminal)
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
state = (.terminal, .terminal)
|
||||
throw error
|
||||
}
|
||||
case (.terminal, .idle(var iterator2)):
|
||||
do {
|
||||
if let value = try await iterator2.next() {
|
||||
state = (.terminal, .idle(iterator2))
|
||||
return value
|
||||
} else {
|
||||
state = (.terminal, .terminal)
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
state = (.terminal, .terminal)
|
||||
throw error
|
||||
}
|
||||
case (.terminal, .pending(let task2)):
|
||||
return try await apply(nil, task2)
|
||||
case (.pending(let task1), .pending(let task2)):
|
||||
return try await apply(task1, task2)
|
||||
case (.pending(let task1), .terminal):
|
||||
return try await apply(task1, nil)
|
||||
case (.terminal, .terminal):
|
||||
return nil
|
||||
}
|
||||
return try await state.next()?.value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
enum PartialIteration<Iterator: AsyncIteratorProtocol, Partial: Sendable>: CustomStringConvertible, Sendable where Iterator: Sendable, Iterator.Element: Sendable {
|
||||
enum PartialIteration<Iterator: AsyncIteratorProtocol, Partial: Sendable>: CustomStringConvertible {
|
||||
case idle(Iterator)
|
||||
case pending(Task<Partial, Never>)
|
||||
case terminal
|
||||
@@ -43,3 +43,5 @@ enum PartialIteration<Iterator: AsyncIteratorProtocol, Partial: Sendable>: Custo
|
||||
self = .terminal
|
||||
}
|
||||
}
|
||||
|
||||
extension PartialIteration: Sendable where Iterator: Sendable, Iterator.Element: Sendable { }
|
||||
@@ -0,0 +1,291 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import AsyncSequenceValidation
|
||||
import AsyncAlgorithms
|
||||
|
||||
func sumCharacters(_ array: [String]) -> String {
|
||||
return "\(array.reduce(into: 0) { $0 = $0 + Int($1)! })"
|
||||
}
|
||||
|
||||
func concatCharacters(_ array: [String]) -> String {
|
||||
return array.joined()
|
||||
}
|
||||
|
||||
final class TestChunk: XCTestCase {
|
||||
|
||||
func test_signal_equalChunks() {
|
||||
validate {
|
||||
"ABC- DEF- GHI- |"
|
||||
"---X ---X ---X |"
|
||||
$0.inputs[0].chunked(bySignal: $0.inputs[1]).map(concatCharacters)
|
||||
"---'ABC'---'DEF'---'GHI'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signal_unequalChunks() {
|
||||
validate {
|
||||
"AB- A-ABCDEFGH- |"
|
||||
"--X -X--------X |"
|
||||
$0.inputs[0].chunked(bySignal: $0.inputs[1]).map(concatCharacters)
|
||||
"--'AB'-A--------'ABCDEFGH'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signal_emptyChunks() {
|
||||
validate {
|
||||
"--1--|"
|
||||
"XX-XX|"
|
||||
$0.inputs[0].chunked(bySignal: $0.inputs[1]).map(concatCharacters)
|
||||
"---1-|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signal_error() {
|
||||
validate {
|
||||
"AB^"
|
||||
"---X|"
|
||||
$0.inputs[0].chunked(bySignal: $0.inputs[1]).map(concatCharacters)
|
||||
"--^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signal_unsignaledTrailingChunk() {
|
||||
validate {
|
||||
"111-111|"
|
||||
"---X---|"
|
||||
$0.inputs[0].chunked(bySignal: $0.inputs[1]).map(sumCharacters)
|
||||
"---3---[3|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signalAndCount_signalAlwaysPrevails() {
|
||||
validate {
|
||||
"AB- A-ABCDEFGH- |"
|
||||
"--X -X--------X |"
|
||||
$0.inputs[0].chunked(byCount: 42, andSignal: $0.inputs[1]).map(concatCharacters)
|
||||
"--'AB'-A--------'ABCDEFGH'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signalAndCount_countAlwaysPrevails() {
|
||||
validate {
|
||||
"AB --A-B -|"
|
||||
"-- X---- X|"
|
||||
$0.inputs[0].chunked(byCount: 2, andSignal: $0.inputs[1]).map(concatCharacters)
|
||||
"-'AB'----'AB'-|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signalAndCount_countResetsAfterCount() {
|
||||
validate {
|
||||
"ABCDE -ABCDE |"
|
||||
"----- ------ |"
|
||||
$0.inputs[0].chunked(byCount: 5, andSignal: $0.inputs[1]).map(concatCharacters)
|
||||
"----'ABCDE'-----'ABCDE'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signalAndCount_countResetsAfterSignal() {
|
||||
validate {
|
||||
"AB- ABCDE |"
|
||||
"--X ----- |"
|
||||
$0.inputs[0].chunked(byCount: 5, andSignal: $0.inputs[1]).map(concatCharacters)
|
||||
"--'AB'----'ABCDE'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_signalAndCount_error() {
|
||||
validate {
|
||||
"ABC^"
|
||||
"----X|"
|
||||
$0.inputs[0].chunked(byCount: 5, andSignal: $0.inputs[1]).map(concatCharacters)
|
||||
"---^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_equalChunks() {
|
||||
validate {
|
||||
"ABC- DEF- GHI- |"
|
||||
$0.inputs[0].chunked(byTime: AsyncTimerSequence(interval: .steps(4), clock: $0.clock)).map(concatCharacters)
|
||||
"---'ABC'---'DEF'---'GHI'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_unequalChunks() {
|
||||
validate {
|
||||
"AB------ A------- ABCDEFG- |"
|
||||
$0.inputs[0].chunked(byTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"-------'AB' -------A -------'ABCDEFG'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_emptyChunks() {
|
||||
validate {
|
||||
"-- 1- --|"
|
||||
$0.inputs[0].chunked(byTime: AsyncTimerSequence(interval: .steps(2), clock: $0.clock)).map(concatCharacters)
|
||||
"-- -1 --|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_error() {
|
||||
validate {
|
||||
"AB^"
|
||||
$0.inputs[0].chunked(byTime: AsyncTimerSequence(interval: .steps(5), clock: $0.clock)).map(concatCharacters)
|
||||
"--^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_time_unsignaledTrailingChunk() {
|
||||
validate {
|
||||
"111-111|"
|
||||
$0.inputs[0].chunked(byTime: AsyncTimerSequence(interval: .steps(4), clock: $0.clock)).map(sumCharacters)
|
||||
"---3---[3|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_timeAlwaysPrevails() {
|
||||
validate {
|
||||
"AB------ A------- ABCDEFG- |"
|
||||
$0.inputs[0].chunked(byCount: 42, andTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"-------'AB' -------A -------'ABCDEFG'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countAlwaysPrevails() {
|
||||
validate {
|
||||
"AB --A-B -|"
|
||||
$0.inputs[0].chunked(byCount: 2, andTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"-'AB'----'AB'-|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countResetsAfterCount() {
|
||||
validate {
|
||||
"ABCDE --- ABCDE |"
|
||||
$0.inputs[0].chunked(byCount: 5, andTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"----'ABCDE'--- ----'ABCDE'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_countResetsAfterSignal() {
|
||||
validate {
|
||||
"AB------ ABCDE |"
|
||||
$0.inputs[0].chunked(byCount: 5, andTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"-------'AB' ----'ABCDE'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_timeAndCount_error() {
|
||||
validate {
|
||||
"ABC^"
|
||||
$0.inputs[0].chunked(byCount: 5, andTime: AsyncTimerSequence(interval: .steps(8), clock: $0.clock)).map(concatCharacters)
|
||||
"---^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_count() {
|
||||
validate {
|
||||
"ABC DEF |"
|
||||
$0.inputs[0].chunks(ofCount: 3).map(concatCharacters)
|
||||
"--'ABC'--'DEF'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_count_nonuniformTiming() {
|
||||
validate {
|
||||
"A--B-C --DE-F |"
|
||||
$0.inputs[0].chunks(ofCount: 3).map(concatCharacters)
|
||||
"-----'ABC'-----'DEF'|"
|
||||
}
|
||||
}
|
||||
|
||||
func test_count_trailingChunk() {
|
||||
validate {
|
||||
"11111|"
|
||||
$0.inputs[0].chunks(ofCount: 3).map(sumCharacters)
|
||||
"--3--[2|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_count_error() {
|
||||
validate {
|
||||
"AB^"
|
||||
$0.inputs[0].chunks(ofCount: 3).map(concatCharacters)
|
||||
"--^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_group() {
|
||||
validate {
|
||||
"ABC def GH ij Kl|"
|
||||
$0.inputs[0].chunked(by: { $0.first!.isUppercase == $1.first!.isUppercase }).map(concatCharacters)
|
||||
"---'ABC'--'def'-'GH'-'ij'K[l|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_group_singleValue() {
|
||||
validate {
|
||||
"A----|"
|
||||
$0.inputs[0].chunked(by: { $0.first!.isUppercase == $1.first!.isUppercase }).map(concatCharacters)
|
||||
"-----[A|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_group_singleGroup() {
|
||||
validate {
|
||||
"ABCDE|"
|
||||
$0.inputs[0].chunked(by: { _, _ in true }).map(concatCharacters)
|
||||
"-----['ABCDE'|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_group_error() {
|
||||
validate {
|
||||
"AB^"
|
||||
$0.inputs[0].chunked(by: { $0.first!.isUppercase == $1.first!.isUppercase }).map(concatCharacters)
|
||||
"--^"
|
||||
}
|
||||
}
|
||||
|
||||
func test_projection() {
|
||||
validate {
|
||||
"A'Aa''ab' b'BB''bb' 'cc''CC' |"
|
||||
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
|
||||
"-- - 'AAa' - - 'bBb' - ['cC'|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_projection_singleValue() {
|
||||
validate {
|
||||
"A----|"
|
||||
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
|
||||
"-----[A|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_projection_singleGroup() {
|
||||
validate {
|
||||
"ABCDE|"
|
||||
$0.inputs[0].chunked(on: { _ in 42 }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
|
||||
"-----['ABCDE'|]"
|
||||
}
|
||||
}
|
||||
|
||||
func test_projection_error() {
|
||||
validate {
|
||||
"Aa^"
|
||||
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
|
||||
"--^"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user