mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-22 04:10:39 +00:00
Compare commits
10
Commits
0.0.3
...
nate/bench
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b333caf0a5 | ||
|
|
e64cff7e1d | ||
|
|
98b6e26d8d | ||
|
|
ca8af77420 | ||
|
|
e077f67639 | ||
|
|
ed38a2dac4 | ||
|
|
18ec8500b7 | ||
|
|
ab0ec2adf4 | ||
|
|
e7c6716499 | ||
|
|
d2546b8740 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<array/>
|
||||
</plist>
|
||||
@@ -0,0 +1,43 @@
|
||||
# First Non-Nil
|
||||
|
||||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/FirstNonNil.swift) |
|
||||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift)]
|
||||
|
||||
Retrieves the first `.some` encountered while applying the given transform.
|
||||
|
||||
This operation is available through the `firstNonNil(_:)` method on any sequence.
|
||||
|
||||
```swift
|
||||
let value = ["A", "B", "10"].firstNonNil { Int($0) }
|
||||
// value == .some(10)
|
||||
//
|
||||
let noValue = ["A", "B", "C"].firstNonNil { Int($0) }
|
||||
// noValue == .none
|
||||
```
|
||||
|
||||
|
||||
This method is analogous to `first(where:)` in how it only consumes values until
|
||||
a `.some` is found, unlike using lazy operators, which will load any sequence into a collection
|
||||
before evaluating its transforms lazily.
|
||||
|
||||
## Detailed Design
|
||||
|
||||
The `firstNonNil(_:)` method is added as an extension method on the `Sequence`
|
||||
protocol:
|
||||
|
||||
```swift
|
||||
public extension Sequence {
|
||||
func firstNonNil<Result>(_ transform: (Element) throws -> Result?)
|
||||
rethrows -> Result?
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Naming
|
||||
|
||||
This method’s name was selected for its comprehensibility.
|
||||
|
||||
### Comparison with other languages
|
||||
|
||||
**Scala**: Scala provides a `collectFirst` function that finds the first element
|
||||
in a collection for which a partial function is defined.
|
||||
@@ -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).
|
||||
@@ -28,6 +28,9 @@ let package = Package(
|
||||
dependencies: [
|
||||
.product(name: "RealModule", package: "swift-numerics"),
|
||||
]),
|
||||
.target(
|
||||
name: "Benchmark",
|
||||
dependencies: ["Algorithms"]),
|
||||
.testTarget(
|
||||
name: "SwiftAlgorithmsTests",
|
||||
dependencies: ["Algorithms"]),
|
||||
|
||||
@@ -37,10 +37,11 @@ Read more about the package, and the intent behind it, in the [announcement on s
|
||||
|
||||
- [`chunked(by:)`, `chunked(on:)`, `chunks(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes or chunks of a given count.
|
||||
- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Interspersed.md): Place a value between every two elements of a sequence.
|
||||
- [`interspersed(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Intersperse.md): Place a value between every two elements of a sequence.
|
||||
- [`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/SlidingWindows.md): Breaks a collection into overlapping subsequences where elements are slices from the original collection.
|
||||
- [`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
|
||||
|
||||
|
||||
@@ -76,8 +76,7 @@ extension LazyChunked: LazyCollectionProtocol {
|
||||
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
|
||||
let subject = projection(base[start])
|
||||
return base[base.index(after: start)...]
|
||||
.firstIndex(where: { !belongInSameGroup(subject, projection($0)) })
|
||||
?? base.endIndex
|
||||
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -119,20 +118,8 @@ extension LazyChunked: BidirectionalCollection
|
||||
|
||||
// Get the projected value of the last element in the range ending at `end`.
|
||||
let subject = projection(base[indexBeforeEnd])
|
||||
|
||||
// Search backward from `end` for the first element whose projection isn't
|
||||
// equal to `subject`.
|
||||
if let firstMismatch = base[..<indexBeforeEnd]
|
||||
.lastIndex(where: { !belongInSameGroup(projection($0), subject) })
|
||||
{
|
||||
// If we found one, that's the last element of the _next_ previous chunk,
|
||||
// and therefore one position _before_ the start of this chunk.
|
||||
return base.index(after: firstMismatch)
|
||||
} else {
|
||||
// If we didn't find such an element, this chunk extends back to the start
|
||||
// of the collection.
|
||||
return base.startIndex
|
||||
}
|
||||
return base[..<indexBeforeEnd]
|
||||
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// firstNonNil(_:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public extension Sequence {
|
||||
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
||||
func firstNonNil<Result>(
|
||||
_ transform: (Element) throws -> Result?
|
||||
) rethrows -> Result? {
|
||||
for value in self {
|
||||
if let value = try transform(value) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -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<Base: Sequence> {
|
||||
@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<Elements> {
|
||||
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<Elements> {
|
||||
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<Base: Collection> {
|
||||
@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..<base.startIndex,
|
||||
sequenceLength: 1,
|
||||
splitCount: 0
|
||||
)
|
||||
if base.isEmpty {
|
||||
if omittingEmptySubsequences {
|
||||
// 2. `base` is empty and we _are_ omitting empty subsequences, so this
|
||||
// collection has no elements;
|
||||
_startIndex = endIndex
|
||||
}
|
||||
} else {
|
||||
// 3. `base` isn't empty, so we must iterate it to determine the start
|
||||
// index.
|
||||
_startIndex = indexForSubsequence(
|
||||
atOrAfter: base.startIndex,
|
||||
sequenceLength: 0,
|
||||
splitCount: 0
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LazySplitCollection: LazyCollectionProtocol {
|
||||
/// Position of a subsequence in a split collection.
|
||||
public struct Index: Comparable {
|
||||
/// The range corresponding to the subsequence at this position.
|
||||
@usableFromInline
|
||||
internal let baseRange: Range<Base.Index>
|
||||
|
||||
/// 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<Base.Index>,
|
||||
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..<end].isEmpty {
|
||||
if omittingEmptySubsequences {
|
||||
// Find the next subsequence of non-separators.
|
||||
start =
|
||||
base[end...].firstIndex(where: { !isSeparator($0) })
|
||||
?? base.endIndex
|
||||
if start == base.endIndex {
|
||||
// No non-separators left in the base collection. We're done.
|
||||
return endIndex
|
||||
}
|
||||
end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var updatedSplitCount = splitCount
|
||||
if end < base.endIndex {
|
||||
// This subsequence ends on a separator (and perhaps includes other
|
||||
// separators, if we're omitting empty subsequences), so we've performed
|
||||
// another split.
|
||||
updatedSplitCount += 1
|
||||
}
|
||||
|
||||
return Index(
|
||||
baseRange: start..<end,
|
||||
sequenceLength: sequenceLength + 1,
|
||||
splitCount: updatedSplitCount
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Index {
|
||||
_startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Index {
|
||||
Index(
|
||||
baseRange: base.endIndex..<base.endIndex,
|
||||
sequenceLength: Int.max,
|
||||
splitCount: Int.max
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Index) -> 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.endIndex,
|
||||
sequenceLength: i.sequenceLength + 1,
|
||||
splitCount: i.splitCount
|
||||
)
|
||||
} else {
|
||||
return endIndex
|
||||
}
|
||||
}
|
||||
|
||||
return indexForSubsequence(
|
||||
atOrAfter: subsequenceStart,
|
||||
sequenceLength: i.sequenceLength,
|
||||
splitCount: i.splitCount
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Index) -> 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<Elements> {
|
||||
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<Elements> {
|
||||
precondition(maxSplits >= 0, "Must take zero or more splits")
|
||||
|
||||
return LazySplitCollection(
|
||||
base: elements,
|
||||
isSeparator: { $0 == separator },
|
||||
maxSplits: maxSplits,
|
||||
omittingEmptySubsequences: omittingEmptySubsequences
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,25 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Sequence {
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10]
|
||||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9]
|
||||
///
|
||||
/// - Complexity: O(1). Access to successive values is O(k) where
|
||||
/// _k_ is the striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: Returns a sequence for stepping through the
|
||||
/// elements by the specified amount.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> StrideSequence<Self> {
|
||||
StrideSequence(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
/// Returns a sequence stepping through the elements every `step` starting
|
||||
/// at the first value. Any remainders of the stride will be trimmed.
|
||||
///
|
||||
@@ -25,16 +44,17 @@ extension Sequence {
|
||||
/// O(_k_), where _k_ is the striding `step`.
|
||||
///
|
||||
/// - Parameter step: The amount to step with each iteration.
|
||||
/// - Returns: Returns a sequence or collection for stepping through the
|
||||
/// - Returns: Returns a collection for stepping through the
|
||||
/// elements by the specified amount.
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Stride<Self> {
|
||||
Stride(base: self, stride: step)
|
||||
public func striding(by step: Int) -> StrideCollection<Self> {
|
||||
StrideCollection(base: self, stride: step)
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that strides over a base sequence or collection.
|
||||
public struct Stride<Base: Sequence> {
|
||||
/// A wrapper that strides over a base sequence.
|
||||
public struct StrideSequence<Base: Sequence>: Sequence {
|
||||
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@@ -49,14 +69,8 @@ public struct Stride<Base: Sequence> {
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Stride(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride: Sequence {
|
||||
extension StrideSequence {
|
||||
|
||||
/// An iterator over a `Stride` sequence.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
@@ -88,12 +102,43 @@ extension Stride: Sequence {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeIterator() -> Stride<Base>.Iterator {
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(iterator: base.makeIterator(), stride: stride)
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride: Collection where Base: Collection {
|
||||
extension StrideSequence {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that strides over a base collection.
|
||||
public struct StrideCollection<Base: Collection> {
|
||||
@usableFromInline
|
||||
internal let base: Base
|
||||
|
||||
@usableFromInline
|
||||
internal let stride: Int
|
||||
|
||||
@usableFromInline
|
||||
internal init(base: Base, stride: Int) {
|
||||
precondition(stride > 0, "striding must be greater than zero")
|
||||
self.base = base
|
||||
self.stride = stride
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection {
|
||||
@inlinable
|
||||
public func striding(by step: Int) -> Self {
|
||||
Self(base: base, stride: stride * step)
|
||||
}
|
||||
}
|
||||
|
||||
extension StrideCollection: Collection {
|
||||
|
||||
/// A position in a `Stride` collection.
|
||||
public struct Index: Comparable {
|
||||
@usableFromInline
|
||||
@@ -213,7 +258,7 @@ extension Stride: Collection where Base: Collection {
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride: BidirectionalCollection
|
||||
extension StrideCollection: BidirectionalCollection
|
||||
where Base: RandomAccessCollection {
|
||||
|
||||
@inlinable
|
||||
@@ -223,16 +268,16 @@ extension Stride: BidirectionalCollection
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
extension StrideCollection: RandomAccessCollection where Base: RandomAccessCollection {}
|
||||
|
||||
extension Stride: Equatable where Base.Element: Equatable {
|
||||
extension StrideCollection: Equatable where Base.Element: Equatable {
|
||||
@inlinable
|
||||
public static func == (lhs: Stride, rhs: Stride) -> Bool {
|
||||
public static func == (lhs: StrideCollection, rhs: StrideCollection) -> Bool {
|
||||
lhs.elementsEqual(rhs, by: ==)
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride: Hashable where Base.Element: Hashable {
|
||||
extension StrideCollection: Hashable where Base.Element: Hashable {
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(stride)
|
||||
@@ -242,4 +287,4 @@ extension Stride: Hashable where Base.Element: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
extension Stride.Index: Hashable where Base.Index: Hashable {}
|
||||
extension StrideCollection.Index: Hashable where Base.Index: Hashable {}
|
||||
@@ -27,13 +27,62 @@ extension BidirectionalCollection {
|
||||
public func suffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
let start = startIndex
|
||||
var result = endIndex
|
||||
while result != start {
|
||||
let previous = index(before: result)
|
||||
guard try predicate(self[previous]) else { break }
|
||||
result = previous
|
||||
}
|
||||
return self[result...]
|
||||
try self[startOfSuffix(while: predicate)...]
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// endOfPrefix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Collection {
|
||||
/// Returns the exclusive upper bound of the prefix of elements that satisfy
|
||||
/// the predicate.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the collection
|
||||
/// as its argument and returns `true` if the element is part of the prefix
|
||||
/// or `false` if it is not. Once the predicate returns `false` it will not
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal func endOfPrefix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
var index = startIndex
|
||||
while try index != endIndex && predicate(self[index]) {
|
||||
formIndex(after: &index)
|
||||
}
|
||||
return index
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// startOfSuffix(while:)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension BidirectionalCollection {
|
||||
/// Returns the inclusive lower bound of the suffix of elements that satisfy
|
||||
/// the predicate.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the collection
|
||||
/// as its argument and returns `true` if the element is part of the suffix
|
||||
/// or `false` if it is not. Once the predicate returns `false` it will not
|
||||
/// be called again.
|
||||
///
|
||||
/// - Complexity: O(*n*), where *n* is the length of the collection.
|
||||
@usableFromInline
|
||||
internal func startOfSuffix(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> Index {
|
||||
var index = endIndex
|
||||
while index != startIndex {
|
||||
let after = index
|
||||
formIndex(before: &index)
|
||||
if try !predicate(self[index]) {
|
||||
return after
|
||||
}
|
||||
}
|
||||
return index
|
||||
}
|
||||
}
|
||||
@@ -29,20 +29,8 @@ extension BidirectionalCollection {
|
||||
public func trimming(
|
||||
while predicate: (Element) throws -> Bool
|
||||
) rethrows -> SubSequence {
|
||||
// Consume elements from the front.
|
||||
let sliceStart = try firstIndex { try predicate($0) == false } ?? endIndex
|
||||
// sliceEnd is the index _after_ the last index to match the predicate.
|
||||
var sliceEnd = endIndex
|
||||
|
||||
while sliceStart != sliceEnd {
|
||||
let idxBeforeSliceEnd = index(before: sliceEnd)
|
||||
guard try predicate(self[idxBeforeSliceEnd]) else {
|
||||
return self[sliceStart..<sliceEnd]
|
||||
}
|
||||
sliceEnd = idxBeforeSliceEnd
|
||||
}
|
||||
|
||||
// Trimmed everything.
|
||||
return self[Range(uncheckedBounds: (sliceStart, sliceStart))]
|
||||
let start = try endOfPrefix(while: predicate)
|
||||
let end = try self[start...].startOfSuffix(while: predicate)
|
||||
return self[start..<end]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import Darwin
|
||||
import Algorithms
|
||||
|
||||
struct Benchmark {
|
||||
var name: String
|
||||
var `default`: Int
|
||||
var body: (Int) -> Int
|
||||
}
|
||||
|
||||
let benchmarks = [
|
||||
Benchmark(name: "chain", default: 100) { count in
|
||||
let x = String(repeating: "_", count: 10_000)
|
||||
.chained(with: String(repeating: "-", count: 10_000))
|
||||
.chained(with: "0")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(of: "0")!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "lazy chunked", default: 1000) { count in
|
||||
let x = (1...1000).shuffled()
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.lazy.chunked(by: <=)
|
||||
v &+= y.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "combinations", default: 100) { count in
|
||||
let x = 1...30
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.combinations(ofCount: 4)
|
||||
let combo = y.first(where: { combo in combo.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= combo.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable partition", default: 100) { count in
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
var x = Array(1...10000)
|
||||
let i = x.stablePartition(by: { $0.isMultiple(of: 3) })
|
||||
v &+= i
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "permutations", default: 10) { count in
|
||||
let x = 1...20
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let y = x.permutations(ofCount: 4)
|
||||
let perm = y.first(where: { perm in perm.allSatisfy { $0.isMultiple(of: 2) }})!
|
||||
v &+= perm.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "product", default: 1000) { count in
|
||||
let x = product(1...100, "abcdefghijklmnopqrstuvwxyz")
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let i = x.firstIndex(where: { $0 == 77 && $1 == "m" })!
|
||||
let d = x.distance(from: x.startIndex, to: i)
|
||||
v &+= d
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "stable sample", default: 1000) { count in
|
||||
let x = 1...10000
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.randomStableSample(count: 20)
|
||||
v &+= r.reduce(0, +)
|
||||
}
|
||||
return v
|
||||
},
|
||||
|
||||
Benchmark(name: "uniqued", default: 1000) { count in
|
||||
let x = repeatElement(1...1000, count: 1000)
|
||||
var v = 0
|
||||
for _ in 0..<count {
|
||||
let r = x.uniqued()
|
||||
v &+= r.count
|
||||
}
|
||||
return v
|
||||
},
|
||||
]
|
||||
|
||||
func printChoices() -> Never {
|
||||
print(benchmarks.enumerated().map { "\($0): \($1.name)" }.joined(separator: "\n"))
|
||||
exit(0)
|
||||
}
|
||||
|
||||
if CommandLine.arguments.count <= 1 {
|
||||
printChoices()
|
||||
} else {
|
||||
guard let choice = Int(CommandLine.arguments[1]), benchmarks.indices.contains(choice) else {
|
||||
print("Invalid choice:")
|
||||
printChoices()
|
||||
}
|
||||
|
||||
let bench = benchmarks[choice]
|
||||
let count: Int
|
||||
if CommandLine.arguments.count > 2, let c = Int(CommandLine.arguments[2]) {
|
||||
count = c
|
||||
} else {
|
||||
count = bench.default
|
||||
}
|
||||
|
||||
print(bench.body(count))
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2020 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 Algorithms
|
||||
|
||||
final class FirstNonNilTests: XCTestCase {
|
||||
func testFirstNonNil() {
|
||||
XCTAssertNil([].firstNonNil { $0 })
|
||||
XCTAssertNil(["A", "B", "C"].firstNonNil { Int($0) })
|
||||
XCTAssertNil(["A", "B", "C"].firstNonNil { _ in nil })
|
||||
XCTAssertEqual(["A", "B", "10"].firstNonNil { Int($0) }, 10)
|
||||
XCTAssertEqual(["20", "B", "10"].firstNonNil { Int($0) }, 20)
|
||||
}
|
||||
}
|
||||
@@ -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, 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, 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 = [
|
||||
[1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0],
|
||||
[1, 1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0],
|
||||
[1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0],
|
||||
[1, 1, 1, 0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0, 0, 1, 0],
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1, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 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, 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 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<C: Collection>
|
||||
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<L: LazySequenceProtocol, S: Sequence>(
|
||||
actual: L,
|
||||
expected: S,
|
||||
maxSplits: MaxSplits,
|
||||
omittingEmptySubsequences: OmittingEmptySubsequences
|
||||
) -> String {
|
||||
"for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)"
|
||||
}
|
||||
|
||||
private func _validateAsSequence<T: Sequence>(_ 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))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,14 +64,17 @@ final class PartitionTests: XCTestCase {
|
||||
func testStablePartitionWithSubrange() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
for j in 0..<length {
|
||||
var b = a
|
||||
let partitionRange = 0..<j
|
||||
let condition = { $0 < j - 1 }
|
||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||
XCTAssertEqual(p, partitionRange.count > 0 ? 1 : 0)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
for i in 0..<length {
|
||||
for j in 0...i {
|
||||
var b = a
|
||||
let partitionRange = j..<i
|
||||
let condition = { $0 < i - 1 }
|
||||
let p = b.stablePartition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,4 +91,46 @@ final class PartitionTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitionWithSubrangeBidirectionalCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
for i in 0..<length {
|
||||
for j in 0...i {
|
||||
var b = a
|
||||
let partitionRange = j..<i
|
||||
let condition = { $0 < i - 1 }
|
||||
let p = b.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPartitionWithSubrangeMutableCollection() {
|
||||
for length in 10...20 {
|
||||
let a = Array(0..<length)
|
||||
for i in 0..<length {
|
||||
for j in 0...i {
|
||||
var b = a.eraseToAnyMutableCollection()
|
||||
var bdc = a
|
||||
let partitionRange = j..<i
|
||||
let condition = { $0 < i - 1 }
|
||||
let p = b.partition(subrange: partitionRange, by: condition)
|
||||
let bdcp = bdc.partition(subrange: partitionRange, by: condition)
|
||||
|
||||
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
|
||||
|
||||
// Must produce the same result as the `BidirectionalCollection` specialized overload.
|
||||
XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
|
||||
XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ final class StridingTests: XCTestCase {
|
||||
let a = (0...10)
|
||||
XCTAssertEqualSequences(a.striding(by: 6), a.striding(by: 2).striding(by: 3))
|
||||
XCTAssertTrue(a.striding(by: 6) == a.striding(by: 2).striding(by: 3))
|
||||
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == Stride<ClosedRange<Int>>.self)
|
||||
XCTAssert(type(of: a.striding(by: 2).striding(by: 3)) == StrideCollection<ClosedRange<Int>>.self)
|
||||
}
|
||||
|
||||
func testEquality() {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Algorithms
|
||||
@testable import Algorithms
|
||||
|
||||
final class SuffixTests: XCTestCase {
|
||||
func testSuffix() {
|
||||
@@ -23,4 +23,28 @@ final class SuffixTests: XCTestCase {
|
||||
let empty: [Int] = []
|
||||
XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
|
||||
}
|
||||
|
||||
func testEndOfPrefix() {
|
||||
let array = Array(0..<10)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
|
||||
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
|
||||
|
||||
let empty = [Int]()
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
|
||||
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
|
||||
}
|
||||
|
||||
func testStartOfSuffix() {
|
||||
let array = Array(0..<10)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
|
||||
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
|
||||
|
||||
let empty = [Int]()
|
||||
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
|
||||
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
|
||||
XCTAssertEqual(empty.startOfSuffix(while: { _ in true }), empty.startIndex)
|
||||
}
|
||||
}
|
||||
@@ -46,13 +46,69 @@ struct SplitMix64: RandomNumberGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
// An eraser helper to any mutable collection
|
||||
struct AnyMutableCollection<Base> where Base: MutableCollection {
|
||||
var base: Base
|
||||
}
|
||||
|
||||
extension AnyMutableCollection: MutableCollection {
|
||||
typealias Index = Base.Index
|
||||
typealias Element = Base.Element
|
||||
|
||||
var startIndex: Base.Index { base.startIndex }
|
||||
var endIndex: Base.Index { base.endIndex }
|
||||
|
||||
func index(after i: Index) -> Index {
|
||||
return base.index(after: i)
|
||||
}
|
||||
|
||||
subscript(position: Base.Index) -> Base.Element {
|
||||
_read { yield base[position] }
|
||||
set { base[position] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
extension MutableCollection {
|
||||
func eraseToAnyMutableCollection() -> AnyMutableCollection<Self> {
|
||||
AnyMutableCollection(base: self)
|
||||
}
|
||||
}
|
||||
|
||||
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
_ expression1: @autoclosure () throws -> S1,
|
||||
_ expression2: @autoclosure () throws -> S2,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
|
||||
try XCTAssert(expression1().elementsEqual(expression2()), message(), file: file, line: line)
|
||||
try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
|
||||
message(), file: file, line: line)
|
||||
}
|
||||
|
||||
// Two sequences contains exactly the same element but not necessarily in the same order.
|
||||
func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
_ expression1: @autoclosure () throws -> S1,
|
||||
_ expression2: @autoclosure () throws -> S2,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
|
||||
var s1 = Array(try expression1())
|
||||
var missing: [S1.Element] = []
|
||||
for elt in try expression2() {
|
||||
guard let idx = s1.firstIndex(of: elt) else {
|
||||
missing.append(elt)
|
||||
continue
|
||||
}
|
||||
s1.remove(at: idx)
|
||||
}
|
||||
|
||||
XCTAssertTrue(
|
||||
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
|
||||
file: file, line: line
|
||||
)
|
||||
|
||||
XCTAssertTrue(
|
||||
s1.isEmpty, "first sequence contains \(s1) missing from second sequence",
|
||||
file: file, line: line
|
||||
)
|
||||
}
|
||||
|
||||
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
@@ -62,7 +118,31 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) rethrows where S1.Element == S2.Element {
|
||||
try XCTAssert(expression1().elementsEqual(expression2(), by: areEquivalent), message(), file: file, line: line)
|
||||
|
||||
func fail(_ reason: String) {
|
||||
let message = message()
|
||||
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
var iter1 = try expression1().makeIterator()
|
||||
var iter2 = try expression2().makeIterator()
|
||||
var idx = 0
|
||||
while true {
|
||||
switch (iter1.next(), iter2.next()) {
|
||||
case let (e1?, e2?) where areEquivalent(e1, e2):
|
||||
idx += 1
|
||||
continue
|
||||
case let (e1?, e2?):
|
||||
fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)")
|
||||
case (_?, nil):
|
||||
fail("second sequence shorter than first")
|
||||
case (nil, _?):
|
||||
fail("first sequence shorter than second")
|
||||
case (nil, nil): break
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}
|
||||
|
||||
Reference in new issue
Block a user