From e7c671649979212e354fd741946f09880a4978f3 Mon Sep 17 00:00:00 2001 From: Todd Thomas Date: Tue, 9 Mar 2021 00:48:58 -0700 Subject: [PATCH] Add lazy `split` implementation. (#78) `split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and `split(separator:maxSplits:omittingEmptySubsequences:)` now operate lazily when called on `LazySequenceProtocol`- or `LazyCollectionProtocol`-conforming values. In the latter case, no additional storage is allocated on the heap. --- Guides/LazySplit.md | 80 ++ README.md | 1 + Sources/Algorithms/LazySplit.swift | 750 ++++++++++++++++ .../SwiftAlgorithmsTests/LazySplitTests.swift | 840 ++++++++++++++++++ 4 files changed, 1671 insertions(+) create mode 100644 Guides/LazySplit.md create mode 100644 Sources/Algorithms/LazySplit.swift create mode 100644 Tests/SwiftAlgorithmsTests/LazySplitTests.swift diff --git a/Guides/LazySplit.md b/Guides/LazySplit.md new file mode 100644 index 0000000..08bb1b7 --- /dev/null +++ b/Guides/LazySplit.md @@ -0,0 +1,80 @@ +# LazySplit + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/LazySplit.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/LazySplitTests.swift)] + +Lazily-evaluating versions of +[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](https://developer.apple.com/documentation/swift/sequence/3128814-split) +and [`split(separator:maxSplits:omittingEmptySubsequences:)`](https://developer.apple.com/documentation/swift/sequence/3128818-split), +performing the same operation as their counterparts defined on +`Sequence` and `Collection`, are added to `LazySequence` and +`LazyCollection`. The `LazyCollection` methods allow splitting a +collection without allocating additional storage on the heap. + +```swift +// Splitting a lazy sequence. +let numbers = stride(from: 1, through: 16, by: 1) +for subsequence in numbers.lazy.split( + whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } +) { + print(subsequence) +} +/* Prints: +[1, 2] +[4] +[7, 8] +[11] +[13, 14] +[16] +*/ + +// Splitting a lazy collection. +let line = "BLANCHE: I don't want realism. I want magic!" +for subsequence in line.lazy.split(separator: " ") { + print(subsequence) +} +/* Prints +BLANCHE: +I +don't +want +realism. +I +want +magic! +*/ +``` + +## Detailed Design + +`LazySequence` and `LazyCollection` are each extended with +`split(maxSplits:omittingEmptySubsequences:whereSeparator:)` and +`split(separator:maxSplits:omittingEmptySubsequences:)`. + +The `LazySequence` versions of those methods return an instance of +`LazySplitSequence`. The `LazyCollection` versions return an instance of +`LazySplitCollection`. + +`LazySplitSequence` wraps the sequence to be split, and provides an +iterator whose `next` method returns a newly-allocated array containing +the elements of each subsequence in the split sequence in turn. + +`LazySplitCollection` wraps the collection to be split. Its `Index` +wraps a range of base collection indices. `startIndex` is computed at +initialization. Subscripting a `LazySplitCollection` instance returns +the slice of the original collection which is the subsequence of the +split collection at the given index's position. + +### Complexity + +Iterating a `LazySplitSequence` instance is O(_n_) in time and space, +since each subsequence returned is a newly-allocated array. + +Iterating a `LazySplitCollection` instance is O(_n_) in time and O(1) in +space, since each subsequence returned is a slice of the base +collection. Since `startIndex` is computed at initialization, some or +all of the time cost may be paid at initialization. For example, if the +base collection contains no elements determined to be separators, it +will be iterated entirely on initialization of the split collection, and +all subsequent operations on the split collection, such as +`index(after:)`, will have complexity O(1). diff --git a/README.md b/README.md index 9e7a086..789774a 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Read more about the package, and the intent behind it, in the [announcement on s - [`trimming(while:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Trim.md): Returns a slice by trimming elements from a collection's start and end. - [`windows(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Windows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection. - [`striding(by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Stride.md): Returns every nth element of a collection. +- [`split(maxSplits:omittingEmptySubsequences:whereSeparator)`, `split(separator:maxSplits:omittingEmptySubsequences)`](https://github.com/apple/swift-algorithms/blob/main/Guides/LazySplit.md): Lazy versions of the Standard Library's eager operations that split sequences and collections into subsequences separated by the specified separator element. ## Adding Swift Algorithms as a Dependency diff --git a/Sources/Algorithms/LazySplit.swift b/Sources/Algorithms/LazySplit.swift new file mode 100644 index 0000000..5f6dae6 --- /dev/null +++ b/Sources/Algorithms/LazySplit.swift @@ -0,0 +1,750 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift 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 +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// LazySplitSequence +//===----------------------------------------------------------------------===// +/// A sequence that lazily splits a base sequence into subsequences separated by +/// elements that satisfy the given `whereSeparator` predicate. +/// +/// - Note: This type is the result of +/// +/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator) +/// x.split(separator:maxSplits:omittingEmptySubsequences) +/// +/// where `x` conforms to `LazySequenceProtocol`. +public struct LazySplitSequence { + @usableFromInline + internal let base: Base + + @usableFromInline + internal let isSeparator: (Base.Element) -> Bool + + @usableFromInline + internal let maxSplits: Int + + @usableFromInline + internal let omittingEmptySubsequences: Bool + + @usableFromInline + internal init( + base: Base, + isSeparator: @escaping (Base.Element) -> Bool, + maxSplits: Int, + omittingEmptySubsequences: Bool + ) { + self.base = base + self.isSeparator = isSeparator + self.maxSplits = maxSplits + self.omittingEmptySubsequences = omittingEmptySubsequences + } +} + +extension LazySplitSequence { + public struct Iterator { + public typealias Element = [Base.Element] + + @usableFromInline + internal var base: Base.Iterator + + @usableFromInline + internal let isSeparator: (Base.Element) -> Bool + + @usableFromInline + internal let maxSplits: Int + + @usableFromInline + internal let omittingEmptySubsequences: Bool + + /// The number of splits performed. + @usableFromInline + internal var splitCount = 0 + + /// The number of subsequences returned. + @usableFromInline + internal var sequenceLength = 0 + + @usableFromInline + internal init( + base: Base.Iterator, + whereSeparator: @escaping (Base.Element) -> Bool, + maxSplits: Int, + omittingEmptySubsequences: Bool + ) { + self.base = base + self.isSeparator = whereSeparator + self.maxSplits = maxSplits + self.omittingEmptySubsequences = omittingEmptySubsequences + } + } +} + +extension LazySplitSequence.Iterator: IteratorProtocol { + @inlinable + public mutating func next() -> Element? { + var currentElement = base.next() + var subsequence: Element = [] + + // Add the next elements of the base sequence to this subsequence, until we + // reach a separator, unless we've already split the maximum number of + // times. In all cases, stop at the end of the base sequence. + while currentElement != nil { + if splitCount < maxSplits && isSeparator(currentElement!) { + if omittingEmptySubsequences && subsequence.isEmpty { + // Keep going if we don't want to return an empty subsequence. + currentElement = base.next() + continue + } else { + splitCount += 1 + break + } + } else { + subsequence.append(currentElement!) + currentElement = base.next() + } + } + + // We're done iterating when we've reached the end of the base sequence, + // and we've either returned the maximum number of subsequences (one more + // than the number of separators), or the only subsequence left to return is + // empty and we're omitting those. + if currentElement == nil + && (sequenceLength == splitCount + 1 + || omittingEmptySubsequences && subsequence.isEmpty) + { + return nil + } else { + sequenceLength += 1 + return subsequence + } + } +} + +extension LazySplitSequence: LazySequenceProtocol { + @inlinable + public func makeIterator() -> Iterator { + return Iterator( + base: base.makeIterator(), + whereSeparator: self.isSeparator, + maxSplits: self.maxSplits, + omittingEmptySubsequences: self.omittingEmptySubsequences + ) + } +} + +extension LazySequenceProtocol { + /// Lazily returns the longest possible subsequences of the sequence, in + /// order, that don't contain elements satisfying the given predicate. + /// + /// The resulting lazy sequence consists of at most `maxSplits + 1` + /// subsequences. Elements that are used to split the sequence are not + /// returned as part of any subsequence (except possibly the last one, in the + /// case where `maxSplits` is less than the number of separators in the + /// sequence). + /// + /// The following examples show the effects of the `maxSplits` and + /// `omittingEmptySubsequences` parameters when lazily splitting a sequence of + /// integers using a closure that matches numbers evenly divisible by 3 or 5. + /// The first use of `split` returns each subsequence that was originally + /// separated by one or more such numbers. + /// + /// let numbers = stride(from: 1, through: 16, by: 1) + /// for subsequence in numbers.lazy.split( + /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } + /// ) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [4] + /// [7, 8] + /// [11] + /// [13, 14] + /// [16] + /// */ + /// + /// The second example passes `1` for the `maxSplits` parameter, so the + /// original sequence is split just once, into two subsequences. + /// + /// for subsequence in numbers.lazy.split( + /// maxSplits: 1, + /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } + /// ) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + /// */ + /// + /// The final example passes `false` for the `omittingEmptySubsequences` + /// parameter, so the sequence of returned subsequences contains empty + /// subsequences where numbers evenly divisible by 3 or 5 were repeated. + /// + /// for subsequence in numbers.lazy.split( + /// omittingEmptySubsequences: false, + /// whereSeparator: { $0 % 3 == 0 || $0 % 5 == 0 } + /// ) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [4] + /// [] + /// [7, 8] + /// [] + /// [11] + /// [13, 14] + /// [16] + /// */ + /// + /// - Parameters: + /// - maxSplits: The maximum number of times to split the sequence, or + /// one less than the number of subsequences to return. If + /// `maxSplits + 1` subsequences are returned, the last one is a suffix + /// of the original sequence containing the remaining elements. + /// `maxSplits` must be greater than or equal to zero. The default value + /// is `Int.max`. + /// - omittingEmptySubsequences: If `false`, an empty subsequence is + /// returned in the result for each pair of consecutive elements + /// satisfying the `isSeparator` predicate and for each element at the + /// start or end of the sequence satisfying the `isSeparator` + /// predicate. The default value is `true`. + /// - whereSeparator: A closure that takes an element as an argument and + /// returns a Boolean value indicating whether the sequence should be + /// split at that element. + /// - Returns: A lazy sequence of subsequences, split from this sequence's + /// elements. + /// + /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable + public func split( + maxSplits: Int = Int.max, + omittingEmptySubsequences: Bool = true, + whereSeparator isSeparator: @escaping (Element) -> Bool + ) -> LazySplitSequence { + precondition(maxSplits >= 0, "Must take zero or more splits") + + return LazySplitSequence( + base: elements, + isSeparator: isSeparator, + maxSplits: maxSplits, + omittingEmptySubsequences: omittingEmptySubsequences + ) + } +} + +extension LazySequenceProtocol where Element: Equatable { + /// Lazily returns the longest possible subsequences of the sequence, in + /// order, around elements equal to the given element. + /// + /// The resulting lazy sequence consists of at most `maxSplits + 1` + /// subsequences. Elements that are used to split the sequence are not + /// returned as part of any subsequence (except possibly the last one, in the + /// case where `maxSplits` is less than the number of separators in the + /// sequence). + /// + /// The following examples show the effects of the `maxSplits` and + /// `omittingEmptySubsequences` parameters when splitting a sequence of + /// integers at each zero (`0`). The first use of `split` returns each + /// subsequence that was originally separated by one or more zeros. + /// + /// let numbers = AnySequence([1, 2, 0, 3, 4, 0, 0, 5]) + /// for subsequence in numbers.lazy.split(separator: 0) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [3, 4] + /// [5] + /// */ + /// + /// The second example passes `1` for the `maxSplits` parameter, so the + /// original sequence is split just once, into two subsequences. + /// + /// for subsequence in numbers.lazy.split( + /// separator: 0, + /// maxSplits: 1 + /// ) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [3, 4, 0, 0, 5] + /// */ + /// + /// The final example passes `false` for the `omittingEmptySubsequences` + /// parameter, so the sequence of returned subsequences contains empty + /// subsequences where zeros were repeated. + /// + /// for subsequence in numbers.lazy.split( + /// separator: 0, + /// omittingEmptySubsequences: false + /// ) { + /// print(subsequence) + /// } + /// /* Prints: + /// [1, 2] + /// [3, 4] + /// [] + /// [5] + /// */ + /// + /// - Parameters: + /// - separator: The element that should be split upon. + /// - maxSplits: The maximum number of times to split the sequence, or + /// one less than the number of subsequences to return. If + /// `maxSplits + 1` subsequences are returned, the last one is a suffix + /// of the original sequence containing the remaining elements. + /// `maxSplits` must be greater than or equal to zero. The default value + /// is `Int.max`. + /// - omittingEmptySubsequences: If `false`, an empty subsequence is + /// returned in the result for each consecutive pair of `separator` + /// elements in the sequence and for each instance of `separator` at + /// the start or end of the sequence. If `true`, only nonempty + /// subsequences are returned. The default value is `true`. + /// - Returns: A lazy sequence of subsequences, split from this sequence's + /// elements. + /// + /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable + public func split( + separator: Element, + maxSplits: Int = Int.max, + omittingEmptySubsequences: Bool = true + ) -> LazySplitSequence { + precondition(maxSplits >= 0, "Must take zero or more splits") + + return LazySplitSequence( + base: elements, + isSeparator: { $0 == separator }, + maxSplits: maxSplits, + omittingEmptySubsequences: omittingEmptySubsequences + ) + } +} + +//===----------------------------------------------------------------------===// +// LazySplitCollection +//===----------------------------------------------------------------------===// +/// A collection that lazily splits a base collection into subsequences +/// separated by elements that satisfy the given `whereSeparator` predicate. +/// +/// - Note: This type is the result of +/// +/// x.split(maxSplits:omittingEmptySubsequences:whereSeparator) +/// x.split(separator:maxSplits:omittingEmptySubsequences) +/// +/// where `x` conforms to `LazyCollectionProtocol`. +public struct LazySplitCollection { + @usableFromInline + internal let base: Base + + @usableFromInline + internal let isSeparator: (Base.Element) -> Bool + + @usableFromInline + internal let maxSplits: Int + + @usableFromInline + internal let omittingEmptySubsequences: Bool + + @usableFromInline + internal var _startIndex: Index + + @usableFromInline + internal init( + base: Base, + isSeparator: @escaping (Base.Element) -> Bool, + maxSplits: Int, + omittingEmptySubsequences: Bool + ) { + self.base = base + self.isSeparator = isSeparator + self.maxSplits = maxSplits + self.omittingEmptySubsequences = omittingEmptySubsequences + + // We precalculate `startIndex`. There are three possibilities: + // 1. `base` is empty and we're _not_ omitting empty subsequences, in which + // case the following index describes the sole element of this collection; + self._startIndex = Index( + baseRange: base.startIndex.. + + /// The number of subsequences up to and including this position in the + /// collection. + @usableFromInline + internal let sequenceLength: Int + + /// The number splits performed up to and including this position in the + /// collection. + @usableFromInline + internal let splitCount: Int + + @usableFromInline + internal init( + baseRange: Range, + sequenceLength: Int, + splitCount: Int + ) { + self.baseRange = baseRange + self.sequenceLength = sequenceLength + self.splitCount = splitCount + } + + @inlinable + public static func == (lhs: Index, rhs: Index) -> Bool { + // `sequenceLength` is equivalent to the index's 1-based position in the + // collection of indices. + lhs.sequenceLength == rhs.sequenceLength + } + + @inlinable + public static func < (lhs: Index, rhs: Index) -> Bool { + lhs.sequenceLength < rhs.sequenceLength + } + } + + /// Returns the index of the subsequence starting at or after the given base + /// collection index. + @usableFromInline + internal func indexForSubsequence( + atOrAfter lowerBound: Base.Index, + sequenceLength: Int, + splitCount: Int + ) -> Index { + var start = lowerBound + // If we don't have any more splits to do (which we'll determine shortly), + // the end of this subsequence will be the end of the base collection. + var end = base.endIndex + + if splitCount < maxSplits { + // The non-inclusive end of this subsequence is marked by the next + // separator, or the end of the base collection. + end = + base[start...].firstIndex(where: isSeparator) + ?? base.endIndex + + if base[start.. Index { + precondition(i != endIndex, "Can't advance past endIndex") + + var subsequenceStart = i.baseRange.upperBound + if subsequenceStart < base.endIndex { + // If we're not already at the end of the base collection, the previous + // susequence ended with a separator. Start searching for the next + // subsequence at the following element. + subsequenceStart = base.index(after: i.baseRange.upperBound) + } + + guard subsequenceStart != base.endIndex else { + if !omittingEmptySubsequences + && i.sequenceLength < i.splitCount + 1 + { + // The base collection ended with a separator, so we need to emit one + // more empty subsequence. This one differs from `endIndex` in its + // `sequenceLength` (except in an extreme edge case!), which is the + // sole property tested for equality and comparison. + return Index( + baseRange: base.endIndex.. Base.SubSequence { + precondition(position != endIndex, "Can't subscript using endIndex") + return base[position.baseRange] + } +} + +extension LazySplitCollection.Index: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(sequenceLength) + } +} + +extension LazyCollectionProtocol { + /// Lazily returns the longest possible subsequences of the collection, in + /// order, that don't contain elements satisfying the given predicate. + /// + /// The resulting lazy collection consists of at most `maxSplits + 1` + /// subsequences. Elements that are used to split the collection are not + /// returned as part of any subsequence (except possibly the last one, in the + /// case where `maxSplits` is less than the number of separators in the + /// collection). + /// + /// The following examples show the effects of the `maxSplits` and + /// `omittingEmptySubsequences` parameters when lazily splitting a string + /// using a closure that matches spaces. The first use of `split` returns each + /// word that was originally separated by one or more spaces. + /// + /// let line = "BLANCHE: I don't want realism. I want magic!" + /// for spaceless in line.lazy.split(whereSeparator: { $0 == " " }) { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // I + /// // don't + /// // want + /// // realism. + /// // I + /// // want + /// // magic! + /// + /// The second example passes `1` for the `maxSplits` parameter, so the + /// original string is split just once, into two new strings. + /// + /// for spaceless in line.lazy.split( + /// maxSplits: 1, + /// whereSeparator: { $0 == " " } + /// ) { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // I don't want realism. I want magic! + /// + /// The final example passes `false` for the `omittingEmptySubsequences` + /// parameter, so the returned array contains empty strings where spaces + /// were repeated. + /// + /// for spaceless in line.lazy.split( + /// omittingEmptySubsequences: false, + /// whereSeparator: { $0 == " " } + /// ) { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // + /// // + /// // I + /// // don't + /// // want + /// // realism. + /// // I + /// // want + /// // magic! + /// + /// - Parameters: + /// - maxSplits: The maximum number of times to split the collection, or + /// one less than the number of subsequences to return. If + /// `maxSplits + 1` subsequences are returned, the last one is a suffix + /// of the original collection containing the remaining elements. + /// `maxSplits` must be greater than or equal to zero. The default value + /// is `Int.max`. + /// - omittingEmptySubsequences: If `false`, an empty subsequence is + /// returned in the result for each pair of consecutive elements + /// satisfying the `isSeparator` predicate and for each element at the + /// start or end of the collection satisfying the `isSeparator` + /// predicate. The default value is `true`. + /// - whereSeparator: A closure that takes an element as an argument and + /// returns a Boolean value indicating whether the collection should be + /// split at that element. + /// - Returns: A lazy collection of subsequences, split from this collection's + /// elements. + /// + /// - Complexity: O(*n*), where *n* is the length of the collection. + @inlinable + public func split( + maxSplits: Int = Int.max, + omittingEmptySubsequences: Bool = true, + whereSeparator isSeparator: @escaping (Element) -> Bool + ) -> LazySplitCollection { + precondition(maxSplits >= 0, "Must take zero or more splits") + + return LazySplitCollection( + base: elements, + isSeparator: isSeparator, + maxSplits: maxSplits, + omittingEmptySubsequences: omittingEmptySubsequences + ) + } +} + +extension LazyCollectionProtocol +where Element: Equatable { + /// Lazily returns the longest possible subsequences of the collection, in + /// order, around elements equal to the given element. + /// + /// The resulting lazy collection consists of at most `maxSplits + 1` + /// subsequences. Elements that are used to split the collection are not + /// returned as part of any subsequence (except possibly the last one, in the + /// case where `maxSplits` is less than the number of separators in the + /// collection). + /// + /// The following examples show the effects of the `maxSplits` and + /// `omittingEmptySubsequences` parameters when splitting a string at each + /// space character (" "). The first use of `split` returns each word that + /// was originally separated by one or more spaces. + /// + /// let line = "BLANCHE: I don't want realism. I want magic!" + /// for spaceless in line.lazy.split(separator: " ") { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // I + /// // don't + /// // want + /// // realism. + /// // I + /// // want + /// // magic! + /// + /// The second example passes `1` for the `maxSplits` parameter, so the + /// original string is split just once, into two new strings. + /// + /// for spaceless in line.lazy.split(separator: " ", maxSplits: 1) { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // I don't want realism. I want magic! + /// + /// The final example passes `false` for the `omittingEmptySubsequences` + /// parameter, so the returned array contains empty strings where spaces + /// were repeated. + /// + /// for spaceless in line.lazy.split( + /// separator: " ", + /// omittingEmptySubsequences: false + /// ) { + /// print(spaceless) + /// } + /// // Prints + /// // BLANCHE: + /// // + /// // + /// // I + /// // don't + /// // want + /// // realism. + /// // I + /// // want + /// // magic! + /// + /// - Parameters: + /// - separator: The element that should be split upon. + /// - maxSplits: The maximum number of times to split the collection, or + /// one less than the number of subsequences to return. If + /// `maxSplits + 1` subsequences are returned, the last one is a suffix + /// of the original collection containing the remaining elements. + /// `maxSplits` must be greater than or equal to zero. The default value + /// is `Int.max`. + /// - omittingEmptySubsequences: If `false`, an empty subsequence is + /// returned in the result for each consecutive pair of `separator` + /// elements in the collection and for each instance of `separator` at + /// the start or end of the collection. If `true`, only nonempty + /// subsequences are returned. The default value is `true`. + /// - Returns: A lazy collection of subsequences split from this collection's + /// elements. + /// + /// - Complexity: O(*n*), where *n* is the length of the collection. + @inlinable + public func split( + separator: Element, + maxSplits: Int = Int.max, + omittingEmptySubsequences: Bool = true + ) -> LazySplitCollection { + precondition(maxSplits >= 0, "Must take zero or more splits") + + return LazySplitCollection( + base: elements, + isSeparator: { $0 == separator }, + maxSplits: maxSplits, + omittingEmptySubsequences: omittingEmptySubsequences + ) + } +} diff --git a/Tests/SwiftAlgorithmsTests/LazySplitTests.swift b/Tests/SwiftAlgorithmsTests/LazySplitTests.swift new file mode 100644 index 0000000..34cdfe7 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/LazySplitTests.swift @@ -0,0 +1,840 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift 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 +// +//===----------------------------------------------------------------------===// + +import Algorithms +import XCTest + +//===----------------------------------------------------------------------===// +// Tests for `LazySplitSequence` and `LazySplitCollection` +//===----------------------------------------------------------------------===// + +final class LazySplitTests: XCTestCase { + func testEmpty() { + Validator( + subject: [], + separator: .element(0), + maxSplits: 1 + ).validate() + } + + // The following test names indicate the sequence being split, using the + // notation + // S: Separator + // E: Element + // + // Values of `maxSplit` are interesting when they're less than the number of + // splits that would occur with the default. That varies depending on whether + // empty subsequences are omitted or included. `Validator` tests both the + // default and the value provided, but there are cases below where the + // provided `maxSplit` isn't less than the number of splits when empty + // subsequences are omitted. + + //===--------------------------------------------------------------------===// + // Length 1 + //===--------------------------------------------------------------------===// + + func testE() { + Validator(subject: [1], separator: .element(0), maxSplits: 0).validate() + } + + func testS() { + Validator(subject: [0], separator: .element(0), maxSplits: 0).validate() + } + + //===--------------------------------------------------------------------===// + // Length 2 + //===--------------------------------------------------------------------===// + + func testEE() { + Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate() + } + + func testSS() { + Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate() + } + + func testES() { + Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate() + } + + func testSE() { + Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate() + } + + //===--------------------------------------------------------------------===// + // Length 3 + //===--------------------------------------------------------------------===// + + func testEEE() { + Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0) + .validate() + } + + func testSSS() { + Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1) + .validate() + } + + func testAllEES() { + let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 0) + .validate() + } + } + + func testAllESS() { + let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Length 4 with less than two separators. + //===--------------------------------------------------------------------===// + + func testEEEE() { + Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0) + .validate() + } + + func testAllEEES() { + let permutations = [ + [1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1] + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 0) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Unique permutations of sequences with at least two separators, so there can + // be multiple adjacent separators at the beginning, middle, or end. + //===--------------------------------------------------------------------===// + + // All separators. + func testSSSS() { + Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1) + .validate() + } + + // Equal numbers of elements and separators. + func testAllEESS() { + let permutations = [ + [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], + [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + // More separators than elements. + func testAllEESSS() { + let permutations = [ + [1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1], + [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0], + [0, 0, 1, 0, 1], [0, 0, 0, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + // More elements than separators. + func testAllEEESS() { + let permutations = [ + [1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0], + [1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], + [0, 1, 0, 1, 1], [0, 0, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Unique permutations of sequences with at least three separators. + //===--------------------------------------------------------------------===// + + func testAllESSS() { + let permutations = [ + [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + func testAllEEEESSS() { + let permutations = [ + [1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0], + [1, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0], + [1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1], + [1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0], + [1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1], + [1, 0, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1], + [1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0], + [0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0], + [0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Unique permutations of sequences with at least four separators, so there + // can be two runs of multiple adjacent separators: beginning and end, + // beginning and middle, or end and middle. + //===--------------------------------------------------------------------===// + + // Equal numbers of separators and elements. + func testAllEEEESSSS() { + let permutations = [ + [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0, 0], + [1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 0, 0, 0, 1, 0], + [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0, 0], + [1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 0], + [1, 1, 0, 1, 0, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0, 0], + [1, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 0, 1, 0, 0, 1], + [1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 0, 0, 0, 1, 0, 1], + [1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0], + [1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 0, 1, 0], + [1, 0, 1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0, 0], + [1, 0, 1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 0, 0, 1], + [1, 0, 1, 0, 0, 1, 1, 0], [1, 0, 1, 0, 0, 1, 0, 1], + [1, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0, 0], + [1, 0, 0, 1, 1, 0, 1, 0], [1, 0, 0, 1, 1, 0, 0, 1], + [1, 0, 0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1], + [1, 0, 0, 1, 0, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1, 0], + [1, 0, 0, 0, 1, 1, 0, 1], [1, 0, 0, 0, 1, 0, 1, 1], + [1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0, 1, 0], + [0, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0, 0, 1], + [0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1], + [0, 1, 1, 0, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0, 0], + [0, 1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 0, 1], + [0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1], + [0, 1, 0, 1, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1, 0], + [0, 1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 1], + [0, 1, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0, 0, 1], + [0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1], + [0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0], + [0, 0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1], + [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0], + [0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1], + [0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + // More separators than elements. + func testAllEEESSSS() { + let permutations = [ + [1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], + [1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0], + [1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1], + [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1], + [1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1], + [0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], + [0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1], + [0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], + [0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], + [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1], + [0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + // More elements than separators. + func testAllEEEEESSSS() { + let permutations =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, 1, 1, 0], + [0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1], + [0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0], + [0, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1], + [0, 0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 0, 1, 1, 0, 1, 1, 1], + [0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Permutations of a sequence with six separators, so there can be multiple + // adjacent separators at the beginning, middle, _and_ end. + //===--------------------------------------------------------------------===// + + // More separators than elements. + func testAllEEESSSSSS() { + let permutations = [ + [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 0, 0, 0], + [1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1, 0], + [1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0], + [1, 0, 1, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 0], + [1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0], + [1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0], + [1, 0, 0, 1, 0, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0], + [1, 0, 0, 1, 0, 0, 0, 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0, 0, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0, 0, 1], + [0, 0, 1, 0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 1, 0], + [0, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 1, 1, 0], + [0, 0, 1, 0, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 0, 0, 1, 1], + [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1], + [0, 0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0, 1, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0], + [0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 1, 0], + [0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0], + [0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1], + [0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1], + ] + + for permutation in permutations { + Validator(subject: permutation, separator: .element(0), maxSplits: 1) + .validate() + } + } + + //===--------------------------------------------------------------------===// + // Specific examples of interest. + //===--------------------------------------------------------------------===// + + // The motivating example from + // https://github.com/apple/swift-algorithms/issues/59. + func testSplitFilenameComponents() { + Validator( + subject: "archive.tar.gz", + separator: .element("."), + maxSplits: 1 + ).validate() + } + + // Examples from documentation. + func testSequenceDocExamples() { + // Closure version. + let numbers = stride(from: 1, through: 16, by: 1) + Validator( + subject: Array(numbers), + separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }), + maxSplits: 1 + ).validate() + + // Equatable element version. + let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5] + Validator(subject: numbers2, separator: .element(0), maxSplits: 1) + .validate() + } + + func testCollectionDocExample() { + let line = "BLANCHE: I don't want realism. I want magic!" + Validator(subject: line, separator: .element("."), maxSplits: 1).validate() + } + + // Patterns tested in a previous version of this file which aren't tested + // above. Preserved to ensure we're not losing any test coverage. + func testVintagePatterns() { + let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7] + Validator(subject: pattern1, separator: .element(42), maxSplits: 2) + .validate() + Validator(subject: pattern1, separator: .element(42), maxSplits: 0) + .validate() + + let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7] + Validator(subject: pattern2, separator: .element(42), maxSplits: 2) + .validate() + + let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7] + Validator(subject: pattern3, separator: .element(42), maxSplits: 2) + .validate() + + let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42] + Validator(subject: pattern4, separator: .element(42), maxSplits: 1) + .validate() + } + + //===--------------------------------------------------------------------===// + // Protocol conformance. + //===--------------------------------------------------------------------===// + + func testLaziness() { + let splitSequence = AnySequence([1, 2, 42, 3]).lazy.split(separator: 42) + XCTAssertLazySequence(splitSequence) + + let splitCollection = "foo.bar".lazy.split(separator: ".") + XCTAssertLazySequence(splitCollection) + XCTAssertLazyCollection(splitCollection) + } + + // TODO: Need a version of `validateIndexTraversals` that doesn't require + // `BidirectionalCollection` conformance. + + //===--------------------------------------------------------------------===// + // Validator + //===--------------------------------------------------------------------===// + + /// Splits a collection as both a lazy sequence and a lazy collection, using + /// the provided separator, and compares the results to those of the Standard + /// Library's eager splits, which are assumed to be correct. + /// + /// Tests all combinations of default and provided `maxSplit` arguments and + /// default (true) and explicit false for `omittingEmptySubsequences`. + /// + /// - Parameters: + /// - subject: The collection whose splits will be validated. + /// - separator: The element of the collection--or a predicate function to + /// determine the element--on which to split. + /// - maxSplits: The value to pass for `maxSplits` during validation. The + /// default value is also validated. + fileprivate struct Validator + where C.Element: Equatable, C.SubSequence: Equatable { + enum Separator { + case element(C.Element) + case closure((C.Element) -> Bool) + } + + let subject: C + let separator: Separator + let maxSplits: Int + + func validate() { + _validateAsSequence(AnySequence(subject)) + _validateAsCollection(subject) + } + + private enum MaxSplits: CustomStringConvertible { + case provided(Int) + case defaultValue + + var description: String { + switch self { + case .provided(let value): + return "maxSplits: \(value)" + case .defaultValue: + return "maxSplits: default" + } + } + } + + private enum OmittingEmptySubsequences: CustomStringConvertible { + case provided(Bool) + case defaultValue + + var description: String { + switch self { + case .provided(let value): + return "omittingEmptySubsequences: \(value)" + case .defaultValue: + return "omittingEmptySubsequences: default" + } + } + } + + private func failureMessage( + actual: L, + expected: S, + maxSplits: MaxSplits, + omittingEmptySubsequences: OmittingEmptySubsequences + ) -> String { + "for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)" + } + + private func _validateAsSequence(_ s: T) + where T.Element == C.Element { + // Default max splits, omitting empty sequences + switch separator { + case let .element(element): + let expected = s.split(separator: element).map { Array($0) } + let actual = s.lazy.split(separator: element) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .defaultValue) + ) + case let .closure(closure): + let expected = s.split(whereSeparator: closure).map { Array($0) } + let actual = s.lazy.split(whereSeparator: closure) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .defaultValue) + ) + } + + // Provided max splits, omitting empty sequences + switch separator { + case let .element(element): + let expected = s.split( + separator: element, + maxSplits: maxSplits + ).map { Array($0) } + let actual = s.lazy.split( + separator: element, + maxSplits: maxSplits + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .defaultValue) + ) + case let .closure(closure): + let expected = s.split( + maxSplits: maxSplits, + whereSeparator: closure + ).map { Array($0) } + let actual = s.lazy.split( + maxSplits: maxSplits, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .defaultValue) + ) + } + + // Default max splits, including empty sequences + switch separator { + case let .element(element): + let expected = s.split( + separator: element, + omittingEmptySubsequences: false + ).map { Array($0) } + let actual = s.lazy.split( + separator: element, + omittingEmptySubsequences: false + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .provided(false)) + ) + case let .closure(closure): + let expected = s.split( + omittingEmptySubsequences: false, + whereSeparator: closure + ).map { Array($0) } + let actual = s.lazy.split( + omittingEmptySubsequences: false, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .provided(false)) + ) + } + + // Provided max splits, including empty sequences + switch separator { + case let .element(element): + let expected = s.split( + separator: element, + maxSplits: maxSplits, + omittingEmptySubsequences: false + ).map { Array($0) } + let actual = s.lazy.split( + separator: element, + maxSplits: maxSplits, + omittingEmptySubsequences: false + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .provided(false)) + ) + case let .closure(closure): + let expected = s.split( + maxSplits: maxSplits, + omittingEmptySubsequences: false, + whereSeparator: closure + ).map { Array($0) } + let actual = s.lazy.split( + maxSplits: maxSplits, + omittingEmptySubsequences: false, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .provided(false)) + ) + } + } + + private func _validateAsCollection(_ c: C) { + // Default max splits, omitting empty sequences + switch separator { + case let .element(element): + let expected = c.split(separator: element) + let actual = c.lazy.split(separator: element) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .defaultValue) + ) + case let .closure(closure): + let expected = c.split(whereSeparator: closure) + let actual = c.lazy.split(whereSeparator: closure) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .defaultValue) + ) + } + + // Provided max splits, omitting empty sequences + switch separator { + case let .element(element): + let expected = c.split( + separator: element, + maxSplits: maxSplits + ) + let actual = c.lazy.split( + separator: element, + maxSplits: maxSplits + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .defaultValue) + ) + case let .closure(closure): + let expected = c.split( + maxSplits: maxSplits, + whereSeparator: closure + ) + let actual = c.lazy.split( + maxSplits: maxSplits, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .defaultValue) + ) + } + + // Default max splits, including empty sequences + switch separator { + case let .element(element): + let expected = c.split( + separator: element, + omittingEmptySubsequences: false + ) + let actual = c.lazy.split( + separator: element, + omittingEmptySubsequences: false + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .provided(false)) + ) + case let .closure(closure): + let expected = c.split( + omittingEmptySubsequences: false, + whereSeparator: closure + ) + let actual = c.lazy.split( + omittingEmptySubsequences: false, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .defaultValue, + omittingEmptySubsequences: .provided(false)) + ) + } + + // Provided max splits, including empty sequences + switch separator { + case let .element(element): + let expected = c.split( + separator: element, + maxSplits: maxSplits, + omittingEmptySubsequences: false + ) + let actual = c.lazy.split( + separator: element, + maxSplits: maxSplits, + omittingEmptySubsequences: false + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .provided(false)) + ) + case let .closure(closure): + let expected = c.split( + maxSplits: maxSplits, + omittingEmptySubsequences: false, + whereSeparator: closure + ) + let actual = c.lazy.split( + maxSplits: maxSplits, + omittingEmptySubsequences: false, + whereSeparator: closure + ) + XCTAssertEqualSequences( + expected, + actual, + failureMessage( + actual: actual, expected: expected, maxSplits: .provided(maxSplits), + omittingEmptySubsequences: .provided(false)) + ) + } + } + } +}