From b8242c4a6bc2d2c018c7bedc67d83fefc455629c Mon Sep 17 00:00:00 2001 From: kperryua Date: Wed, 23 Feb 2022 17:17:20 -0800 Subject: [PATCH] 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 --- .../AsyncChunkedByGroupSequence.swift | 96 ++++++ .../AsyncChunkedOnProjectionSequence.swift | 99 ++++++ .../AsyncChunksOfCountAndSignalSequence.swift | 98 ++++++ .../AsyncChunksOfCountSequence.swift | 83 +++++ .../AsyncAlgorithms/AsyncMerge2Sequence.swift | 271 +++++++++------- .../AsyncAlgorithms/PartialIteration.swift | 4 +- Tests/AsyncAlgorithmsTests/TestChunk.swift | 291 ++++++++++++++++++ 7 files changed, 827 insertions(+), 115 deletions(-) create mode 100644 Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift create mode 100644 Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift create mode 100644 Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift create mode 100644 Sources/AsyncAlgorithms/AsyncChunksOfCountSequence.swift create mode 100644 Tests/AsyncAlgorithmsTests/TestChunk.swift diff --git a/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift b/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift new file mode 100644 index 0000000..8960760 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChunkedByGroupSequence.swift @@ -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(by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool, collectedInto: Collected.Type) -> AsyncChunkedByGroupSequence where Collected.Element == Element { + AsyncChunkedByGroupSequence(self, grouping: belongInSameGroup) + } + + @inlinable + public func chunked(by belongInSameGroup: @escaping @Sendable (Element, Element) -> Bool) -> AsyncChunkedByGroupSequence { + chunked(by: belongInSameGroup, collectedInto: [Element].self) + } + +} + +public struct AsyncChunkedByGroupSequence: 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 { } diff --git a/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift b/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift new file mode 100644 index 0000000..c07eb66 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChunkedOnProjectionSequence.swift @@ -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(on projection: @escaping @Sendable (Element) -> Subject, collectedInto: Collected.Type) -> AsyncChunkedOnProjectionSequence { + AsyncChunkedOnProjectionSequence(self, projection: projection) + } + + @inlinable + public func chunked(on projection: @escaping @Sendable (Element) -> Subject) -> AsyncChunkedOnProjectionSequence { + chunked(on: projection, collectedInto: [Element].self) + } + +} + +public struct AsyncChunkedOnProjectionSequence: 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 { } + diff --git a/Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift b/Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift new file mode 100644 index 0000000..4dc8a35 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChunksOfCountAndSignalSequence.swift @@ -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(byCount count: Int, andSignal signal: Signal, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence where Collected.Element == Element { + AsyncChunksOfCountAndSignalSequence(self, count: count, signal: signal) + } + + public func chunked(byCount count: Int, andSignal signal: Signal) -> AsyncChunksOfCountAndSignalSequence { + chunked(byCount: count, andSignal: signal, collectedInto: [Element].self) + } + + public func chunked(bySignal signal: Signal, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence where Collected.Element == Element { + AsyncChunksOfCountAndSignalSequence(self, count: nil, signal: signal) + } + + public func chunked(bySignal signal: Signal) -> AsyncChunksOfCountAndSignalSequence { + chunked(bySignal: signal, collectedInto: [Element].self) + } + + public func chunked(byCount count: Int, andTime timer: AsyncTimerSequence, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence> where Collected.Element == Element { + AsyncChunksOfCountAndSignalSequence(self, count: count, signal: timer) + } + + public func chunked(byCount count: Int, andTime timer: AsyncTimerSequence) -> AsyncChunksOfCountAndSignalSequence> { + chunked(byCount: count, andTime: timer, collectedInto: [Element].self) + } + + public func chunked(byTime timer: AsyncTimerSequence, collectedInto: Collected.Type) -> AsyncChunksOfCountAndSignalSequence> where Collected.Element == Element { + AsyncChunksOfCountAndSignalSequence(self, count: nil, signal: timer) + } + + public func chunked(byTime timer: AsyncTimerSequence) -> AsyncChunksOfCountAndSignalSequence> { + chunked(byTime: timer, collectedInto: [Element].self) + } + +} + +public struct AsyncChunksOfCountAndSignalSequence: 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 + 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()) + } +} diff --git a/Sources/AsyncAlgorithms/AsyncChunksOfCountSequence.swift b/Sources/AsyncAlgorithms/AsyncChunksOfCountSequence.swift new file mode 100644 index 0000000..abaab98 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChunksOfCountSequence.swift @@ -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(ofCount count: Int, collectedInto: Collected.Type) -> AsyncChunksOfCountSequence where Collected.Element == Element { + AsyncChunksOfCountSequence(self, count: count) + } + + @inlinable + public func chunks(ofCount count: Int) -> AsyncChunksOfCountSequence { + chunks(ofCount: count, collectedInto: [Element].self) + } + +} + +public struct AsyncChunksOfCountSequence: 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 { } diff --git a/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift b/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift index 9ce9f53..ac220ec 100644 --- a/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift +++ b/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift @@ -19,6 +19,158 @@ where return AsyncMerge2Sequence(base1, base2) } +struct Merge2StateMachine: 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, Base1.AsyncIterator) + case second(Result, Base2.AsyncIterator) + } + + enum Either { + case first(Base1.Element) + case second(Base2.Element) + } + + var state: (PartialIteration, PartialIteration) + + 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.Partial, Never>?, _ task2: Task.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 { + 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 { + 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, Base1.AsyncIterator) - case second(Result, Base2.AsyncIterator) + var state: Merge2StateMachine + init(_ base1: Base1.AsyncIterator, _ base2: Base2.AsyncIterator) { + state = Merge2StateMachine(base1, base2) } - - var state: (PartialIteration, PartialIteration) - - init(_ iterator1: Base1.AsyncIterator, _ iterator2: Base2.AsyncIterator) { - state = (.idle(iterator1), .idle(iterator2)) - } - - mutating func apply(_ task1: Task?, _ task2: Task?) 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 { - 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 { - 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 } } diff --git a/Sources/AsyncAlgorithms/PartialIteration.swift b/Sources/AsyncAlgorithms/PartialIteration.swift index 226d3c6..1404ddc 100644 --- a/Sources/AsyncAlgorithms/PartialIteration.swift +++ b/Sources/AsyncAlgorithms/PartialIteration.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -enum PartialIteration: CustomStringConvertible, Sendable where Iterator: Sendable, Iterator.Element: Sendable { +enum PartialIteration: CustomStringConvertible { case idle(Iterator) case pending(Task) case terminal @@ -43,3 +43,5 @@ enum PartialIteration: Custo self = .terminal } } + +extension PartialIteration: Sendable where Iterator: Sendable, Iterator.Element: Sendable { } diff --git a/Tests/AsyncAlgorithmsTests/TestChunk.swift b/Tests/AsyncAlgorithmsTests/TestChunk.swift new file mode 100644 index 0000000..b00ee88 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestChunk.swift @@ -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!)} ) ) } + "--^" + } + } +}