Compare commits

..
1 Commits
Author SHA1 Message Date
Nate Cook 87e50f483c Prepare for 1.2.1 release 2025-02-10 14:43:52 -06:00
64 changed files with 1964 additions and 2776 deletions

No files matched your search

-34
View File
@@ -1,34 +0,0 @@
name: Pull request
permissions:
contents: read
on:
pull_request:
types: [opened, reopened, synchronize]
jobs:
validate_format_config:
name: Validate Format Config
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install apt dependencies
run: sudo apt-get -qq update && sudo apt-get -qq -y install curl
- name: Compare against swift-mmio swift-format config
run: |
curl -sL https://raw.githubusercontent.com/apple/swift-mmio/refs/heads/main/.swift-format -o .swift-format-mmio
diff .swift-format .swift-format-mmio
tests:
name: Test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
with:
enable_wasm_sdk_build: true
enable_android_sdk_build: true
enable_android_sdk_checks: true
soundness:
name: Soundness
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
-10
View File
@@ -1,10 +0,0 @@
@@===----------------------------------------------------------------------===@@
@@
@@ This source file is part of the Swift Algorithms open source project
@@
@@ Copyright (c) YEARS 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
@@
@@===----------------------------------------------------------------------===@@
-30
View File
@@ -1,30 +0,0 @@
.gitignore
**/.gitignore
.licenseignore
.gitattributes
.git-blame-ignore-revs
.mailfilter
.mailmap
.spi.yml
.swift-format
.editorconfig
.github/*
*.md
*.mdoc
*.txt
*.yml
*.yaml
*.json
*.png
*.bash
*.cmake
*.cmake.in
Package.swift
**/Package.swift
Package@*.swift
**/Package@*.swift
Package.resolved
**/Package.resolved
.unacceptablelanguageignore
**/Snapshots/*
Xcode/*
+1
View File
@@ -2,3 +2,4 @@ version: 1
builder: builder:
configs: configs:
- documentation_targets: [Algorithms] - documentation_targets: [Algorithms]
-71
View File
@@ -1,71 +0,0 @@
{
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"indentation" : {
"spaces" : 2
},
"indentConditionalCompilationBlocks" : false,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : false,
"lineBreakBeforeEachGenericRequirement" : false,
"lineLength" : 80,
"maximumBlankLines" : 1,
"multiElementCollectionTrailingCommas" : true,
"noAssignmentInExpressions" : {
"allowedFunctions" : [
"XCTAssertNoThrow"
]
},
"prioritizeKeepingFunctionOutputTogether" : false,
"respectsExistingLineBreaks" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLiteralForEmptyCollectionInit" : true,
"AlwaysUseLowerCamelCase" : true,
"AmbiguousTrailingClosureOverload" : false,
"BeginDocumentationCommentWithOneLineSummary" : true,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : true,
"NeverUseForceTry" : true,
"NeverUseImplicitlyUnwrappedOptionals" : true,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoPlaygroundLiterals" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OmitExplicitReturns" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"TypeNamesShouldBeCapitalized" : true,
"UseEarlyExits" : false,
"UseExplicitNilCheckInConditions" : true,
"UseLetInEveryBoundCaseVariable" : true,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : true,
"UseSynthesizedInitializer" : true,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : true
},
"spacesBeforeEndOfLineComments": 2,
"spacesAroundRangeFormationOperators" : false,
"tabWidth" : 2,
"version" : 1
}
+2 -2
View File
@@ -241,7 +241,7 @@ The 0.2.0 release includes contributions from [CTMacUser], [LemonSpike],
- The base collections of the sequence and collection wrapper types are no - The base collections of the sequence and collection wrapper types are no
longer public ([#85], [#125]), and the wrapper types no longer conform to the longer public ([#85], [#125]), and the wrapper types no longer conform to the
`Equatable` or `Hashable` protocols ([#124]). If you need those conformances, `Equatable` or `Hashable` protocols ([#124]). If you need those conformances,
convert the wrapper type to an `Array` or other collection currency type convert the wrapper type to an `Array` or other collection currrency type
before storing. Please file an issue if these changes pose a problem for your before storing. Please file an issue if these changes pose a problem for your
use case. use case.
@@ -335,7 +335,7 @@ The 0.0.3 release includes contributions from [benrimmington], [danielctull],
### Fixes ### Fixes
- `Algorithms` now builds under SwiftPM on Windows. - `Algorithms` now builds under SwiftPM on Windows.
- A wide variety of errors, misspellings, and omissions in the documentation - A wide variety of errors, misspellings, and ommissions in the documentation
and guides have been fixed. and guides have been fixed.
- Index/distance calculations for the `Product2` and `Chain` types have been - Index/distance calculations for the `Product2` and `Chain` types have been
corrected. corrected.
-37
View File
@@ -1,37 +0,0 @@
# EndsWith
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/EndsWith.swift) |
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/EndsWithTests.swift)]
This function checks whether the final elements of the one collection are the same as the elements in another collection.
```
## Detailed Design
The `ends(with:)` and `ends(with:by:)` functions are added as methods on an extension of
`BidirectionalCollection`.
```swift
extension BidirectionalCollection {
public func ends<PossibleSuffix: BidirectionalCollection>(
with possibleSuffix: PossibleSuffix
) -> Bool where PossibleSuffix.Element == Element
public func ends<PossibleSuffix: BidirectionalCollection>(
with possibleSuffix: PossibleSuffix,
by areEquivalent: (Element, PossibleSuffix.Element) throws -> Bool
) rethrows -> Bool
}
```
This method requires `BidirectionalCollection` for being able to traverse back from the end of the collection. It also requires the `possibleSuffix` to be `BidirectionalCollection`, because it too needs to be traverse backwards, to compare its elements against `self` from back to front.
### Complexity
O(*m*), where *m* is the lesser of the length of the collection and the length of `possibleSuffix`.
### Naming
The function's name resembles that of an existing Swift function
`starts(with:)`, which performs same operation however in the forward direction
of the collection.
+19 -19
View File
@@ -13,23 +13,23 @@
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "swift-algorithms", name: "swift-algorithms",
products: [ products: [
.library( .library(
name: "Algorithms", name: "Algorithms",
targets: ["Algorithms"]) targets: ["Algorithms"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0") .package(url: "https://github.com/apple/swift-numerics.git", from: "1.0.0"),
], ],
targets: [ targets: [
.target( .target(
name: "Algorithms", name: "Algorithms",
dependencies: [ dependencies: [
.product(name: "RealModule", package: "swift-numerics") .product(name: "RealModule", package: "swift-numerics"),
]), ]),
.testTarget( .testTarget(
name: "SwiftAlgorithmsTests", name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]), dependencies: ["Algorithms"]),
] ]
) )
-20
View File
@@ -1,20 +0,0 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the Swift Algorithms open source project
##
## Copyright (c) 2025 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
##
##===----------------------------------------------------------------------===##
# Move to the project root
cd "$(dirname "$0")" || exit
cd ..
echo "Formatting Swift sources in $(pwd)"
# Run the format / lint commands
git ls-files -z '*.swift' | xargs -0 swift format format --parallel --in-place
git ls-files -z '*.swift' | xargs -0 swift format lint --strict --parallel
+25 -39
View File
@@ -126,7 +126,7 @@ extension AdjacentPairsSequence: Sequence {
} }
extension AdjacentPairsSequence: LazySequenceProtocol extension AdjacentPairsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
/// A collection of adjacent pairs of elements built from an underlying /// A collection of adjacent pairs of elements built from an underlying
/// collection. /// collection.
@@ -143,8 +143,7 @@ public struct AdjacentPairsCollection<Base: Collection> {
@inlinable @inlinable
internal init(base: Base) { internal init(base: Base) {
self.base = base self.base = base
self.secondBaseIndex = self.secondBaseIndex = base.isEmpty
base.isEmpty
? base.endIndex ? base.endIndex
: base.index(after: base.startIndex) : base.index(after: base.startIndex)
} }
@@ -155,7 +154,7 @@ extension AdjacentPairsCollection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal var first: Base.Index internal var first: Base.Index
@usableFromInline @usableFromInline
internal var second: Base.Index internal var second: Base.Index
@@ -169,7 +168,7 @@ extension AdjacentPairsCollection {
public static func == (lhs: Index, rhs: Index) -> Bool { public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.first == rhs.first lhs.first == rhs.first
} }
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.first < rhs.first lhs.first < rhs.first
@@ -184,7 +183,7 @@ extension AdjacentPairsCollection: Collection {
first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex, first: secondBaseIndex == base.endIndex ? base.endIndex : base.startIndex,
second: secondBaseIndex) second: secondBaseIndex)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(first: base.endIndex, second: base.endIndex) Index(first: base.endIndex, second: base.endIndex)
@@ -208,23 +207,20 @@ extension AdjacentPairsCollection: Collection {
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
guard guard let result = distance > 0
let result = distance > 0 ? offsetForward(i, by: distance, limitedBy: endIndex)
? offsetForward(i, by: distance, limitedBy: endIndex) : offsetBackward(i, by: -distance, limitedBy: startIndex)
: offsetBackward(i, by: -distance, limitedBy: startIndex)
else { fatalError("Index out of bounds") } else { fatalError("Index out of bounds") }
return result return result
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index, offsetBy distance: Int, limitedBy limit: Index
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
guard distance != 0 else { return i } guard distance != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
if distance > 0 { if distance > 0 {
let limit = limit > i ? limit : endIndex let limit = limit > i ? limit : endIndex
return offsetForward(i, by: distance, limitedBy: limit) return offsetForward(i, by: distance, limitedBy: limit)
@@ -233,48 +229,38 @@ extension AdjacentPairsCollection: Collection {
return offsetBackward(i, by: -distance, limitedBy: limit) return offsetBackward(i, by: -distance, limitedBy: limit)
} }
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit > i) assert(limit > i)
let newFirst = base.index( guard let newFirst = base.index(i.second, offsetBy: distance - 1, limitedBy: limit.first),
i.second, newFirst != base.endIndex
offsetBy: distance - 1,
limitedBy: limit.first)
guard let newFirst, newFirst != base.endIndex
else { return nil } else { return nil }
let newSecond = base.index(after: newFirst) let newSecond = base.index(after: newFirst)
precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex") precondition(newSecond <= base.endIndex, "Can't advance beyond endIndex")
return newSecond == base.endIndex return newSecond == base.endIndex
? endIndex ? endIndex
: Index(first: newFirst, second: newSecond) : Index(first: newFirst, second: newSecond)
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit < i) assert(limit < i)
let offset = i == endIndex ? 0 : 1 let offset = i == endIndex ? 0 : 1
let newSecond = base.index( guard let newSecond = base.index(
i.first, i.first,
offsetBy: -(distance - offset), offsetBy: -(distance - offset),
limitedBy: limit.second) limitedBy: limit.second)
guard let newSecond
else { return nil } else { return nil }
let newFirst = base.index(newSecond, offsetBy: -1) let newFirst = base.index(newSecond, offsetBy: -1)
precondition(newFirst >= base.startIndex, "Can't move before startIndex") precondition(newFirst >= base.startIndex, "Can't move before startIndex")
return Index(first: newFirst, second: newSecond) return Index(first: newFirst, second: newSecond)
@@ -296,12 +282,12 @@ extension AdjacentPairsCollection: Collection {
} }
extension AdjacentPairsCollection: BidirectionalCollection extension AdjacentPairsCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't offset before startIndex") precondition(i != startIndex, "Can't offset before startIndex")
let second = let second = i == endIndex
i == endIndex
? base.index(before: base.endIndex) ? base.index(before: base.endIndex)
: i.first : i.first
let first = base.index(before: second) let first = base.index(before: second)
@@ -310,10 +296,10 @@ where Base: BidirectionalCollection {
} }
extension AdjacentPairsCollection: RandomAccessCollection extension AdjacentPairsCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol extension AdjacentPairsCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable { extension AdjacentPairsCollection.Index: Hashable where Base.Index: Hashable {
@inlinable @inlinable
+57 -66
View File
@@ -11,11 +11,12 @@
/// A concatenation of two sequences with the same element type. /// A concatenation of two sequences with the same element type.
public struct Chain2Sequence<Base1: Sequence, Base2: Sequence> public struct Chain2Sequence<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element { where Base1.Element == Base2.Element
{
/// The first sequence in this chain. /// The first sequence in this chain.
@usableFromInline @usableFromInline
internal let base1: Base1 internal let base1: Base1
/// The second sequence in this chain. /// The second sequence in this chain.
@usableFromInline @usableFromInline
internal let base2: Base2 internal let base2: Base2
@@ -32,30 +33,29 @@ extension Chain2Sequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var iterator1: Base1.Iterator internal var iterator1: Base1.Iterator
@usableFromInline @usableFromInline
internal var iterator2: Base2.Iterator internal var iterator2: Base2.Iterator
@inlinable @inlinable
internal init(_ concatenation: Chain2Sequence) { internal init(_ concatenation: Chain2Sequence) {
iterator1 = concatenation.base1.makeIterator() iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator() iterator2 = concatenation.base2.makeIterator()
} }
@inlinable @inlinable
public mutating func next() -> Base1.Element? { public mutating func next() -> Base1.Element? {
iterator1.next() ?? iterator2.next() return iterator1.next() ?? iterator2.next()
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(self) Iterator(self)
} }
} }
extension Chain2Sequence: Collection extension Chain2Sequence: Collection where Base1: Collection, Base2: Collection {
where Base1: Collection, Base2: Collection {
/// A position in a `Chain2Sequence` instance. /// A position in a `Chain2Sequence` instance.
public struct Index: Comparable { public struct Index: Comparable {
// The internal index representation, which can either be an index of the // The internal index representation, which can either be an index of the
@@ -91,14 +91,14 @@ where Base1: Collection, Base2: Collection {
return true return true
case (.second, .first): case (.second, .first):
return false return false
case (.first(let l), .first(let r)): case let (.first(l), .first(r)):
return l < r return l < r
case (.second(let l), .second(let r)): case let (.second(l), .second(r)):
return l < r return l < r
} }
} }
} }
/// Converts an index of `Base1` to the corresponding `Index` by mapping /// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`. /// `base1.endIndex` to `base2.startIndex`.
@inlinable @inlinable
@@ -121,9 +121,9 @@ where Base1: Collection, Base2: Collection {
@inlinable @inlinable
public subscript(i: Index) -> Base1.Element { public subscript(i: Index) -> Base1.Element {
switch i.position { switch i.position {
case .first(let i): case let .first(i):
return base1[i] return base1[i]
case .second(let i): case let .second(i):
return base2[i] return base2[i]
} }
} }
@@ -131,23 +131,23 @@ where Base1: Collection, Base2: Collection {
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
switch i.position { switch i.position {
case .first(let i): case let .first(i):
assert(i != base1.endIndex) assert(i != base1.endIndex)
return normalizeIndex(base1.index(after: i)) return normalizeIndex(base1.index(after: i))
case .second(let i): case let .second(i):
return Index(second: base2.index(after: i)) return Index(second: base2.index(after: i))
} }
} }
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
return distance > 0 return distance > 0
? offsetForward(i, by: distance) ? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance) : offsetBackward(i, by: -distance)
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index,
@@ -168,50 +168,45 @@ where Base1: Collection, Base2: Collection {
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit >= i) assert(limit >= i)
switch (i.position, limit.position) { switch (i.position, limit.position) {
case (.first(let i), .first(let limit)): case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: distance, limitedBy: limit) return base1.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(first:)) .map(Index.init(first:))
case (.first(let i), .second(let limit)): case let (.first(i), .second(limit)):
guard if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) // the offset stays within the bounds of `base1`
else { return normalizeIndex(j)
} else {
// the offset overflows the bounds of `base1` by `n - d` // the offset overflows the bounds of `base1` by `n - d`
let d = base1.distance(from: i, to: base1.endIndex) let d = base1.distance(from: i, to: base1.endIndex)
return return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
base2
.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
.map(Index.init(second:)) .map(Index.init(second:))
} }
// the offset stays within the bounds of `base1`
return normalizeIndex(j)
case (.second, .first): case (.second, .first):
// impossible because `limit >= i` // impossible because `limit >= i`
fatalError() fatalError()
case (.second(let i), .second(let limit)): case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: distance, limitedBy: limit) return base2.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(second:)) .map(Index.init(second:))
} }
@@ -219,54 +214,49 @@ where Base1: Collection, Base2: Collection {
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit <= i) assert(limit <= i)
switch (i.position, limit.position) { switch (i.position, limit.position) {
case (.first(let i), .first(let limit)): case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: -distance, limitedBy: limit) return base1.index(i, offsetBy: -distance, limitedBy: limit)
.map(Index.init(first:)) .map(Index.init(first:))
case (.first, .second): case (.first, .second):
// impossible because `limit <= i` // impossible because `limit <= i`
fatalError() fatalError()
case (.second(let i), .first(let limit)): case let (.second(i), .first(limit)):
guard if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) // the offset stays within the bounds of `base2`
else { return Index(second: j)
} else {
// the offset overflows the bounds of `base2` by `n - d` // the offset overflows the bounds of `base2` by `n - d`
let d = base2.distance(from: base2.startIndex, to: i) let d = base2.distance(from: base2.startIndex, to: i)
return return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
base1
.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
.map(Index.init(first:)) .map(Index.init(first:))
} }
// the offset stays within the bounds of `base2`
return Index(second: j)
case (.second(let i), .second(let limit)): case let (.second(i), .second(limit)):
// `limit` is relevant, so `base1` cannot be reached // `limit` is relevant, so `base1` cannot be reached
return base2.index(i, offsetBy: -distance, limitedBy: limit) return base2.index(i, offsetBy: -distance, limitedBy: limit)
.map(Index.init(second:)) .map(Index.init(second:))
} }
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
switch (start.position, end.position) { switch (start.position, end.position) {
case (.first(let i), .first(let j)): case let (.first(i), .first(j)):
return base1.distance(from: i, to: j) return base1.distance(from: i, to: j)
case (.second(let i), .second(let j)): case let (.second(i), .second(j)):
return base2.distance(from: i, to: j) return base2.distance(from: i, to: j)
case (.first(let i), .second(let j)): case let (.first(i), .second(j)):
return base1.distance(from: i, to: base1.endIndex) return base1.distance(from: i, to: base1.endIndex)
+ base2.distance(from: base2.startIndex, to: j) + base2.distance(from: base2.startIndex, to: j)
case (.second(let i), .first(let j)): case let (.second(i), .first(j)):
return base2.distance(from: i, to: base2.startIndex) return base2.distance(from: i, to: base2.startIndex)
+ base1.distance(from: base1.endIndex, to: j) + base1.distance(from: base1.endIndex, to: j)
} }
@@ -274,14 +264,15 @@ where Base1: Collection, Base2: Collection {
} }
extension Chain2Sequence: BidirectionalCollection extension Chain2Sequence: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection { where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex") assert(i != startIndex, "Can't advance before startIndex")
switch i.position { switch i.position {
case .first(let i): case let .first(i):
return Index(first: base1.index(before: i)) return Index(first: base1.index(before: i))
case .second(let i): case let .second(i):
return i == base2.startIndex return i == base2.startIndex
? Index(first: base1.index(before: base1.endIndex)) ? Index(first: base1.index(before: base1.endIndex))
: Index(second: base2.index(before: i)) : Index(second: base2.index(before: i))
@@ -290,7 +281,7 @@ where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
} }
extension Chain2Sequence: RandomAccessCollection extension Chain2Sequence: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// chain(_:_:) // chain(_:_:)
+140 -195
View File
@@ -17,19 +17,19 @@ public struct ChunkedByCollection<Base: Collection, Subject> {
/// The collection that this instance provides a view onto. /// The collection that this instance provides a view onto.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
/// The projection function. /// The projection function.
@usableFromInline @usableFromInline
internal let projection: (Base.Element) -> Subject internal let projection: (Base.Element) -> Subject
/// The predicate. /// The predicate.
@usableFromInline @usableFromInline
internal let belongInSameGroup: (Subject, Subject) -> Bool internal let belongInSameGroup: (Subject, Subject) -> Bool
/// The end index of the first chunk. /// The end index of the first chunk.
@usableFromInline @usableFromInline
internal var endOfFirstChunk: Base.Index internal var endOfFirstChunk: Base.Index
@inlinable @inlinable
internal init( internal init(
base: Base, base: Base,
@@ -40,7 +40,7 @@ public struct ChunkedByCollection<Base: Collection, Subject> {
self.projection = projection self.projection = projection
self.belongInSameGroup = belongInSameGroup self.belongInSameGroup = belongInSameGroup
self.endOfFirstChunk = base.startIndex self.endOfFirstChunk = base.startIndex
if !base.isEmpty { if !base.isEmpty {
endOfFirstChunk = endOfChunk(startingAt: base.startIndex) endOfFirstChunk = endOfChunk(startingAt: base.startIndex)
} }
@@ -53,19 +53,19 @@ extension ChunkedByCollection: Collection {
/// The range corresponding to the chunk at this position. /// The range corresponding to the chunk at this position.
@usableFromInline @usableFromInline
internal var baseRange: Range<Base.Index> internal var baseRange: Range<Base.Index>
@inlinable @inlinable
internal init(_ baseRange: Range<Base.Index>) { internal init(_ baseRange: Range<Base.Index>) {
self.baseRange = baseRange self.baseRange = baseRange
} }
@inlinable @inlinable
public static func == (lhs: Index, rhs: Index) -> Bool { public static func == (lhs: Index, rhs: Index) -> Bool {
// Since each index represents the range of a disparate chunk, no two // Since each index represents the range of a disparate chunk, no two
// unique indices will have the same lower bound. // unique indices will have the same lower bound.
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
} }
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
// Only use the lower bound to test for ordering, as above. // Only use the lower bound to test for ordering, as above.
@@ -78,24 +78,24 @@ extension ChunkedByCollection: Collection {
@inlinable @inlinable
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index { internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
var subject = projection(base[start]) var subject = projection(base[start])
return base[base.index(after: start)...].endOfPrefix(while: { element in return base[base.index(after: start)...].endOfPrefix(while: { element in
let nextSubject = projection(element) let nextSubject = projection(element)
defer { subject = nextSubject } defer { subject = nextSubject }
return belongInSameGroup(subject, nextSubject) return belongInSameGroup(subject, nextSubject)
}) })
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index(base.startIndex..<endOfFirstChunk) Index(base.startIndex..<endOfFirstChunk)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(base.endIndex..<base.endIndex) Index(base.endIndex..<base.endIndex)
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
@@ -104,7 +104,7 @@ extension ChunkedByCollection: Collection {
let end = endOfChunk(startingAt: upperBound) let end = endOfChunk(startingAt: upperBound)
return Index(upperBound..<end) return Index(upperBound..<end)
} }
@inlinable @inlinable
public subscript(position: Index) -> Base.SubSequence { public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex") precondition(position != endIndex, "Can't subscript using endIndex")
@@ -115,14 +115,15 @@ extension ChunkedByCollection: Collection {
extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {} extension ChunkedByCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunkedByCollection: BidirectionalCollection extension ChunkedByCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
/// Returns the index in the base collection of the start of the chunk ending /// Returns the index in the base collection of the start of the chunk ending
/// at the given index. /// at the given index.
@inlinable @inlinable
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index { internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
let indexBeforeEnd = base.index(before: end) let indexBeforeEnd = base.index(before: end)
var subject = projection(base[indexBeforeEnd]) var subject = projection(base[indexBeforeEnd])
return base[..<indexBeforeEnd].startOfSuffix(while: { element in return base[..<indexBeforeEnd].startOfSuffix(while: { element in
let nextSubject = projection(element) let nextSubject = projection(element)
defer { subject = nextSubject } defer { subject = nextSubject }
@@ -147,7 +148,7 @@ extension ChunkedByCollection: LazyCollectionProtocol {}
public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> { public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
@usableFromInline @usableFromInline
internal var chunked: ChunkedByCollection<Base, Subject> internal var chunked: ChunkedByCollection<Base, Subject>
@inlinable @inlinable
internal init( internal init(
base: Base, base: Base,
@@ -162,26 +163,24 @@ public struct ChunkedOnCollection<Base: Collection, Subject: Equatable> {
extension ChunkedOnCollection: Collection { extension ChunkedOnCollection: Collection {
public typealias Index = ChunkedByCollection<Base, Subject>.Index public typealias Index = ChunkedByCollection<Base, Subject>.Index
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
chunked.startIndex chunked.startIndex
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
chunked.endIndex chunked.endIndex
} }
@inlinable @inlinable
public subscript(position: Index) -> (Subject, Base.SubSequence) { public subscript(position: Index) -> (Subject, Base.SubSequence) {
let subsequence = chunked[position] let subsequence = chunked[position]
// swift-format-ignore: NeverForceUnwrap
// Chunks are never empty, so `.first!` is safe.
let subject = chunked.projection(subsequence.first!) let subject = chunked.projection(subsequence.first!)
return (subject, subsequence) return (subject, subsequence)
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
chunked.index(after: i) chunked.index(after: i)
@@ -189,7 +188,8 @@ extension ChunkedOnCollection: Collection {
} }
extension ChunkedOnCollection: BidirectionalCollection extension ChunkedOnCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
chunked.index(before: i) chunked.index(before: i)
@@ -204,26 +204,26 @@ public struct EvenlyChunkedCollection<Base: Collection> {
/// The base collection. /// The base collection.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
/// The number of equal chunks the base collection is divided into. /// The number of equal chunks the base collection is divided into.
@usableFromInline @usableFromInline
internal let numberOfChunks: Int internal let numberOfChunks: Int
/// The count of the base collection. /// The count of the base collection.
@usableFromInline @usableFromInline
internal let baseCount: Int internal let baseCount: Int
/// The upper bound of the first chunk. /// The upper bound of the first chunk.
@usableFromInline @usableFromInline
internal var firstUpperBound: Base.Index internal var firstUpperBound: Base.Index
@inlinable @inlinable
internal init(base: Base, numberOfChunks: Int) { internal init(base: Base, numberOfChunks: Int) {
self.base = base self.base = base
self.numberOfChunks = numberOfChunks self.numberOfChunks = numberOfChunks
self.baseCount = base.count self.baseCount = base.count
self.firstUpperBound = base.startIndex self.firstUpperBound = base.startIndex
if numberOfChunks > 0 { if numberOfChunks > 0 {
firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0) firstUpperBound = endOfChunk(startingAt: base.startIndex, offset: 0)
} }
@@ -237,42 +237,37 @@ extension EvenlyChunkedCollection {
internal var numberOfLargeChunks: Int { internal var numberOfLargeChunks: Int {
baseCount % numberOfChunks baseCount % numberOfChunks
} }
/// Returns the size of a chunk at a given offset. /// Returns the size of a chunk at a given offset.
@inlinable @inlinable
internal func sizeOfChunk(offset: Int) -> Int { internal func sizeOfChunk(offset: Int) -> Int {
let isLargeChunk = offset < numberOfLargeChunks let isLargeChunk = offset < numberOfLargeChunks
return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0) return baseCount / numberOfChunks + (isLargeChunk ? 1 : 0)
} }
/// Returns the index in the base collection of the end of the chunk starting /// Returns the index in the base collection of the end of the chunk starting
/// at the given index. /// at the given index.
@inlinable @inlinable
internal func endOfChunk(startingAt start: Base.Index, offset: Int) internal func endOfChunk(startingAt start: Base.Index, offset: Int) -> Base.Index {
-> Base.Index
{
base.index(start, offsetBy: sizeOfChunk(offset: offset)) base.index(start, offsetBy: sizeOfChunk(offset: offset))
} }
/// Returns the index in the base collection of the start of the chunk ending /// Returns the index in the base collection of the start of the chunk ending
/// at the given index. /// at the given index.
@inlinable @inlinable
internal func startOfChunk(endingAt end: Base.Index, offset: Int) internal func startOfChunk(endingAt end: Base.Index, offset: Int) -> Base.Index {
-> Base.Index
{
base.index(end, offsetBy: -sizeOfChunk(offset: offset)) base.index(end, offsetBy: -sizeOfChunk(offset: offset))
} }
/// Returns the index that corresponds to the chunk that starts at the given /// Returns the index that corresponds to the chunk that starts at the given
/// base index. /// base index.
@inlinable @inlinable
internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index internal func indexOfChunk(startingAt start: Base.Index, offset: Int) -> Index {
{
guard offset != numberOfChunks else { return endIndex } guard offset != numberOfChunks else { return endIndex }
let end = endOfChunk(startingAt: start, offset: offset) let end = endOfChunk(startingAt: start, offset: offset)
return Index(start..<end, offset: offset) return Index(start..<end, offset: offset)
} }
/// Returns the index that corresponds to the chunk that ends at the given /// Returns the index that corresponds to the chunk that ends at the given
/// base index. /// base index.
@inlinable @inlinable
@@ -287,56 +282,55 @@ extension EvenlyChunkedCollection: Collection {
/// The range corresponding to the chunk at this position. /// The range corresponding to the chunk at this position.
@usableFromInline @usableFromInline
internal var baseRange: Range<Base.Index> internal var baseRange: Range<Base.Index>
/// The offset corresponding to the chunk at this position. /// The offset corresponding to the chunk at this position. The first chunk
/// /// has offset `0` and all other chunks have an offset `1` greater than the
/// The first chunk has offset `0` and all other chunks have an offset /// previous.
/// `1` greater than the previous.
@usableFromInline @usableFromInline
internal var offset: Int internal var offset: Int
@inlinable @inlinable
internal init(_ baseRange: Range<Base.Index>, offset: Int) { internal init(_ baseRange: Range<Base.Index>, offset: Int) {
self.baseRange = baseRange self.baseRange = baseRange
self.offset = offset self.offset = offset
} }
@inlinable @inlinable
public static func == (lhs: Self, rhs: Self) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.offset == rhs.offset lhs.offset == rhs.offset
} }
@inlinable @inlinable
public static func < (lhs: Self, rhs: Self) -> Bool { public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.offset < rhs.offset lhs.offset < rhs.offset
} }
} }
public typealias Element = Base.SubSequence public typealias Element = Base.SubSequence
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index(base.startIndex..<firstUpperBound, offset: 0) Index(base.startIndex..<firstUpperBound, offset: 0)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(base.endIndex..<base.endIndex, offset: numberOfChunks) Index(base.endIndex..<base.endIndex, offset: numberOfChunks)
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
let start = i.baseRange.upperBound let start = i.baseRange.upperBound
return indexOfChunk(startingAt: start, offset: i.offset + 1) return indexOfChunk(startingAt: start, offset: i.offset + 1)
} }
@inlinable @inlinable
public subscript(position: Index) -> Element { public subscript(position: Index) -> Element {
precondition(position != endIndex) precondition(position != endIndex)
return base[position.baseRange] return base[position.baseRange]
} }
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
/// Returns the base distance between two `EvenChunksCollection` indices /// Returns the base distance between two `EvenChunksCollection` indices
@@ -344,14 +338,14 @@ extension EvenlyChunkedCollection: Collection {
func baseDistance(from offsetA: Int, to offsetB: Int) -> Int { func baseDistance(from offsetA: Int, to offsetB: Int) -> Int {
let smallChunkSize = baseCount / numberOfChunks let smallChunkSize = baseCount / numberOfChunks
let numberOfChunks = (offsetB - offsetA) - 1 let numberOfChunks = (offsetB - offsetA) - 1
let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB) let largeChunksEnd = Swift.min(self.numberOfLargeChunks, offsetB)
let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1) let largeChunksStart = Swift.min(self.numberOfLargeChunks, offsetA + 1)
let numberOfLargeChunks = largeChunksEnd - largeChunksStart let numberOfLargeChunks = largeChunksEnd - largeChunksStart
return smallChunkSize * numberOfChunks + numberOfLargeChunks return smallChunkSize * numberOfChunks + numberOfLargeChunks
} }
if distance == 0 { if distance == 0 {
return i return i
} else if distance > 0 { } else if distance > 0 {
@@ -366,13 +360,9 @@ extension EvenlyChunkedCollection: Collection {
return indexOfChunk(endingAt: end, offset: offset) return indexOfChunk(endingAt: end, offset: offset)
} }
} }
@inlinable @inlinable
public func index( public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
if distance >= 0 { if distance >= 0 {
if (0..<distance).contains(self.distance(from: i, to: limit)) { if (0..<distance).contains(self.distance(from: i, to: limit)) {
return nil return nil
@@ -384,7 +374,7 @@ extension EvenlyChunkedCollection: Collection {
} }
return index(i, offsetBy: distance) return index(i, offsetBy: distance)
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
end.offset - start.offset end.offset - start.offset
@@ -394,7 +384,8 @@ extension EvenlyChunkedCollection: Collection {
extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {} extension EvenlyChunkedCollection.Index: Hashable where Base.Index: Hashable {}
extension EvenlyChunkedCollection: BidirectionalCollection extension EvenlyChunkedCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't advance before startIndex") precondition(i != startIndex, "Can't advance before startIndex")
@@ -403,13 +394,13 @@ where Base: BidirectionalCollection {
} }
extension EvenlyChunkedCollection: RandomAccessCollection extension EvenlyChunkedCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension EvenlyChunkedCollection: LazySequenceProtocol extension EvenlyChunkedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension EvenlyChunkedCollection: LazyCollectionProtocol extension EvenlyChunkedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {} where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// lazy.chunked(by:) / lazy.chunked(on:) // lazy.chunked(by:) / lazy.chunked(on:)
@@ -420,10 +411,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// the given predicate. /// the given predicate.
/// ///
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements /// - Parameter belongInSameGroup: A closure that takes two adjacent elements
/// of the sequence and returns whether or not they belong in the same /// of the sequence and returns whether or not they belong in the same group.
/// group.
/// - Returns: A collection of subsequences, with every pairwise group of
/// elements in each chunk returning `true` for `belongInSameGroup`.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable
@@ -435,15 +423,13 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
projection: { $0 }, projection: { $0 },
belongInSameGroup: belongInSameGroup) belongInSameGroup: belongInSameGroup)
} }
/// Returns a lazy collection of subsequences of this collection, chunked by /// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to equal values. /// grouping elements that project to equal values.
/// ///
/// - Parameter projection: A closure that takes an element in the sequence /// - Parameter projection: A closure that takes an element in the sequence
/// and returns an `Equatable` value that can be used to determine if /// and returns an `Equatable` value that can be used to determine if adjacent
/// adjacent elements belong in the same group. /// elements belong in the same group.
/// - Returns: A collection of subsequences, with every element in each chunk
/// returning the same value for `projection`.
/// ///
/// - Complexity: O(*n*), because the start index is pre-computed. /// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable @inlinable
@@ -452,8 +438,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
) -> ChunkedOnCollection<Elements, Subject> { ) -> ChunkedOnCollection<Elements, Subject> {
ChunkedOnCollection( ChunkedOnCollection(
base: elements, base: elements,
projection: projection projection: projection)
)
} }
} }
@@ -466,10 +451,8 @@ extension Collection {
/// given predicate. /// given predicate.
/// ///
/// - Parameter belongInSameGroup: A closure that takes two adjacent elements /// - Parameter belongInSameGroup: A closure that takes two adjacent elements
/// of the collection and returns whether or not they belong in the same /// of the collection and returns whether or not they belong in the same
/// group. /// group.
/// - Returns: A collection of subsequences, with every pairwise group of
/// elements in each chunk returning `true` for `belongInSameGroup`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable
@@ -478,10 +461,10 @@ extension Collection {
) rethrows -> [SubSequence] { ) rethrows -> [SubSequence] {
guard !isEmpty else { return [] } guard !isEmpty else { return [] }
var result: [SubSequence] = [] var result: [SubSequence] = []
var start = startIndex var start = startIndex
var current = self[start] var current = self[start]
for (index, element) in indexed().dropFirst() { for (index, element) in indexed().dropFirst() {
if try !belongInSameGroup(current, element) { if try !belongInSameGroup(current, element) {
result.append(self[start..<index]) result.append(self[start..<index])
@@ -489,11 +472,11 @@ extension Collection {
} }
current = element current = element
} }
if start != endIndex { if start != endIndex {
result.append(self[start...]) result.append(self[start...])
} }
return result return result
} }
@@ -501,10 +484,8 @@ extension Collection {
/// grouping elements that project to equal values. /// grouping elements that project to equal values.
/// ///
/// - Parameter projection: A closure that takes an element in the collection /// - Parameter projection: A closure that takes an element in the collection
/// and returns an `Equatable` value that can be used to determine if /// and returns an `Equatable` value that can be used to determine if adjacent
/// adjacent elements belong in the same group. /// elements belong in the same group.
/// - Returns: A collection of subsequences, with every element in each chunk
/// returning the same value for `projection`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable @inlinable
@@ -513,10 +494,10 @@ extension Collection {
) rethrows -> [(Subject, SubSequence)] { ) rethrows -> [(Subject, SubSequence)] {
guard !isEmpty else { return [] } guard !isEmpty else { return [] }
var result: [(Subject, SubSequence)] = [] var result: [(Subject, SubSequence)] = []
var start = startIndex var start = startIndex
var subject = try projection(self[start]) var subject = try projection(self[start])
for (index, element) in indexed().dropFirst() { for (index, element) in indexed().dropFirst() {
let nextSubject = try projection(element) let nextSubject = try projection(element)
if subject != nextSubject { if subject != nextSubject {
@@ -525,11 +506,11 @@ extension Collection {
subject = nextSubject subject = nextSubject
} }
} }
if start != endIndex { if start != endIndex {
result.append((subject, self[start...])) result.append((subject, self[start...]))
} }
return result return result
} }
} }
@@ -551,13 +532,13 @@ extension Collection {
/// `LazyMapCollection` /// `LazyMapCollection`
public struct ChunksOfCountCollection<Base: Collection> { public struct ChunksOfCountCollection<Base: Collection> {
public typealias Element = Base.SubSequence public typealias Element = Base.SubSequence
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let chunkCount: Int internal let chunkCount: Int
@usableFromInline @usableFromInline
internal var endOfFirstChunk: Base.Index internal var endOfFirstChunk: Base.Index
@@ -569,15 +550,13 @@ public struct ChunksOfCountCollection<Base: Collection> {
internal init(_base: Base, _chunkCount: Int) { internal init(_base: Base, _chunkCount: Int) {
self.base = _base self.base = _base
self.chunkCount = _chunkCount self.chunkCount = _chunkCount
// Compute the start index upfront in order to make start index a O(1) // Compute the start index upfront in order to make start index a O(1)
// lookup. // lookup.
self.endOfFirstChunk = self.endOfFirstChunk = _base.index(
_base.index( _base.startIndex, offsetBy: _chunkCount,
_base.startIndex, limitedBy: _base.endIndex
offsetBy: _chunkCount, ) ?? _base.endIndex
limitedBy: _base.endIndex
) ?? _base.endIndex
} }
} }
@@ -585,7 +564,7 @@ extension ChunksOfCountCollection: Collection {
public struct Index { public struct Index {
@usableFromInline @usableFromInline
internal let baseRange: Range<Base.Index> internal let baseRange: Range<Base.Index>
@inlinable @inlinable
internal init(_baseRange: Range<Base.Index>) { internal init(_baseRange: Range<Base.Index>) {
self.baseRange = _baseRange self.baseRange = _baseRange
@@ -597,46 +576,40 @@ extension ChunksOfCountCollection: Collection {
public var startIndex: Index { public var startIndex: Index {
Index(_baseRange: base.startIndex..<endOfFirstChunk) Index(_baseRange: base.startIndex..<endOfFirstChunk)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(_baseRange: base.endIndex..<base.endIndex) Index(_baseRange: base.endIndex..<base.endIndex)
} }
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable
public subscript(i: Index) -> Element { public subscript(i: Index) -> Element {
precondition(i != endIndex, "Index out of range") precondition(i != endIndex, "Index out of range")
return base[i.baseRange] return base[i.baseRange]
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i != endIndex, "Advancing past end index") precondition(i != endIndex, "Advancing past end index")
let baseIdx = let baseIdx = base.index(
base.index( i.baseRange.upperBound, offsetBy: chunkCount,
i.baseRange.upperBound, limitedBy: base.endIndex
offsetBy: chunkCount, ) ?? base.endIndex
limitedBy: base.endIndex
) ?? base.endIndex
return Index(_baseRange: i.baseRange.upperBound..<baseIdx) return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
} }
} }
extension ChunksOfCountCollection.Index: Comparable { extension ChunksOfCountCollection.Index: Comparable {
@inlinable @inlinable
public static func == ( public static func == (lhs: ChunksOfCountCollection.Index,
lhs: ChunksOfCountCollection.Index, rhs: ChunksOfCountCollection.Index) -> Bool {
rhs: ChunksOfCountCollection.Index
) -> Bool {
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
} }
@inlinable @inlinable
public static func < ( public static func < (lhs: ChunksOfCountCollection.Index,
lhs: ChunksOfCountCollection.Index, rhs: ChunksOfCountCollection.Index) -> Bool {
rhs: ChunksOfCountCollection.Index
) -> Bool {
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
} }
} }
@@ -647,7 +620,7 @@ where Base: RandomAccessCollection {
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i != startIndex, "Advancing past start index") precondition(i != startIndex, "Advancing past start index")
var offset = chunkCount var offset = chunkCount
if i.baseRange.lowerBound == base.endIndex { if i.baseRange.lowerBound == base.endIndex {
let remainder = base.count % chunkCount let remainder = base.count % chunkCount
@@ -655,13 +628,11 @@ where Base: RandomAccessCollection {
offset = remainder offset = remainder
} }
} }
let baseIdx = let baseIdx = base.index(
base.index( i.baseRange.lowerBound, offsetBy: -offset,
i.baseRange.lowerBound, limitedBy: base.startIndex
offsetBy: -offset, ) ?? base.startIndex
limitedBy: base.startIndex
) ?? base.startIndex
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound) return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
} }
} }
@@ -670,11 +641,10 @@ extension ChunksOfCountCollection {
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
let distance = let distance =
base base.distance(from: start.baseRange.lowerBound,
.distance(from: start.baseRange.lowerBound, to: end.baseRange.lowerBound) to: end.baseRange.lowerBound)
let (quotient, remainder) = let (quotient, remainder) =
distance distance.quotientAndRemainder(dividingBy: chunkCount)
.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum() return quotient + remainder.signum()
} }
@@ -684,16 +654,14 @@ extension ChunksOfCountCollection {
base.count.quotientAndRemainder(dividingBy: chunkCount) base.count.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum() return quotient + remainder.signum()
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index, offsetBy offset: Int, limitedBy limit: Index
offsetBy offset: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
guard offset != 0 else { return i } guard offset != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
if offset > 0 { if offset > 0 {
return limit > i return limit > i
? offsetForward(i, offsetBy: offset, limit: limit) ? offsetForward(i, offsetBy: offset, limit: limit)
@@ -708,40 +676,33 @@ extension ChunksOfCountCollection {
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
let idx = let idx = distance > 0
distance > 0 ? offsetForward(i, offsetBy: distance)
? offsetForward(i, offsetBy: distance) : offsetBackward(i, offsetBy: distance)
: offsetBackward(i, offsetBy: distance)
guard let index = idx else { guard let index = idx else {
fatalError("Out of bounds") fatalError("Out of bounds")
} }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index, offsetBy distance: Int, limit: Index? = nil
offsetBy distance: Int,
limit: Index? = nil
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
return makeOffsetIndex( return makeOffsetIndex(
from: i, from: i, baseBound: base.endIndex,
baseBound: base.endIndex, distance: distance, baseDistance: distance * chunkCount,
distance: distance, limit: limit, by: >
baseDistance: distance * chunkCount,
limit: limit,
by: >
) )
} }
// Convenience to compute offset backward base distance. // Convenience to compute offset backward base distance.
@inlinable @inlinable
internal func computeOffsetBackwardBaseDistance( internal func computeOffsetBackwardBaseDistance(
_ i: Index, _ i: Index, _ distance: Int
_ distance: Int
) -> Int { ) -> Int {
if i == endIndex { if i == endIndex {
let remainder = base.count % chunkCount let remainder = base.count % chunkCount
@@ -755,41 +716,32 @@ extension ChunksOfCountCollection {
} }
return distance * chunkCount return distance * chunkCount
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index, offsetBy distance: Int, limit: Index? = nil
offsetBy distance: Int,
limit: Index? = nil
) -> Index? { ) -> Index? {
assert(distance < 0) assert(distance < 0)
let baseDistance = computeOffsetBackwardBaseDistance(i, distance) let baseDistance =
computeOffsetBackwardBaseDistance(i, distance)
return makeOffsetIndex( return makeOffsetIndex(
from: i, from: i, baseBound: base.startIndex,
baseBound: base.startIndex, distance: distance, baseDistance: baseDistance,
distance: distance, limit: limit, by: <
baseDistance: baseDistance,
limit: limit,
by: <
) )
} }
// Helper to compute `index(offsetBy:)` index. // Helper to compute `index(offsetBy:)` index.
@inlinable @inlinable
internal func makeOffsetIndex( internal func makeOffsetIndex(
from i: Index, from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
baseBound: Base.Index, limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
distance: Int,
baseDistance: Int,
limit: Index?,
by limitFn: (Base.Index, Base.Index) -> Bool
) -> Index? { ) -> Index? {
let baseIdx = base.index( let baseIdx = base.index(
i.baseRange.lowerBound, i.baseRange.lowerBound, offsetBy: baseDistance,
offsetBy: baseDistance,
limitedBy: baseBound limitedBy: baseBound
) )
if let limit = limit { if let limit = limit {
if baseIdx == nil { if baseIdx == nil {
// If we passed the bounds while advancing forward, and the limit is the // If we passed the bounds while advancing forward, and the limit is the
@@ -814,16 +766,12 @@ extension ChunksOfCountCollection {
return nil return nil
} }
} }
let baseStartIdx = baseIdx ?? baseBound let baseStartIdx = baseIdx ?? baseBound
let baseEndIdx = let baseEndIdx = base.index(
base.index( baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
baseStartIdx, ) ?? base.endIndex
offsetBy: chunkCount,
limitedBy: base.endIndex
)
?? base.endIndex
return Index(_baseRange: baseStartIdx..<baseEndIdx) return Index(_baseRange: baseStartIdx..<baseEndIdx)
} }
} }
@@ -870,10 +818,10 @@ extension Collection {
extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {} extension ChunksOfCountCollection.Index: Hashable where Base.Index: Hashable {}
extension ChunksOfCountCollection: LazySequenceProtocol extension ChunksOfCountCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension ChunksOfCountCollection: LazyCollectionProtocol extension ChunksOfCountCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {} where Base: LazyCollectionProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// evenlyChunked(in:) // evenlyChunked(in:)
@@ -920,10 +868,7 @@ extension Collection {
@inlinable @inlinable
public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> { public func evenlyChunked(in count: Int) -> EvenlyChunkedCollection<Self> {
precondition(count >= 0, "Can't divide into a negative number of chunks") precondition(count >= 0, "Can't divide into a negative number of chunks")
precondition( precondition(count > 0 || isEmpty, "Can't divide a non-empty collection into 0 chunks")
count > 0 || isEmpty,
"Can't divide a non-empty collection into 0 chunks"
)
return EvenlyChunkedCollection(base: self, numberOfChunks: count) return EvenlyChunkedCollection(base: self, numberOfChunks: count)
} }
} }
+28 -36
View File
@@ -14,17 +14,17 @@ public struct CombinationsSequence<Base: Collection> {
/// The collection to iterate over for combinations. /// The collection to iterate over for combinations.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let baseCount: Int internal let baseCount: Int
/// The range of accepted sizes of combinations. /// The range of accepted sizes of combinations.
/// ///
/// - Note: This may be `nil` if the attempted range entirely exceeds the /// - Note: This may be `nil` if the attempted range entirely exceeds the
/// upper bounds of the size of the `base` collection. /// upper bounds of the size of the `base` collection.
@usableFromInline @usableFromInline
internal let kRange: Range<Int>? internal let kRange: Range<Int>?
/// Initializes a `CombinationsSequence` for all combinations of `base` of /// Initializes a `CombinationsSequence` for all combinations of `base` of
/// size `k`. /// size `k`.
/// ///
@@ -35,7 +35,7 @@ public struct CombinationsSequence<Base: Collection> {
internal init(_ base: Base, k: Int) { internal init(_ base: Base, k: Int) {
self.init(base, kRange: k...k) self.init(base, kRange: k...k)
} }
/// Initializes a `CombinationsSequence` for all combinations of `base` of /// Initializes a `CombinationsSequence` for all combinations of `base` of
/// sizes within a given range. /// sizes within a given range.
/// ///
@@ -44,29 +44,27 @@ public struct CombinationsSequence<Base: Collection> {
/// - kRange: The range of accepted sizes of combinations. /// - kRange: The range of accepted sizes of combinations.
@inlinable @inlinable
internal init<R: RangeExpression>( internal init<R: RangeExpression>(
_ base: Base, _ base: Base, kRange: R
kRange: R
) where R.Bound == Int { ) where R.Bound == Int {
let range = kRange.relative(to: 0 ..< .max) let range = kRange.relative(to: 0 ..< .max)
self.base = base self.base = base
let baseCount = base.count let baseCount = base.count
self.baseCount = baseCount self.baseCount = baseCount
let upperBound = baseCount + 1 let upperBound = baseCount + 1
self.kRange = self.kRange = range.lowerBound < upperBound
range.lowerBound < upperBound ? range.clamped(to: 0 ..< upperBound)
? range.clamped(to: 0..<upperBound)
: nil : nil
} }
/// The total number of combinations. /// The total number of combinations.
@inlinable @inlinable
public var count: Int { public var count: Int {
guard let k = self.kRange else { return 0 } guard let k = self.kRange else { return 0 }
let n = baseCount let n = baseCount
if k == 0..<(n + 1) { if k == 0 ..< (n + 1) {
return 1 << n return 1 << n
} }
func binomial(n: Int, k: Int) -> Int { func binomial(n: Int, k: Int) -> Int {
switch k { switch k {
case n, 0: return 1 case n, 0: return 1
@@ -75,7 +73,7 @@ public struct CombinationsSequence<Base: Collection> {
default: return n * binomial(n: n - 1, k: k - 1) / k default: return n * binomial(n: n - 1, k: k - 1) / k
} }
} }
return k.map { return k.map {
binomial(n: n, k: $0) binomial(n: n, k: $0)
}.reduce(0, +) }.reduce(0, +)
@@ -91,7 +89,7 @@ extension CombinationsSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
/// The current range of accepted sizes of combinations. /// The current range of accepted sizes of combinations.
/// ///
/// - Note: The range is contracted until empty while iterating over /// - Note: The range is contracted until empty while iterating over
@@ -99,23 +97,23 @@ extension CombinationsSequence: Sequence {
/// finished. /// finished.
@usableFromInline @usableFromInline
internal var kRange: Range<Int> internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty). /// Whether or not iteration is finished (`kRange` is empty)
@inlinable @inlinable
internal var isFinished: Bool { internal var isFinished: Bool {
kRange.isEmpty return kRange.isEmpty
} }
@usableFromInline @usableFromInline
internal var indexes: [Base.Index] internal var indexes: [Base.Index]
@inlinable @inlinable
internal init(_ combinations: CombinationsSequence) { internal init(_ combinations: CombinationsSequence) {
self.base = combinations.base self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0 self.kRange = combinations.kRange ?? 0..<0
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound)) self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
} }
/// Advances the current indices to the next set of combinations. If /// Advances the current indices to the next set of combinations. If
/// `indexes.count == 3` and `base.count == 5`, the indices advance like /// `indexes.count == 3` and `base.count == 5`, the indices advance like
/// this: /// this:
@@ -141,12 +139,12 @@ extension CombinationsSequence: Sequence {
func advanceKRange() { func advanceKRange() {
if kRange.lowerBound < kRange.upperBound { if kRange.lowerBound < kRange.upperBound {
let advancedLowerBound = kRange.lowerBound + 1 let advancedLowerBound = kRange.lowerBound + 1
kRange = advancedLowerBound..<kRange.upperBound kRange = advancedLowerBound ..< kRange.upperBound
indexes.removeAll(keepingCapacity: true) indexes.removeAll(keepingCapacity: true)
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound)) indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
} }
} }
guard !indexes.isEmpty else { guard !indexes.isEmpty else {
// Initial state for combinations of 0 elements is an empty array with // Initial state for combinations of 0 elements is an empty array with
// `finished == false`. Even though no indexes are involved, advancing // `finished == false`. Even though no indexes are involved, advancing
@@ -154,11 +152,11 @@ extension CombinationsSequence: Sequence {
advanceKRange() advanceKRange()
return return
} }
let i = indexes.count - 1 let i = indexes.count - 1
base.formIndex(after: &indexes[i]) base.formIndex(after: &indexes[i])
if indexes[i] != base.endIndex { return } if indexes[i] != base.endIndex { return }
var j = i var j = i
while indexes[i] == base.endIndex { while indexes[i] == base.endIndex {
j -= 1 j -= 1
@@ -167,7 +165,7 @@ extension CombinationsSequence: Sequence {
advanceKRange() advanceKRange()
return return
} }
base.formIndex(after: &indexes[j]) base.formIndex(after: &indexes[j])
for k in indexes.indices[(j + 1)...] { for k in indexes.indices[(j + 1)...] {
indexes[k] = base.index(after: indexes[k - 1]) indexes[k] = base.index(after: indexes[k - 1])
@@ -177,7 +175,7 @@ extension CombinationsSequence: Sequence {
} }
} }
} }
@inlinable @inlinable
public mutating func next() -> [Base.Element]? { public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil } guard !isFinished else { return nil }
@@ -185,7 +183,7 @@ extension CombinationsSequence: Sequence {
return indexes.map { i in base[i] } return indexes.map { i in base[i] }
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(self) Iterator(self)
@@ -193,7 +191,7 @@ extension CombinationsSequence: Sequence {
} }
extension CombinationsSequence: LazySequenceProtocol extension CombinationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// combinations(ofCount:) // combinations(ofCount:)
@@ -257,8 +255,6 @@ extension Collection {
/// ///
/// - Parameter kRange: The range of numbers of elements to include in each /// - Parameter kRange: The range of numbers of elements to include in each
/// combination. /// combination.
/// - Returns: A sequence of the combinations of this collection's
/// elements, for all sizes in `kRange`, from smallest to largest.
/// ///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since /// is the number of elements in the base collection, since
@@ -269,7 +265,7 @@ extension Collection {
) -> CombinationsSequence<Self> where R.Bound == Int { ) -> CombinationsSequence<Self> where R.Bound == Int {
CombinationsSequence(self, kRange: kRange) CombinationsSequence(self, kRange: kRange)
} }
/// Returns a collection of combinations of this collection's elements, with /// Returns a collection of combinations of this collection's elements, with
/// each combination having the specified number of elements. /// each combination having the specified number of elements.
/// ///
@@ -295,17 +291,13 @@ extension Collection {
/// the resulting sequence has no elements. /// the resulting sequence has no elements.
/// ///
/// - Parameter k: The number of elements to include in each combination. /// - Parameter k: The number of elements to include in each combination.
/// - Returns: A sequence of the combinations of this collection's
/// elements.
/// ///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since /// is the number of elements in the base collection, since
/// `CombinationsSequence` accesses the `count` of the base collection. /// `CombinationsSequence` accesses the `count` of the base collection.
@inlinable @inlinable
public func combinations(ofCount k: Int) -> CombinationsSequence<Self> { public func combinations(ofCount k: Int) -> CombinationsSequence<Self> {
precondition( precondition(k >= 0, "Can't have combinations with a negative number of elements.")
k >= 0,
"Can't have combinations with a negative number of elements.")
return CombinationsSequence(self, k: k) return CombinationsSequence(self, k: k)
} }
} }
+29 -33
View File
@@ -12,11 +12,11 @@
/// A `Sequence` that iterates over every non-nil element from the original /// A `Sequence` that iterates over every non-nil element from the original
/// `Sequence`. /// `Sequence`.
public struct CompactedSequence<Base: Sequence, Element>: Sequence public struct CompactedSequence<Base: Sequence, Element>: Sequence
where Base.Element == Element? { where Base.Element == Element? {
@usableFromInline @usableFromInline
let base: Base let base: Base
@inlinable @inlinable
init(base: Base) { init(base: Base) {
self.base = base self.base = base
@@ -25,12 +25,12 @@ where Base.Element == Element? {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
var base: Base.Iterator var base: Base.Iterator
@inlinable @inlinable
init(base: Base.Iterator) { init(base: Base.Iterator) {
self.base = base self.base = base
} }
@inlinable @inlinable
public mutating func next() -> Element? { public mutating func next() -> Element? {
while let wrapped = base.next() { while let wrapped = base.next() {
@@ -68,7 +68,7 @@ extension Sequence {
/// Complexity: O(1) /// Complexity: O(1)
@inlinable @inlinable
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped> public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == Unwrapped? { where Element == Unwrapped? {
CompactedSequence(base: self) CompactedSequence(base: self)
} }
} }
@@ -76,79 +76,74 @@ extension Sequence {
/// A `Collection` that iterates over every non-nil element from the original /// A `Collection` that iterates over every non-nil element from the original
/// `Collection`. /// `Collection`.
public struct CompactedCollection<Base: Collection, Element>: Collection public struct CompactedCollection<Base: Collection, Element>: Collection
where Base.Element == Element? { where Base.Element == Element? {
@usableFromInline @usableFromInline
let base: Base let base: Base
@inlinable @inlinable
init(base: Base) { init(base: Base) {
self.base = base self.base = base
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
self.startIndex = Index(base: idx) self.startIndex = Index(base: idx)
} }
public struct Index { public struct Index {
@usableFromInline @usableFromInline
let base: Base.Index let base: Base.Index
@inlinable @inlinable
init(base: Base.Index) { init(base: Base.Index) {
self.base = base self.base = base
} }
} }
public var startIndex: Index public var startIndex: Index
@inlinable @inlinable
public var endIndex: Index { Index(base: base.endIndex) } public var endIndex: Index { Index(base: base.endIndex) }
@inlinable @inlinable
public subscript(position: Index) -> Element { public subscript(position: Index) -> Element {
// swift-format-ignore: NeverForceUnwrap
// All indices are only for non-`nil` elements.
base[position.base]! base[position.base]!
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i != endIndex, "Index out of bounds") precondition(i != endIndex, "Index out of bounds")
let baseIdx = base.index(after: i.base) let baseIdx = base.index(after: i.base)
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil }) guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
else { return endIndex } else { return endIndex }
return Index(base: idx) return Index(base: idx)
} }
} }
extension CompactedCollection: BidirectionalCollection extension CompactedCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection {
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i != startIndex, "Index out of bounds") precondition(i != startIndex, "Index out of bounds")
guard guard let idx =
let idx = base[startIndex.base..<i.base]
base[startIndex.base..<i.base] .lastIndex(where: { $0 != nil })
.lastIndex(where: { $0 != nil }) else { fatalError("Index out of bounds") }
else { fatalError("Index out of bounds") }
return Index(base: idx) return Index(base: idx)
} }
} }
extension CompactedCollection.Index: Comparable { extension CompactedCollection.Index: Comparable {
@inlinable @inlinable
public static func < ( public static func < (lhs: CompactedCollection.Index,
lhs: CompactedCollection.Index, rhs: CompactedCollection.Index) -> Bool {
rhs: CompactedCollection.Index
) -> Bool {
lhs.base < rhs.base lhs.base < rhs.base
} }
} }
extension CompactedCollection.Index: Hashable extension CompactedCollection.Index: Hashable
where Base.Index: Hashable {} where Base.Index: Hashable {}
extension Collection { extension Collection {
/// Returns a new `Collection` that iterates over every non-nil element from /// Returns a new `Collection` that iterates over every non-nil element from
@@ -172,7 +167,8 @@ extension Collection {
/// original `Collection`. /// original `Collection`.
@inlinable @inlinable
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped> public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped? { where Element == Unwrapped?
{
CompactedCollection(base: self) CompactedCollection(base: self)
} }
} }
@@ -182,7 +178,7 @@ extension Collection {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension CompactedSequence: LazySequenceProtocol extension CompactedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol extension CompactedCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
+16 -17
View File
@@ -14,7 +14,7 @@ public struct CycledSequence<Base: Collection> {
/// The collection to repeat. /// The collection to repeat.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@inlinable @inlinable
internal init(base: Base) { internal init(base: Base) {
self.base = base self.base = base
@@ -26,29 +26,29 @@ extension CycledSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal var current: Base.Index internal var current: Base.Index
@inlinable @inlinable
internal init(base: Base) { internal init(base: Base) {
self.base = base self.base = base
self.current = base.startIndex self.current = base.startIndex
} }
@inlinable @inlinable
public mutating func next() -> Base.Element? { public mutating func next() -> Base.Element? {
guard !base.isEmpty else { return nil } guard !base.isEmpty else { return nil }
if current == base.endIndex { if current == base.endIndex {
current = base.startIndex current = base.startIndex
} }
defer { base.formIndex(after: &current) } defer { base.formIndex(after: &current) }
return base[current] return base[current]
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(base: base) Iterator(base: base)
@@ -56,7 +56,7 @@ extension CycledSequence: Sequence {
} }
extension CycledSequence: LazySequenceProtocol extension CycledSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
/// A collection wrapper that repeats the elements of a base collection for a /// A collection wrapper that repeats the elements of a base collection for a
/// finite number of times. /// finite number of times.
@@ -134,11 +134,10 @@ extension CycledTimesCollection: Collection {
offsetBy distance: Int, offsetBy distance: Int,
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
guard guard let productIndex = product.index(
let productIndex = product.index( i.productIndex,
i.productIndex, offsetBy: distance,
offsetBy: distance, limitedBy: limit.productIndex)
limitedBy: limit.productIndex)
else { return nil } else { return nil }
return Index(productIndex) return Index(productIndex)
} }
@@ -150,7 +149,7 @@ extension CycledTimesCollection: Collection {
} }
extension CycledTimesCollection: BidirectionalCollection extension CycledTimesCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection {
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
let productIndex = product.index(before: i.productIndex) let productIndex = product.index(before: i.productIndex)
@@ -159,10 +158,10 @@ where Base: BidirectionalCollection {
} }
extension CycledTimesCollection: RandomAccessCollection extension CycledTimesCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol extension CycledTimesCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// cycled() // cycled()
@@ -198,7 +197,7 @@ extension Collection {
public func cycled() -> CycledSequence<Self> { public func cycled() -> CycledSequence<Self> {
CycledSequence(base: self) CycledSequence(base: self)
} }
/// Returns a sequence that repeats the elements of this collection the /// Returns a sequence that repeats the elements of this collection the
/// specified number of times. /// specified number of times.
/// ///
+27 -24
View File
@@ -24,9 +24,9 @@ extension Either: Equatable where Left: Equatable, Right: Equatable {
@usableFromInline @usableFromInline
internal static func == (lhs: Self, rhs: Self) -> Bool { internal static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (.left(let lhs), .left(let rhs)): case let (.left(lhs), .left(rhs)):
return lhs == rhs return lhs == rhs
case (.right(let lhs), .right(let rhs)): case let (.right(lhs), .right(rhs)):
return lhs == rhs return lhs == rhs
case (.left, .right), (.right, .left): case (.left, .right), (.right, .left):
return false return false
@@ -38,9 +38,9 @@ extension Either: Comparable where Left: Comparable, Right: Comparable {
@usableFromInline @usableFromInline
internal static func < (lhs: Self, rhs: Self) -> Bool { internal static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (.left(let lhs), .left(let rhs)): case let (.left(lhs), .left(rhs)):
return lhs < rhs return lhs < rhs
case (.right(let lhs), .right(let rhs)): case let (.right(lhs), .right(rhs)):
return lhs < rhs return lhs < rhs
case (.left, .right): case (.left, .right):
return true return true
@@ -57,7 +57,8 @@ extension Either: Comparable where Left: Comparable, Right: Comparable {
/// A sequence that has one of the two specified types. /// A sequence that has one of the two specified types.
@usableFromInline @usableFromInline
internal enum EitherSequence<Left: Sequence, Right: Sequence> internal enum EitherSequence<Left: Sequence, Right: Sequence>
where Left.Element == Right.Element { where Left.Element == Right.Element
{
case left(Left) case left(Left)
case right(Right) case right(Right)
} }
@@ -67,16 +68,16 @@ extension EitherSequence: Sequence {
internal struct Iterator: IteratorProtocol { internal struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var left: Left.Iterator? internal var left: Left.Iterator?
@usableFromInline @usableFromInline
internal var right: Right.Iterator? internal var right: Right.Iterator?
@inlinable @inlinable
internal mutating func next() -> Left.Element? { internal mutating func next() -> Left.Element? {
left?.next() ?? right?.next() left?.next() ?? right?.next()
} }
} }
@usableFromInline @usableFromInline
internal func makeIterator() -> Iterator { internal func makeIterator() -> Iterator {
switch self { switch self {
@@ -89,7 +90,8 @@ extension EitherSequence: Sequence {
} }
extension EitherSequence: Collection extension EitherSequence: Collection
where Left: Collection, Right: Collection, Left.Element == Right.Element { where Left: Collection, Right: Collection, Left.Element == Right.Element
{
@usableFromInline @usableFromInline
internal typealias Index = Either<Left.Index, Right.Index> internal typealias Index = Either<Left.Index, Right.Index>
@@ -116,9 +118,9 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
@inlinable @inlinable
internal subscript(position: Index) -> Element { internal subscript(position: Index) -> Element {
switch (self, position) { switch (self, position) {
case (.left(let s), .left(let i)): case let (.left(s), .left(i)):
return s[i] return s[i]
case (.right(let s), .right(let i)): case let (.right(s), .right(i)):
return s[i] return s[i]
default: default:
fatalError() fatalError()
@@ -127,10 +129,10 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
@inlinable @inlinable
internal func index(after i: Index) -> Index { internal func index(after i: Index) -> Index {
switch (self, i) { switch (self,i) {
case (.left(let s), .left(let i)): case let (.left(s), .left(i)):
return .left(s.index(after: i)) return .left(s.index(after: i))
case (.right(let s), .right(let i)): case let (.right(s), .right(i)):
return .right(s.index(after: i)) return .right(s.index(after: i))
default: default:
fatalError() fatalError()
@@ -144,9 +146,9 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
switch (self, i, limit) { switch (self, i, limit) {
case (.left(let s), .left(let i), .left(let limit)): case let (.left(s), .left(i), .left(limit)):
return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) } return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }
case (.right(let s), .right(let i), .right(let limit)): case let (.right(s), .right(i), .right(limit)):
return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) } return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }
default: default:
fatalError() fatalError()
@@ -156,9 +158,9 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
@inlinable @inlinable
internal func index(_ i: Index, offsetBy distance: Int) -> Index { internal func index(_ i: Index, offsetBy distance: Int) -> Index {
switch (self, i) { switch (self, i) {
case (.left(let s), .left(let i)): case let (.left(s), .left(i)):
return .left(s.index(i, offsetBy: distance)) return .left(s.index(i, offsetBy: distance))
case (.right(let s), .right(let i)): case let (.right(s), .right(i)):
return .right(s.index(i, offsetBy: distance)) return .right(s.index(i, offsetBy: distance))
default: default:
fatalError() fatalError()
@@ -168,9 +170,9 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
@inlinable @inlinable
internal func distance(from start: Index, to end: Index) -> Int { internal func distance(from start: Index, to end: Index) -> Int {
switch (self, start, end) { switch (self, start, end) {
case (.left(let s), .left(let i), .left(let j)): case let (.left(s), .left(i), .left(j)):
return s.distance(from: i, to: j) return s.distance(from: i, to: j)
case (.right(let s), .right(let i), .right(let j)): case let (.right(s), .right(i), .right(j)):
return s.distance(from: i, to: j) return s.distance(from: i, to: j)
default: default:
fatalError() fatalError()
@@ -179,13 +181,14 @@ where Left: Collection, Right: Collection, Left.Element == Right.Element {
} }
extension EitherSequence: BidirectionalCollection extension EitherSequence: BidirectionalCollection
where Left: BidirectionalCollection, Right: BidirectionalCollection { where Left: BidirectionalCollection, Right: BidirectionalCollection
{
@inlinable @inlinable
internal func index(before i: Index) -> Index { internal func index(before i: Index) -> Index {
switch (self, i) { switch (self, i) {
case (.left(let s), .left(let i)): case let (.left(s), .left(i)):
return .left(s.index(before: i)) return .left(s.index(before: i))
case (.right(let s), .right(let i)): case let (.right(s), .right(i)):
return .right(s.index(before: i)) return .right(s.index(before: i))
default: default:
fatalError() fatalError()
@@ -194,4 +197,4 @@ where Left: BidirectionalCollection, Right: BidirectionalCollection {
} }
extension EitherSequence: RandomAccessCollection extension EitherSequence: RandomAccessCollection
where Left: RandomAccessCollection, Right: RandomAccessCollection {} where Left: RandomAccessCollection, Right: RandomAccessCollection {}
-83
View File
@@ -1,83 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// EndsWith
//===----------------------------------------------------------------------===//
extension BidirectionalCollection where Element: Equatable {
/// Returns a Boolean value indicating whether the final elements of the
/// collection are the same as the elements in another collection.
///
/// This example tests whether one countable range ends with the elements
/// of another countable range.
///
/// let a = 8...10
/// let b = 1...10
///
/// print(b.ends(with: a))
/// // Prints "true"
///
/// Passing a collection with no elements or an empty collection as
/// `possibleSuffix` always results in `true`.
///
/// print(b.ends(with: []))
/// // Prints "true"
///
/// - Parameter possibleSuffix: A collection to compare to this collection.
/// - Returns: `true` if the initial elements of the collection are the same as
/// the elements of `possibleSuffix`; otherwise, `false`. If
/// `possibleSuffix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// collection and the length of `possibleSuffix`.
@inlinable
public func ends<PossibleSuffix: BidirectionalCollection>(
with possibleSuffix: PossibleSuffix
) -> Bool where PossibleSuffix.Element == Element {
self.ends(with: possibleSuffix, by: ==)
}
}
extension BidirectionalCollection {
/// Returns a Boolean value indicating whether the final elements of the
/// collection are equivalent to the elements in another collection, using
/// the given predicate as the equivalence test.
///
/// The predicate must be an *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - possibleSuffix: A collection to compare to this collection.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if the initial elements of the collection are equivalent
/// to the elements of `possibleSuffix`; otherwise, `false`. If
/// `possibleSuffix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// collection and the length of `possibleSuffix`.
@inlinable
public func ends<PossibleSuffix: BidirectionalCollection>(
with possibleSuffix: PossibleSuffix,
by areEquivalent: (Element, PossibleSuffix.Element) throws -> Bool
) rethrows -> Bool {
try self
.reversed()
.starts(with: possibleSuffix.reversed(), by: areEquivalent)
}
}
+88 -109
View File
@@ -13,13 +13,14 @@
/// collections. /// collections.
@usableFromInline @usableFromInline
internal struct FlattenCollection<Base: Collection> internal struct FlattenCollection<Base: Collection>
where Base.Element: Collection { where Base.Element: Collection
{
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let indexOfFirstNonEmptyElement: Base.Index internal let indexOfFirstNonEmptyElement: Base.Index
@inlinable @inlinable
internal init(base: Base) { internal init(base: Base) {
self.base = base self.base = base
@@ -32,39 +33,35 @@ extension FlattenCollection: Collection {
internal struct Index: Comparable { internal struct Index: Comparable {
@usableFromInline @usableFromInline
internal let outer: Base.Index internal let outer: Base.Index
@usableFromInline @usableFromInline
internal let inner: Base.Element.Index? internal let inner: Base.Element.Index?
@inlinable @inlinable
init(outer: Base.Index, inner: Base.Element.Index?) { init(outer: Base.Index, inner: Base.Element.Index?) {
self.outer = outer self.outer = outer
self.inner = inner self.inner = inner
} }
@inlinable @inlinable
internal static func < (lhs: Self, rhs: Self) -> Bool { internal static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer } guard lhs.outer == rhs.outer else { return lhs.outer < rhs.outer }
// swift-format-ignore: NeverForceUnwrap
// `inner` is nil iff `outer` is `base.endIndex`, and the
// previous line established that the two outer indices are equal.
// Thus, either both inner indices are nil or neither are.
return lhs.inner == nil ? false : lhs.inner! < rhs.inner! return lhs.inner == nil ? false : lhs.inner! < rhs.inner!
} }
} }
@inlinable @inlinable
internal var startIndex: Index { internal var startIndex: Index {
let outer = indexOfFirstNonEmptyElement let outer = indexOfFirstNonEmptyElement
let inner = outer == base.endIndex ? nil : base[outer].startIndex let inner = outer == base.endIndex ? nil : base[outer].startIndex
return Index(outer: outer, inner: inner) return Index(outer: outer, inner: inner)
} }
@inlinable @inlinable
internal var endIndex: Index { internal var endIndex: Index {
Index(outer: base.endIndex, inner: nil) Index(outer: base.endIndex, inner: nil)
} }
/// Forms an index from a pair of base indices, normalizing /// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if /// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary. /// necessary.
@@ -73,64 +70,56 @@ extension FlattenCollection: Collection {
outer: Base.Index, outer: Base.Index,
inner: Base.Element.Index inner: Base.Element.Index
) -> Index { ) -> Index {
guard inner == base[outer].endIndex else { if inner == base[outer].endIndex {
let outer = base[base.index(after: outer)...]
.endOfPrefix(while: { $0.isEmpty })
let inner = outer == base.endIndex ? nil : base[outer].startIndex
return Index(outer: outer, inner: inner)
} else {
return Index(outer: outer, inner: inner) return Index(outer: outer, inner: inner)
} }
let outer = base[base.index(after: outer)...]
.endOfPrefix(while: { $0.isEmpty })
let inner = outer == base.endIndex ? nil : base[outer].startIndex
return Index(outer: outer, inner: inner)
} }
@inlinable @inlinable
internal func index(after index: Index) -> Index { internal func index(after index: Index) -> Index {
let element = base[index.outer] let element = base[index.outer]
// swift-format-ignore: NeverForceUnwrap
// This unwrap, like the unchecked subscript above, enforces the
// precondition that you can't advance past `endIndex`.
let nextInner = element.index(after: index.inner!) let nextInner = element.index(after: index.inner!)
return normalizeIndex(outer: index.outer, inner: nextInner) return normalizeIndex(outer: index.outer, inner: nextInner)
} }
@inlinable @inlinable
internal subscript(position: Index) -> Base.Element.Element { internal subscript(position: Index) -> Base.Element.Element {
// swift-format-ignore: NeverForceUnwrap
// This unwrap, along with the unchecked subscript, enforces the
// precondition that you can't subscript at `endIndex`.
base[position.outer][position.inner!] base[position.outer][position.inner!]
} }
@inlinable @inlinable
internal func distance(from start: Index, to end: Index) -> Int { internal func distance(from start: Index, to end: Index) -> Int {
guard start.outer <= end.outer guard start.outer <= end.outer
else { return -distance(from: end, to: start) } else { return -distance(from: end, to: start) }
guard let startInner = start.inner guard let startInner = start.inner
else { return 0 } else { return 0 }
guard start.outer != end.outer guard start.outer != end.outer
else { else {
// swift-format-ignore: NeverForceUnwrap return base[start.outer].distance(from: startInner, to: end.inner!)
// Established via guards that outer indices are equal and `start.inner` }
// is non-nil, so `end.inner` must also be non-`nil`.
return base[start.outer].distance(from: startInner, to: end.inner!)
}
let firstPart = base[start.outer][startInner...].count let firstPart = base[start.outer][startInner...].count
let middlePart = base[start.outer..<end.outer].dropFirst() let middlePart = base[start.outer..<end.outer].dropFirst()
.reduce(0, { $0 + $1.count }) .reduce(0, { $0 + $1.count })
let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0 let lastPart = end.inner.map { base[end.outer][..<$0].count } ?? 0
return firstPart + middlePart + lastPart return firstPart + middlePart + lastPart
} }
@inlinable @inlinable
internal func index(_ index: Index, offsetBy distance: Int) -> Index { internal func index(_ index: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return index } guard distance != 0 else { return index }
return distance > 0 return distance > 0
? offsetForward(index, by: distance) ? offsetForward(index, by: distance)
: offsetBackward(index, by: -distance) : offsetBackward(index, by: -distance)
} }
@inlinable @inlinable
internal func index( internal func index(
_ index: Index, _ index: Index,
@@ -138,7 +127,7 @@ extension FlattenCollection: Collection {
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
guard distance != 0 else { return index } guard distance != 0 else { return index }
if distance > 0 { if distance > 0 {
return limit >= index return limit >= index
? offsetForward(index, by: distance, limitedBy: limit) ? offsetForward(index, by: distance, limitedBy: limit)
@@ -149,139 +138,133 @@ extension FlattenCollection: Collection {
: offsetBackward(index, by: -distance) : offsetBackward(index, by: -distance)
} }
} }
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit >= index) assert(limit >= index)
if index.outer == limit.outer { if index.outer == limit.outer {
guard let indexInner = index.inner, let limitInner = limit.inner else { if let indexInner = index.inner, let limitInner = limit.inner {
return base[index.outer]
.index(indexInner, offsetBy: distance, limitedBy: limitInner)
.map { inner in Index(outer: index.outer, inner: inner) }
} else {
// `index` and `limit` are both `endIndex` // `index` and `limit` are both `endIndex`
return nil return nil
} }
return base[index.outer]
.index(indexInner, offsetBy: distance, limitedBy: limitInner)
.map { inner in Index(outer: index.outer, inner: inner) }
} }
// swift-format-ignore: NeverForceUnwrap
// `index <= limit` and `index.outer != limit.outer`, so `index != endIndex` // `index <= limit` and `index.outer != limit.outer`, so `index != endIndex`
let indexInner = index.inner! let indexInner = index.inner!
let element = base[index.outer] let element = base[index.outer]
if let inner = element.index( if let inner = element.index(
indexInner, indexInner,
offsetBy: distance, offsetBy: distance,
limitedBy: element.endIndex limitedBy: element.endIndex
) { ) {
return normalizeIndex(outer: index.outer, inner: inner) return normalizeIndex(outer: index.outer, inner: inner)
} }
var remainder = distance - element[indexInner...].count var remainder = distance - element[indexInner...].count
var outer = base.index(after: index.outer) var outer = base.index(after: index.outer)
while outer != limit.outer { while outer != limit.outer {
let element = base[outer] let element = base[outer]
if let inner = element.index( if let inner = element.index(
element.startIndex, element.startIndex,
offsetBy: remainder, offsetBy: remainder,
limitedBy: element.endIndex limitedBy: element.endIndex
) { ) {
return normalizeIndex(outer: outer, inner: inner) return normalizeIndex(outer: outer, inner: inner)
} }
remainder -= element.count remainder -= element.count
base.formIndex(after: &outer) base.formIndex(after: &outer)
} }
if let limitInner = limit.inner { if let limitInner = limit.inner {
let element = base[outer] let element = base[outer]
return element.index( return element.index(
element.startIndex, element.startIndex,
offsetBy: remainder, offsetBy: remainder,
limitedBy: limitInner limitedBy: limitInner)
) .map { inner in Index(outer: outer, inner: inner) }
.map { inner in Index(outer: outer, inner: inner) } } else {
return nil
} }
return nil
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit <= index) assert(limit <= index)
if index.outer == limit.outer { if index.outer == limit.outer {
guard let indexInner = index.inner, let limitInner = limit.inner else { if let indexInner = index.inner, let limitInner = limit.inner {
return base[index.outer]
.index(indexInner, offsetBy: -distance, limitedBy: limitInner)
.map { inner in Index(outer: index.outer, inner: inner) }
} else {
// `index` and `limit` are both `endIndex` // `index` and `limit` are both `endIndex`
return nil return nil
} }
return base[index.outer]
.index(indexInner, offsetBy: -distance, limitedBy: limitInner)
.map { inner in Index(outer: index.outer, inner: inner) }
} }
var remainder = distance var remainder = distance
if let indexInner = index.inner { if let indexInner = index.inner {
let element = base[index.outer] let element = base[index.outer]
if let inner = element.index( if let inner = element.index(
indexInner, indexInner,
offsetBy: -remainder, offsetBy: -remainder,
limitedBy: element.startIndex limitedBy: element.startIndex
) { ) {
return Index(outer: index.outer, inner: inner) return Index(outer: index.outer, inner: inner)
} }
remainder -= element[..<indexInner].count remainder -= element[..<indexInner].count
} }
var outer = base.index(index.outer, offsetBy: -1) var outer = base.index(index.outer, offsetBy: -1)
while outer != limit.outer { while outer != limit.outer {
let element = base[outer] let element = base[outer]
if let inner = element.index( if let inner = element.index(
element.endIndex, element.endIndex,
offsetBy: -remainder, offsetBy: -remainder,
limitedBy: element.startIndex limitedBy: element.startIndex
) { ) {
return Index(outer: outer, inner: inner) return Index(outer: outer, inner: inner)
} }
remainder -= element.count remainder -= element.count
base.formIndex(&outer, offsetBy: -1) base.formIndex(&outer, offsetBy: -1)
} }
let element = base[outer] let element = base[outer]
// swift-format-ignore: NeverForceUnwrap
// At start of function, `limit <= index`, and checked for
// `limit == endIndex`.
return element.index( return element.index(
element.endIndex, element.endIndex,
offsetBy: -remainder, offsetBy: -remainder,
@@ -291,24 +274,20 @@ extension FlattenCollection: Collection {
} }
extension FlattenCollection: BidirectionalCollection extension FlattenCollection: BidirectionalCollection
where Base: BidirectionalCollection, Base.Element: BidirectionalCollection { where Base: BidirectionalCollection, Base.Element: BidirectionalCollection
{
@inlinable @inlinable
internal func index(before index: Index) -> Index { internal func index(before index: Index) -> Index {
if let inner = index.inner { if let inner = index.inner {
let element = base[index.outer] let element = base[index.outer]
if inner != element.startIndex { if inner != element.startIndex {
let previousInner = element.index(before: inner) let previousInner = element.index(before: inner)
return Index(outer: index.outer, inner: previousInner) return Index(outer: index.outer, inner: previousInner)
} }
} }
guard let previousOuter = base[..<index.outer].lastIndex(where: { !$0.isEmpty })!
let previousOuter = base[..<index.outer]
.lastIndex(where: { !$0.isEmpty })
else {
fatalError("Can't move before startIndex.")
}
let element = base[previousOuter] let element = base[previousOuter]
let previousInner = element.index(before: element.endIndex) let previousInner = element.index(before: element.endIndex)
return Index(outer: previousOuter, inner: previousInner) return Index(outer: previousOuter, inner: previousInner)
@@ -316,7 +295,7 @@ where Base: BidirectionalCollection, Base.Element: BidirectionalCollection {
} }
extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol extension FlattenCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {} where Base: LazySequenceProtocol, Base.Element: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// joined() // joined()
+8 -10
View File
@@ -10,18 +10,16 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Sequence { extension Sequence {
/// Groups elements of this sequence into a new dictionary, /// Groups up elements of `self` into a new Dictionary,
/// whose values are arrays of grouped elements, /// whose values are Arrays of grouped elements,
/// each keyed by the key returned by the given closure. /// each keyed by the group key returned by the given closure.
/// /// - Parameters:
/// - Parameter keyForValue: A closure that returns a key for each element /// - keyForValue: A closure that returns a key for each element in
/// in the sequence. /// `self`.
/// - Returns: A dictionary containing grouped elements of self, keyed by /// - Returns: A dictionary containing grouped elements of self, keyed by
/// the keys derived by the `keyForValue` closure. /// the keys derived by the `keyForValue` closure.
@inlinable @inlinable
public func grouped<GroupKey>( public func grouped<GroupKey>(by keyForValue: (Element) throws -> GroupKey) rethrows -> [GroupKey: [Element]] {
by keyForValue: (Element) throws -> GroupKey
) rethrows -> [GroupKey: [Element]] {
try Dictionary(grouping: self, by: keyForValue) try Dictionary(grouping: self, by: keyForValue)
} }
} }
+13 -12
View File
@@ -15,7 +15,7 @@ public struct IndexedCollection<Base: Collection> {
/// The base collection. /// The base collection.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@inlinable @inlinable
internal init(base: Base) { internal init(base: Base) {
self.base = base self.base = base
@@ -25,32 +25,32 @@ public struct IndexedCollection<Base: Collection> {
extension IndexedCollection: Collection { extension IndexedCollection: Collection {
/// The element type for an `IndexedCollection` collection. /// The element type for an `IndexedCollection` collection.
public typealias Element = (index: Base.Index, element: Base.Element) public typealias Element = (index: Base.Index, element: Base.Element)
@inlinable @inlinable
public var startIndex: Base.Index { public var startIndex: Base.Index {
base.startIndex base.startIndex
} }
@inlinable @inlinable
public var endIndex: Base.Index { public var endIndex: Base.Index {
base.endIndex base.endIndex
} }
@inlinable @inlinable
public subscript(position: Base.Index) -> Element { public subscript(position: Base.Index) -> Element {
(index: position, element: base[position]) (index: position, element: base[position])
} }
@inlinable @inlinable
public func index(after i: Base.Index) -> Base.Index { public func index(after i: Base.Index) -> Base.Index {
base.index(after: i) base.index(after: i)
} }
@inlinable @inlinable
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index { public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
base.index(i, offsetBy: distance) base.index(i, offsetBy: distance)
} }
@inlinable @inlinable
public func index( public func index(
_ i: Base.Index, _ i: Base.Index,
@@ -59,12 +59,12 @@ extension IndexedCollection: Collection {
) -> Base.Index? { ) -> Base.Index? {
base.index(i, offsetBy: distance, limitedBy: limit) base.index(i, offsetBy: distance, limitedBy: limit)
} }
@inlinable @inlinable
public func distance(from start: Base.Index, to end: Base.Index) -> Int { public func distance(from start: Base.Index, to end: Base.Index) -> Int {
base.distance(from: start, to: end) base.distance(from: start, to: end)
} }
@inlinable @inlinable
public var indices: Base.Indices { public var indices: Base.Indices {
base.indices base.indices
@@ -72,7 +72,8 @@ extension IndexedCollection: Collection {
} }
extension IndexedCollection: BidirectionalCollection extension IndexedCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Base.Index) -> Base.Index { public func index(before i: Base.Index) -> Base.Index {
base.index(before: i) base.index(before: i)
@@ -80,10 +81,10 @@ where Base: BidirectionalCollection {
} }
extension IndexedCollection: RandomAccessCollection extension IndexedCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol extension IndexedCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// indexed() // indexed()
+154 -169
View File
@@ -18,10 +18,10 @@
public struct InterspersedSequence<Base: Sequence> { public struct InterspersedSequence<Base: Sequence> {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let separator: Base.Element internal let separator: Base.Element
@inlinable @inlinable
internal init(base: Base, separator: Base.Element) { internal init(base: Base, separator: Base.Element) {
self.base = base self.base = base
@@ -38,16 +38,16 @@ extension InterspersedSequence: Sequence {
case element(Base.Element) case element(Base.Element)
case separator case separator
} }
@usableFromInline @usableFromInline
internal var iterator: Base.Iterator internal var iterator: Base.Iterator
@usableFromInline @usableFromInline
internal let separator: Base.Element internal let separator: Base.Element
@usableFromInline @usableFromInline
internal var state = State.start internal var state = State.start
@inlinable @inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) { internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator self.iterator = iterator
@@ -89,7 +89,7 @@ extension InterspersedSequence: Collection where Base: Collection {
case element(Base.Index) case element(Base.Index)
case separator(next: Base.Index) case separator(next: Base.Index)
} }
@usableFromInline @usableFromInline
internal let representation: Representation internal let representation: Representation
@@ -101,15 +101,15 @@ extension InterspersedSequence: Collection where Base: Collection {
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.representation, rhs.representation) { switch (lhs.representation, rhs.representation) {
case (.element(let li), .element(let ri)), case let (.element(li), .element(ri)),
(.separator(next: let li), .separator(next: let ri)), let (.separator(next: li), .separator(next: ri)),
(.element(let li), .separator(next: let ri)): let (.element(li), .separator(next: ri)):
return li < ri return li < ri
case (.separator(next: let li), .element(let ri)): case let (.separator(next: li), .element(ri)):
return li <= ri return li <= ri
} }
} }
@inlinable @inlinable
internal static func element(_ index: Base.Index) -> Self { internal static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index)) Self(representation: .element(index))
@@ -135,9 +135,9 @@ extension InterspersedSequence: Collection where Base: Collection {
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex") precondition(i != endIndex, "Can't advance past endIndex")
switch i.representation { switch i.representation {
case .element(let index): case let .element(index):
return .separator(next: base.index(after: index)) return .separator(next: base.index(after: index))
case .separator(let next): case let .separator(next):
return .element(next) return .element(next)
} }
} }
@@ -149,20 +149,20 @@ extension InterspersedSequence: Collection where Base: Collection {
case .separator: return separator case .separator: return separator
} }
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) { switch (start.representation, end.representation) {
case (.element(let element), .separator(next: let separator)): case let (.element(element), .separator(next: separator)):
return 2 * base.distance(from: element, to: separator) - 1 return 2 * base.distance(from: element, to: separator) - 1
case (.separator(next: let separator), .element(let element)): case let (.separator(next: separator), .element(element)):
return 2 * base.distance(from: separator, to: element) + 1 return 2 * base.distance(from: separator, to: element) + 1
case (.element(let start), .element(let end)), case let (.element(start), .element(end)),
(.separator(let start), .separator(let end)): let (.separator(start), .separator(end)):
return 2 * base.distance(from: start, to: end) return 2 * base.distance(from: start, to: end)
} }
} }
@inlinable @inlinable
public func index(_ index: Index, offsetBy distance: Int) -> Index { public func index(_ index: Index, offsetBy distance: Int) -> Index {
distance >= 0 distance >= 0
@@ -172,94 +172,84 @@ extension InterspersedSequence: Collection where Base: Collection {
@inlinable @inlinable
public func index( public func index(
_ index: Index, _ index: Index,
offsetBy distance: Int, offsetBy distance: Int,
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
if distance >= 0 { if distance >= 0 {
return limit >= index return limit >= index
? offsetForward(index, by: distance, limitedBy: limit) ? offsetForward(index, by: distance, limitedBy: limit)
: offsetForward(index, by: distance) : offsetForward(index, by: distance)
} else { } else {
return limit <= index return limit <= index
? offsetBackward(index, by: -distance, limitedBy: limit) ? offsetBackward(index, by: -distance, limitedBy: limit)
: offsetBackward(index, by: -distance) : offsetBackward(index, by: -distance)
}
} }
}
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit >= index) assert(limit >= index)
switch ( switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
index.representation, limit.representation, distance.isMultiple(of: 2) case let (.element(index), .element(limit), true),
) { let (.separator(next: index), .element(limit), false):
case (.element(let index), .element(let limit), true),
(.separator(next: let index), .element(let limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit) return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.map { .element($0) } .map { .element($0) }
case (.element(let index), .element(let limit), false), case let (.element(index), .element(limit), false),
(.element(let index), .separator(next: let limit), false), let (.element(index), .separator(next: limit), false),
(.separator(next: let index), .element(let limit), true), let (.separator(next: index), .element(limit), true),
(.separator(next: let index), .separator(next: let limit), true): let (.separator(next: index), .separator(next: limit), true):
return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit) return base.index(index, offsetBy: (distance + 1) / 2, limitedBy: limit)
.map { .separator(next: $0) } .map { .separator(next: $0) }
case (.element(let index), .separator(next: let limit), true), case let (.element(index), .separator(next: limit), true),
(.separator(next: let index), .separator(next: let limit), false): let (.separator(next: index), .separator(next: limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit) return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.flatMap { $0 == limit ? nil : .element($0) } .flatMap { $0 == limit ? nil : .element($0) }
} }
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit <= index) assert(limit <= index)
switch ( switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
index.representation, limit.representation, distance.isMultiple(of: 2) case let (.element(index), .element(limit), true),
) { let (.element(index), .separator(next: limit), true),
case (.element(let index), .element(let limit), true), let (.separator(next: index), .element(limit), false),
(.element(let index), .separator(next: let limit), true), let (.separator(next: index), .separator(next: limit), false):
(.separator(next: let index), .element(let limit), false), return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
(.separator(next: let index), .separator(next: let limit), false): .map { .element($0) }
return base.index(
index, offsetBy: -((distance + 1) / 2), limitedBy: limit case let (.element(index), .separator(next: limit), false),
) let (.separator(next: index), .separator(next: limit), true):
.map { .element($0) }
case (.element(let index), .separator(next: let limit), false),
(.separator(next: let index), .separator(next: let limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit) return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.map { .separator(next: $0) } .map { .separator(next: $0) }
case (.element(let index), .element(let limit), false), case let (.element(index), .element(limit), false),
(.separator(next: let index), .element(let limit), true): let (.separator(next: index), .element(limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit) return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.flatMap { $0 == limit ? nil : .separator(next: $0) } .flatMap { $0 == limit ? nil : .separator(next: $0) }
} }
@@ -267,32 +257,34 @@ extension InterspersedSequence: Collection where Base: Collection {
} }
extension InterspersedSequence: BidirectionalCollection extension InterspersedSequence: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex") precondition(i != startIndex, "Can't move before startIndex")
switch i.representation { switch i.representation {
case .element(let index): case let .element(index):
return .separator(next: index) return .separator(next: index)
case .separator(let next): case let .separator(next):
return .element(base.index(before: next)) return .element(base.index(before: next))
} }
} }
} }
extension InterspersedSequence: RandomAccessCollection extension InterspersedSequence: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension InterspersedSequence: LazySequenceProtocol extension InterspersedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension InterspersedSequence: LazyCollectionProtocol extension InterspersedSequence: LazyCollectionProtocol
where Base: LazySequenceProtocol & Collection {} where Base: LazySequenceProtocol & Collection {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// InterspersedMap // InterspersedMap
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
/// A sequence over the results of applying a closure to the sequence's /// A sequence over the results of applying a closure to the sequence's
/// elements, with a separator that separates each pair of adjacent transformed /// elements, with a separator that separates each pair of adjacent transformed
/// values. /// values.
@@ -300,10 +292,10 @@ where Base: LazySequenceProtocol & Collection {}
internal struct InterspersedMapSequence<Base: Sequence, Result> { internal struct InterspersedMapSequence<Base: Sequence, Result> {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let transform: (Base.Element) -> Result internal let transform: (Base.Element) -> Result
@usableFromInline @usableFromInline
internal let separator: (Base.Element, Base.Element) -> Result internal let separator: (Base.Element, Base.Element) -> Result
} }
@@ -317,19 +309,19 @@ extension InterspersedMapSequence: Sequence {
case element(Base.Element) case element(Base.Element)
case separator(previous: Base.Element) case separator(previous: Base.Element)
} }
@usableFromInline @usableFromInline
internal var base: Base.Iterator internal var base: Base.Iterator
@usableFromInline @usableFromInline
internal let transform: (Base.Element) -> Result internal let transform: (Base.Element) -> Result
@usableFromInline @usableFromInline
internal let separator: (Base.Element, Base.Element) -> Result internal let separator: (Base.Element, Base.Element) -> Result
@usableFromInline @usableFromInline
internal var state = State.start internal var state = State.start
@inlinable @inlinable
internal init( internal init(
base: Base.Iterator, base: Base.Iterator,
@@ -376,64 +368,61 @@ extension InterspersedMapSequence: Collection where Base: Collection {
case element(Base.Index) case element(Base.Index)
case separator(previous: Base.Index, next: Base.Index) case separator(previous: Base.Index, next: Base.Index)
} }
@usableFromInline @usableFromInline
internal let base: Representation internal let representation: Representation
@inlinable @inlinable
internal init(representation: Representation) { internal init(representation: Representation) {
self.base = representation self.representation = representation
} }
@inlinable @inlinable
internal static func element(_ index: Base.Index) -> Self { internal static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index)) Self(representation: .element(index))
} }
@inlinable @inlinable
internal static func separator( internal static func separator(previous: Base.Index, next: Base.Index) -> Self {
previous: Base.Index,
next: Base.Index
) -> Self {
Self(representation: .separator(previous: previous, next: next)) Self(representation: .separator(previous: previous, next: next))
} }
@inlinable @inlinable
internal static func == (lhs: Self, rhs: Self) -> Bool { internal static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.base, rhs.base) { switch (lhs.representation, rhs.representation) {
case (.element(let lhs), .element(let rhs)), case let (.element(lhs), .element(rhs)),
(.separator(_, next: let lhs), .separator(_, next: let rhs)): let (.separator(_, next: lhs), .separator(_, next: rhs)):
return lhs == rhs return lhs == rhs
case (.element, .separator), (.separator, .element): case (.element, .separator), (.separator, .element):
return false return false
} }
} }
@inlinable @inlinable
internal static func < (lhs: Self, rhs: Self) -> Bool { internal static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs.base, rhs.base) { switch (lhs.representation, rhs.representation) {
case (.element(let lhs), .element(let rhs)), case let (.element(lhs), .element(rhs)),
(.separator(_, next: let lhs), .separator(_, next: let rhs)), let (.separator(_, next: lhs), .separator(_, next: rhs)),
(.element(let lhs), .separator(_, next: let rhs)), let (.element(lhs), .separator(_, next: rhs)),
(.separator(previous: let lhs, _), .element(let rhs)): let (.separator(previous: lhs, _), .element(rhs)):
return lhs < rhs return lhs < rhs
} }
} }
} }
@inlinable @inlinable
internal var startIndex: Index { internal var startIndex: Index {
base.isEmpty ? endIndex : .element(base.startIndex) base.isEmpty ? endIndex : .element(base.startIndex)
} }
@inlinable @inlinable
internal var endIndex: Index { internal var endIndex: Index {
.separator(previous: base.endIndex, next: base.endIndex) .separator(previous: base.endIndex, next: base.endIndex)
} }
@inlinable @inlinable
internal func index(after index: Index) -> Index { internal func index(after index: Index) -> Index {
switch index.base { switch index.representation {
case .element(let index): case .element(let index):
let next = base.index(after: index) let next = base.index(after: index)
return .separator(previous: index, next: next) return .separator(previous: index, next: next)
@@ -441,39 +430,39 @@ extension InterspersedMapSequence: Collection where Base: Collection {
return .element(next) return .element(next)
} }
} }
@inlinable @inlinable
internal subscript(position: Index) -> Result { internal subscript(position: Index) -> Result {
switch position.base { switch position.representation {
case .element(let index): case .element(let index):
return transform(base[index]) return transform(base[index])
case .separator(let previous, let next): case let .separator(previous, next):
return separator(base[previous], base[next]) return separator(base[previous], base[next])
} }
} }
@inlinable @inlinable
internal func distance(from start: Index, to end: Index) -> Int { internal func distance(from start: Index, to end: Index) -> Int {
switch (start.base, end.base) { switch (start.representation, end.representation) {
case (.element(let lhs), .element(let rhs)), case let (.element(lhs), .element(rhs)),
(.separator(_, next: let lhs), .separator(_, next: let rhs)): let (.separator(_, next: lhs), .separator(_, next: rhs)):
return 2 * base.distance(from: lhs, to: rhs) return 2 * base.distance(from: lhs, to: rhs)
case (.element(let lhs), .separator(_, next: let rhs)): case let (.element(lhs), .separator(_, next: rhs)):
return 2 * base.distance(from: lhs, to: rhs) - 1 return 2 * base.distance(from: lhs, to: rhs) - 1
case (.separator(_, next: let lhs), .element(let rhs)): case let (.separator(_, next: lhs), .element(rhs)):
return 2 * base.distance(from: lhs, to: rhs) + 1 return 2 * base.distance(from: lhs, to: rhs) + 1
} }
} }
@inlinable @inlinable
internal func index(_ index: Index, offsetBy distance: Int) -> Index { internal func index(_ index: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return index } guard distance != 0 else { return index }
return distance > 0 return distance > 0
? offsetForward(index, by: distance) ? offsetForward(index, by: distance)
: offsetBackward(index, by: -distance) : offsetBackward(index, by: -distance)
} }
@inlinable @inlinable
internal func index( internal func index(
_ index: Index, _ index: Index,
@@ -481,7 +470,7 @@ extension InterspersedMapSequence: Collection where Base: Collection {
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
guard distance != 0 else { return index } guard distance != 0 else { return index }
if distance > 0 { if distance > 0 {
return limit >= index return limit >= index
? offsetForward(index, by: distance, limitedBy: limit) ? offsetForward(index, by: distance, limitedBy: limit)
@@ -492,40 +481,38 @@ extension InterspersedMapSequence: Collection where Base: Collection {
: offsetBackward(index, by: -distance) : offsetBackward(index, by: -distance)
} }
} }
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit >= index) assert(limit >= index)
switch (index.base, limit.base, distance.isMultiple(of: 2)) { switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case (.element(let index), .element(let limit), true), case let (.element(index), .element(limit), true),
(.separator(_, next: let index), .element(let limit), false): let (.separator(_, next: index), .element(limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit) return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.map { .element($0) } .map { .element($0) }
case (.element(let index), .element(let limit), false), case let (.element(index), .element(limit), false),
(.element(let index), .separator(_, next: let limit), false), let (.element(index), .separator(_, next: limit), false),
(.separator(_, next: let index), .element(let limit), true), let (.separator(_, next: index), .element(limit), true),
(.separator(_, next: let index), .separator(_, next: let limit), true): let (.separator(_, next: index), .separator(_, next: limit), true):
return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit) return base.index(index, offsetBy: (distance - 1) / 2, limitedBy: limit)
.flatMap { .flatMap {
guard $0 != limit else { return nil } guard $0 != limit else { return nil }
@@ -534,40 +521,36 @@ extension InterspersedMapSequence: Collection where Base: Collection {
? endIndex ? endIndex
: .separator(previous: $0, next: next) : .separator(previous: $0, next: next)
} }
case (.element(let index), .separator(_, next: let limit), true), case let (.element(index), .separator(_, next: limit), true),
(.separator(_, next: let index), .separator(_, next: let limit), false): let (.separator(_, next: index), .separator(_, next: limit), false):
return base.index(index, offsetBy: distance / 2, limitedBy: limit) return base.index(index, offsetBy: distance / 2, limitedBy: limit)
.flatMap { $0 == limit ? nil : .element($0) } .flatMap { $0 == limit ? nil : .element($0) }
} }
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ index: Index, _ index: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit <= index) assert(limit <= index)
switch (index.base, limit.base, distance.isMultiple(of: 2)) { switch (index.representation, limit.representation, distance.isMultiple(of: 2)) {
case (.element(let index), .element(let limit), true), case let (.element(index), .element(limit), true),
(.element(let index), .separator(_, next: let limit), true), let (.element(index), .separator(_, next: limit), true),
(.separator(_, next: let index), .element(let limit), false), let (.separator(_, next: index), .element(limit), false),
(.separator(_, next: let index), .separator(_, next: let limit), false): let (.separator(_, next: index), .separator(_, next: limit), false):
return return base.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
base
.index(index, offsetBy: -((distance + 1) / 2), limitedBy: limit)
.map { .element($0) } .map { .element($0) }
case (.element(let index), .separator(_, next: let limit), false), case let (.element(index), .separator(_, next: limit), false),
(.separator(_, next: let index), .separator(_, next: let limit), true): let (.separator(_, next: index), .separator(_, next: limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit) return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.map { .separator(previous: base.index($0, offsetBy: -1), next: $0) } .map { .separator(previous: base.index($0, offsetBy: -1), next: $0) }
case (.element(let index), .element(let limit), false), case let (.element(index), .element(limit), false),
(.separator(_, next: let index), .element(let limit), true): let (.separator(_, next: index), .element(limit), true):
return base.index(index, offsetBy: -(distance / 2), limitedBy: limit) return base.index(index, offsetBy: -(distance / 2), limitedBy: limit)
.flatMap { .flatMap {
$0 == limit $0 == limit
@@ -579,14 +562,15 @@ extension InterspersedMapSequence: Collection where Base: Collection {
} }
extension InterspersedMapSequence: BidirectionalCollection extension InterspersedMapSequence: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
internal func index(before index: Index) -> Index { internal func index(before index: Index) -> Index {
switch index.base { switch index.representation {
case .element(let index): case .element(let index):
let previous = base.index(before: index) let previous = base.index(before: index)
return .separator(previous: previous, next: index) return .separator(previous: previous, next: index)
case .separator(let previous, let next): case let .separator(previous, next):
let index = next == base.endIndex ? base.index(before: next) : previous let index = next == base.endIndex ? base.index(before: next) : previous
return .element(index) return .element(index)
} }
@@ -594,10 +578,11 @@ where Base: BidirectionalCollection {
} }
extension InterspersedMapSequence.Index: Hashable extension InterspersedMapSequence.Index: Hashable
where Base.Index: Hashable { where Base.Index: Hashable
{
@inlinable @inlinable
internal func hash(into hasher: inout Hasher) { internal func hash(into hasher: inout Hasher) {
switch base { switch representation {
case .element(let base): case .element(let base):
hasher.combine(false) hasher.combine(false)
hasher.combine(base) hasher.combine(base)
@@ -610,7 +595,7 @@ where Base.Index: Hashable {
extension InterspersedMapSequence: LazySequenceProtocol {} extension InterspersedMapSequence: LazySequenceProtocol {}
extension InterspersedMapSequence: LazyCollectionProtocol extension InterspersedMapSequence: LazyCollectionProtocol
where Base: Collection {} where Base: Collection {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// interspersed(with:) // interspersed(with:)
+74 -84
View File
@@ -16,17 +16,15 @@
/// A sequence that presents the elements of a base sequence of sequences /// A sequence that presents the elements of a base sequence of sequences
/// concatenated using a given separator. /// concatenated using a given separator.
public struct JoinedBySequence<Base: Sequence, Separator: Sequence> public struct JoinedBySequence<Base: Sequence, Separator: Sequence>
where Base.Element: Sequence, Base.Element.Element == Separator.Element { where Base.Element: Sequence, Base.Element.Element == Separator.Element
{
@usableFromInline @usableFromInline
internal typealias Inner = FlattenSequence< internal typealias Inner = FlattenSequence<InterspersedSequence<
InterspersedSequence< LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>
>
>
@usableFromInline @usableFromInline
internal let inner: Inner internal let inner: Inner
@inlinable @inlinable
internal init(base: Base, separator: Separator) { internal init(base: Base, separator: Separator) {
self.inner = base.lazy self.inner = base.lazy
@@ -40,18 +38,18 @@ extension JoinedBySequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var inner: Inner.Iterator internal var inner: Inner.Iterator
@inlinable @inlinable
internal init(inner: Inner.Iterator) { internal init(inner: Inner.Iterator) {
self.inner = inner self.inner = inner
} }
@inlinable @inlinable
public mutating func next() -> Base.Element.Element? { public mutating func next() -> Base.Element.Element? {
inner.next() inner.next()
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(inner: inner.makeIterator()) Iterator(inner: inner.makeIterator())
@@ -59,7 +57,7 @@ extension JoinedBySequence: Sequence {
} }
extension JoinedBySequence: LazySequenceProtocol extension JoinedBySequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// JoinedByClosureSequence // JoinedByClosureSequence
@@ -69,17 +67,15 @@ where Base: LazySequenceProtocol {}
/// concatenated using a given separator that depends on the sequences right /// concatenated using a given separator that depends on the sequences right
/// before and after it. /// before and after it.
public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence> public struct JoinedByClosureSequence<Base: Sequence, Separator: Sequence>
where Base.Element: Sequence, Base.Element.Element == Separator.Element { where Base.Element: Sequence, Base.Element.Element == Separator.Element
{
@usableFromInline @usableFromInline
internal typealias Inner = FlattenSequence< internal typealias Inner = FlattenSequence<InterspersedMapSequence<
InterspersedMapSequence< Base, EitherSequence<Base.Element, Separator>>>
Base, EitherSequence<Base.Element, Separator>
>
>
@usableFromInline @usableFromInline
internal let inner: Inner internal let inner: Inner
@inlinable @inlinable
internal init( internal init(
base: Base, base: Base,
@@ -88,8 +84,7 @@ where Base.Element: Sequence, Base.Element.Element == Separator.Element {
self.inner = base.lazy self.inner = base.lazy
.interspersedMap( .interspersedMap(
EitherSequence.left, EitherSequence.left,
with: { EitherSequence.right(separator($0, $1)) } with: { EitherSequence.right(separator($0, $1)) })
)
.joined() .joined()
} }
} }
@@ -98,18 +93,18 @@ extension JoinedByClosureSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var inner: Inner.Iterator internal var inner: Inner.Iterator
@inlinable @inlinable
internal init(inner: Inner.Iterator) { internal init(inner: Inner.Iterator) {
self.inner = inner self.inner = inner
} }
@inlinable @inlinable
public mutating func next() -> Base.Element.Element? { public mutating func next() -> Base.Element.Element? {
inner.next() inner.next()
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(inner: inner.makeIterator()) Iterator(inner: inner.makeIterator())
@@ -125,17 +120,15 @@ extension JoinedByClosureSequence: LazySequenceProtocol {}
/// A collection that presents the elements of a base collection of collections /// A collection that presents the elements of a base collection of collections
/// concatenated using a given separator. /// concatenated using a given separator.
public struct JoinedByCollection<Base: Collection, Separator: Collection> public struct JoinedByCollection<Base: Collection, Separator: Collection>
where Base.Element: Collection, Base.Element.Element == Separator.Element { where Base.Element: Collection, Base.Element.Element == Separator.Element
{
@usableFromInline @usableFromInline
internal typealias Inner = FlattenCollection< internal typealias Inner = FlattenCollection<InterspersedSequence<
InterspersedSequence< LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>>>
LazyMapSequence<Base, EitherSequence<Base.Element, Separator>>
>
>
@usableFromInline @usableFromInline
internal let inner: Inner internal let inner: Inner
@inlinable @inlinable
internal init(base: Base, separator: Separator) { internal init(base: Base, separator: Separator) {
self.inner = base.lazy self.inner = base.lazy
@@ -149,48 +142,48 @@ extension JoinedByCollection: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal let inner: Inner.Index internal let inner: Inner.Index
@inlinable @inlinable
internal init(_ inner: Inner.Index) { internal init(_ inner: Inner.Index) {
self.inner = inner self.inner = inner
} }
@inlinable @inlinable
public static func == (lhs: Self, rhs: Self) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.inner == rhs.inner lhs.inner == rhs.inner
} }
@inlinable @inlinable
public static func < (lhs: Self, rhs: Self) -> Bool { public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.inner < rhs.inner lhs.inner < rhs.inner
} }
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index(inner.startIndex) Index(inner.startIndex)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(inner.endIndex) Index(inner.endIndex)
} }
@inlinable @inlinable
public func index(after index: Index) -> Index { public func index(after index: Index) -> Index {
Index(inner.index(after: index.inner)) Index(inner.index(after: index.inner))
} }
@inlinable @inlinable
public subscript(position: Index) -> Base.Element.Element { public subscript(position: Index) -> Base.Element.Element {
inner[position.inner] inner[position.inner]
} }
@inlinable @inlinable
public func index(_ index: Index, offsetBy distance: Int) -> Index { public func index(_ index: Index, offsetBy distance: Int) -> Index {
Index(inner.index(index.inner, offsetBy: distance)) Index(inner.index(index.inner, offsetBy: distance))
} }
@inlinable @inlinable
public func index( public func index(
_ index: Index, _ index: Index,
@@ -200,7 +193,7 @@ extension JoinedByCollection: Collection {
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner) inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
.map(Index.init) .map(Index.init)
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
inner.distance(from: start.inner, to: end.inner) inner.distance(from: start.inner, to: end.inner)
@@ -208,10 +201,9 @@ extension JoinedByCollection: Collection {
} }
extension JoinedByCollection: BidirectionalCollection extension JoinedByCollection: BidirectionalCollection
where where Base: BidirectionalCollection,
Base: BidirectionalCollection, Base.Element: BidirectionalCollection,
Base.Element: BidirectionalCollection, Separator: BidirectionalCollection
Separator: BidirectionalCollection
{ {
@inlinable @inlinable
public func index(before index: Index) -> Index { public func index(before index: Index) -> Index {
@@ -220,7 +212,7 @@ where
} }
extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol extension JoinedByCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// JoinedByClosureCollection // JoinedByClosureCollection
@@ -230,17 +222,15 @@ where Base: LazySequenceProtocol {}
/// concatenated using a given separator that depends on the collections right /// concatenated using a given separator that depends on the collections right
/// before and after it. /// before and after it.
public struct JoinedByClosureCollection<Base: Collection, Separator: Collection> public struct JoinedByClosureCollection<Base: Collection, Separator: Collection>
where Base.Element: Collection, Base.Element.Element == Separator.Element { where Base.Element: Collection, Base.Element.Element == Separator.Element
{
@usableFromInline @usableFromInline
internal typealias Inner = FlattenCollection< internal typealias Inner = FlattenCollection<InterspersedMapSequence<
InterspersedMapSequence< Base, EitherSequence<Base.Element, Separator>>>
Base, EitherSequence<Base.Element, Separator>
>
>
@usableFromInline @usableFromInline
internal let inner: Inner internal let inner: Inner
@inlinable @inlinable
internal init( internal init(
base: Base, base: Base,
@@ -249,8 +239,7 @@ where Base.Element: Collection, Base.Element.Element == Separator.Element {
self.inner = base.lazy self.inner = base.lazy
.interspersedMap( .interspersedMap(
EitherSequence.left, EitherSequence.left,
with: { EitherSequence.right(separator($0, $1)) } with: { EitherSequence.right(separator($0, $1)) })
)
.joined() .joined()
} }
} }
@@ -259,48 +248,48 @@ extension JoinedByClosureCollection: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal let inner: Inner.Index internal let inner: Inner.Index
@inlinable @inlinable
internal init(_ inner: Inner.Index) { internal init(_ inner: Inner.Index) {
self.inner = inner self.inner = inner
} }
@inlinable @inlinable
public static func == (lhs: Self, rhs: Self) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.inner == rhs.inner lhs.inner == rhs.inner
} }
@inlinable @inlinable
public static func < (lhs: Self, rhs: Self) -> Bool { public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.inner < rhs.inner lhs.inner < rhs.inner
} }
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index(inner.startIndex) Index(inner.startIndex)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(inner.endIndex) Index(inner.endIndex)
} }
@inlinable @inlinable
public func index(after index: Index) -> Index { public func index(after index: Index) -> Index {
Index(inner.index(after: index.inner)) Index(inner.index(after: index.inner))
} }
@inlinable @inlinable
public subscript(position: Index) -> Base.Element.Element { public subscript(position: Index) -> Base.Element.Element {
inner[position.inner] inner[position.inner]
} }
@inlinable @inlinable
public func index(_ index: Index, offsetBy distance: Int) -> Index { public func index(_ index: Index, offsetBy distance: Int) -> Index {
Index(inner.index(index.inner, offsetBy: distance)) Index(inner.index(index.inner, offsetBy: distance))
} }
@inlinable @inlinable
public func index( public func index(
_ index: Index, _ index: Index,
@@ -310,7 +299,7 @@ extension JoinedByClosureCollection: Collection {
inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner) inner.index(index.inner, offsetBy: distance, limitedBy: limit.inner)
.map(Index.init) .map(Index.init)
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
inner.distance(from: start.inner, to: end.inner) inner.distance(from: start.inner, to: end.inner)
@@ -318,10 +307,9 @@ extension JoinedByClosureCollection: Collection {
} }
extension JoinedByClosureCollection: BidirectionalCollection extension JoinedByClosureCollection: BidirectionalCollection
where where Base: BidirectionalCollection,
Base: BidirectionalCollection, Base.Element: BidirectionalCollection,
Base.Element: BidirectionalCollection, Separator: BidirectionalCollection
Separator: BidirectionalCollection
{ {
@inlinable @inlinable
public func index(before index: Index) -> Index { public func index(before index: Index) -> Index {
@@ -349,7 +337,7 @@ extension Sequence where Element: Sequence {
{ {
joined(by: CollectionOfOne(separator)) joined(by: CollectionOfOne(separator))
} }
/// Returns the concatenation of the elements in this sequence of sequences, /// Returns the concatenation of the elements in this sequence of sequences,
/// inserting the given separator between each sequence. /// inserting the given separator between each sequence.
/// ///
@@ -361,29 +349,30 @@ extension Sequence where Element: Sequence {
public func joined<Separator>( public func joined<Separator>(
by separator: Separator by separator: Separator
) -> JoinedBySequence<Self, Separator> ) -> JoinedBySequence<Self, Separator>
where Separator: Collection, Separator.Element == Element.Element { where Separator: Collection, Separator.Element == Element.Element
{
JoinedBySequence(base: self, separator: separator) JoinedBySequence(base: self, separator: separator)
} }
@inlinable @inlinable
internal func _joined( internal func _joined(
by update: (inout [Element.Element], Element, Element) throws -> Void by update: (inout [Element.Element], Element, Element) throws -> Void
) rethrows -> [Element.Element] { ) rethrows -> [Element.Element] {
var iterator = makeIterator() var iterator = makeIterator()
guard let first = iterator.next() else { return [] } guard let first = iterator.next() else { return [] }
var result = Array(first) var result = Array(first)
var previous = first var previous = first
while let next = iterator.next() { while let next = iterator.next() {
try update(&result, previous, next) try update(&result, previous, next)
result.append(contentsOf: next) result.append(contentsOf: next)
previous = next previous = next
} }
return result return result
} }
/// Returns the concatenation of the elements in this sequence of sequences, /// Returns the concatenation of the elements in this sequence of sequences,
/// inserting the separator produced by the closure between each sequence. /// inserting the separator produced by the closure between each sequence.
/// ///
@@ -397,7 +386,7 @@ extension Sequence where Element: Sequence {
) rethrows -> [Element.Element] { ) rethrows -> [Element.Element] {
try _joined(by: { $0.append(try separator($1, $2)) }) try _joined(by: { $0.append(try separator($1, $2)) })
} }
/// Returns the concatenation of the elements in this sequence of sequences, /// Returns the concatenation of the elements in this sequence of sequences,
/// inserting the separator produced by the closure between each sequence. /// inserting the separator produced by the closure between each sequence.
/// ///
@@ -409,7 +398,8 @@ extension Sequence where Element: Sequence {
public func joined<Separator>( public func joined<Separator>(
by separator: (Element, Element) throws -> Separator by separator: (Element, Element) throws -> Separator
) rethrows -> [Element.Element] ) rethrows -> [Element.Element]
where Separator: Sequence, Separator.Element == Element.Element { where Separator: Sequence, Separator.Element == Element.Element
{
try _joined(by: { $0.append(contentsOf: try separator($1, $2)) }) try _joined(by: { $0.append(contentsOf: try separator($1, $2)) })
} }
} }
@@ -427,7 +417,7 @@ extension LazySequenceProtocol where Element: Sequence {
) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> { ) -> JoinedByClosureSequence<Elements, CollectionOfOne<Element.Element>> {
joined(by: { CollectionOfOne(separator($0, $1)) }) joined(by: { CollectionOfOne(separator($0, $1)) })
} }
/// Returns the concatenation of the elements in this sequence of sequences, /// Returns the concatenation of the elements in this sequence of sequences,
/// inserting the separator produced by the closure between each sequence. /// inserting the separator produced by the closure between each sequence.
@inlinable @inlinable
@@ -456,7 +446,7 @@ extension Collection where Element: Collection {
{ {
joined(by: CollectionOfOne(separator)) joined(by: CollectionOfOne(separator))
} }
/// Returns the concatenation of the elements in this collection of /// Returns the concatenation of the elements in this collection of
/// collections, inserting the given separator between each collection. /// collections, inserting the given separator between each collection.
/// ///
@@ -486,7 +476,7 @@ extension LazySequenceProtocol where Elements: Collection, Element: Collection {
) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> { ) -> JoinedByClosureCollection<Elements, CollectionOfOne<Element.Element>> {
joined(by: { CollectionOfOne(separator($0, $1)) }) joined(by: { CollectionOfOne(separator($0, $1)) })
} }
/// Returns the concatenation of the elements in this collection of /// Returns the concatenation of the elements in this collection of
/// collections, inserting the separator produced by the closure between each /// collections, inserting the separator produced by the closure between each
/// sequence. /// sequence.
+15 -26
View File
@@ -10,51 +10,40 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Sequence { extension Sequence {
/// Creates a new dictionary keyed by the result of the given closure, using /// Creates a new Dictionary from the elements of `self`, keyed by the
/// the latest element for any duplicate keys. /// results returned by the given `keyForValue` closure.
/// ///
/// If the key derived for a new element collides with an existing key from a /// If the key derived for a new element collides with an existing key from a previous element,
/// previous element, the latest value will be kept. /// the latest value will be kept.
/// ///
/// - Parameter keyForValue: A closure that returns a key for each element in /// - Parameters:
/// `self`. /// - keyForValue: A closure that returns a key for each element in `self`.
/// - Returns: A dictionary with key-value pairs generated by calling
/// `keyForValue` for each element in this sequence. If `keyForValue`
/// returns the same key for two or more elements, the returned dictionary
/// uses the last value for that key.
@inlinable @inlinable
public func keyed<Key>( public func keyed<Key>(
by keyForValue: (Element) throws -> Key by keyForValue: (Element) throws -> Key
) rethrows -> [Key: Element] { ) rethrows -> [Key: Element] {
try self.reduce(into: [:]) { result, element in return try self.keyed(by: keyForValue, resolvingConflictsWith: { _, old, new in new })
try result[keyForValue(element)] = element
}
} }
/// Creates a new dictionary keyed by the result of the first closure, using /// Creates a new Dictionary from the elements of `self`, keyed by the
/// the second closure to resolve the ambiguity for any duplicate keys. /// results returned by the given `keyForValue` closure. As the dictionary is
/// /// built, the initializer calls the `resolve` closure with the current and
/// As the dictionary is built, the initializer calls the `resolve` closure /// new values for any duplicate keys. Pass a closure as `resolve` that
/// with the current and new values for any duplicate keys. Pass a closure as /// returns the value to use in the resulting dictionary: The closure can
/// `resolve` that returns the value to use for that key in the resulting /// choose between the two values, combine them to produce a new value, or
/// dictionary. The closure can choose between the two values, combine them to /// even throw an error.
/// produce a new value, or even throw an error.
/// ///
/// - Parameters: /// - Parameters:
/// - keyForValue: A closure that returns a key for each element in `self`. /// - keyForValue: A closure that returns a key for each element in `self`.
/// - resolve: A closure that is called with the values for any duplicate /// - resolve: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for /// keys that are encountered. The closure returns the desired value for
/// the final dictionary. /// the final dictionary.
/// - Returns: A dictionary with key-value pairs generated by calling
/// `keyForValue` for each element in this sequence. If `keyForValue`
/// returns the same key for two or more elements, the result of the
/// `resolve` closure is used as the value for that key.
@inlinable @inlinable
public func keyed<Key>( public func keyed<Key>(
by keyForValue: (Element) throws -> Key, by keyForValue: (Element) throws -> Key,
resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element resolvingConflictsWith resolve: (Key, Element, Element) throws -> Element
) rethrows -> [Key: Element] { ) rethrows -> [Key: Element] {
var result: [Key: Element] = [:] var result = [Key: Element]()
for element in self { for element in self {
let key = try keyForValue(element) let key = try keyForValue(element)
+20 -28
View File
@@ -10,24 +10,24 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Sequence { extension Sequence {
// Implementation for min(count:areInIncreasingOrder:) /// Implementation for min(count:areInIncreasingOrder:)
@inlinable @inlinable
internal func _minImplementation( internal func _minImplementation(
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
var iterator = makeIterator() var iterator = makeIterator()
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(count) result.reserveCapacity(count)
while result.count < count, let e = iterator.next() { while result.count < count, let e = iterator.next() {
result.append(e) result.append(e)
} }
try result.sort(by: areInIncreasingOrder) try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() { while let e = iterator.next() {
// To be part of `result`, `e` must be strictly less than `result[count - 1]`. // To be part of `result`, `e` must be strictly less than `result.last`.
guard try areInIncreasingOrder(e, result[count - 1]) else { continue } guard try areInIncreasingOrder(e, result.last!) else { continue }
result.removeLast() result.removeLast()
let insertionIndex = let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) } try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
@@ -36,25 +36,25 @@ extension Sequence {
return result return result
} }
// Implementation for max(count:areInIncreasingOrder:) /// Implementation for max(count:areInIncreasingOrder:)
@inlinable @inlinable
internal func _maxImplementation( internal func _maxImplementation(
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
var iterator = makeIterator() var iterator = makeIterator()
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(count) result.reserveCapacity(count)
while result.count < count, let e = iterator.next() { while result.count < count, let e = iterator.next() {
result.append(e) result.append(e)
} }
try result.sort(by: areInIncreasingOrder) try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() { while let e = iterator.next() {
// To be part of `result`, `e` must be greater/equal to `result[0]`. // To be part of `result`, `e` must be greater/equal to `result.first`.
guard try !areInIncreasingOrder(e, result[0]) else { continue } guard try !areInIncreasingOrder(e, result.first!) else { continue }
let insertionIndex = let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) } try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
@@ -69,10 +69,10 @@ extension Sequence {
} }
result[insertionIndex - 1] = e result[insertionIndex - 1] = e
} }
return result return result
} }
/// Returns the smallest elements of this sequence, as sorted by the given /// Returns the smallest elements of this sequence, as sorted by the given
/// predicate. /// predicate.
/// ///
@@ -105,9 +105,7 @@ extension Sequence {
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition( precondition(count >= 0, """
count >= 0,
"""
Cannot find a minimum with a negative count of elements! Cannot find a minimum with a negative count of elements!
""" """
) )
@@ -152,9 +150,7 @@ extension Sequence {
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition( precondition(count >= 0, """
count >= 0,
"""
Cannot find a maximum with a negative count of elements! Cannot find a maximum with a negative count of elements!
""" """
) )
@@ -255,16 +251,14 @@ extension Collection {
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition( precondition(count >= 0, """
count >= 0,
"""
Cannot find a minimum with a negative count of elements! Cannot find a minimum with a negative count of elements!
""" """
) )
// Make sure we are within bounds. // Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count) let prefixCount = Swift.min(count, self.count)
// Do nothing if we're prefixing nothing. // Do nothing if we're prefixing nothing.
guard prefixCount > 0 else { guard prefixCount > 0 else {
return [] return []
@@ -275,7 +269,7 @@ extension Collection {
guard prefixCount < (self.count / 10) else { guard prefixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount)) return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
} }
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder) return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
} }
@@ -311,16 +305,14 @@ extension Collection {
count: Int, count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] { ) rethrows -> [Element] {
precondition( precondition(count >= 0, """
count >= 0,
"""
Cannot find a maximum with a negative count of elements! Cannot find a maximum with a negative count of elements!
""" """
) )
// Make sure we are within bounds. // Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count) let suffixCount = Swift.min(count, self.count)
// Do nothing if we're suffixing nothing. // Do nothing if we're suffixing nothing.
guard suffixCount > 0 else { guard suffixCount > 0 else {
return [] return []
+46 -90
View File
@@ -33,9 +33,8 @@ extension MutableCollection {
? subrange.lowerBound ? subrange.lowerBound
: subrange.upperBound : subrange.upperBound
} }
let h = n / 2 let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
let i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition( let j = try stablePartition(
count: h, count: h,
subrange: subrange.lowerBound..<i, subrange: subrange.lowerBound..<i,
@@ -46,7 +45,7 @@ extension MutableCollection {
by: belongsInSecondPartition) by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i) return rotate(subrange: j..<k, toStartAt: i)
} }
/// Moves all elements satisfying the given predicate into a suffix of the /// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both /// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix. /// partitions, and returns the start of the resulting suffix.
@@ -56,23 +55,19 @@ extension MutableCollection {
/// - belongsInSecondPartition: A predicate used to partition the /// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after /// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it. /// all elements not satisfying it.
/// - Returns: The pivot index `p`, which is the index of the first element
/// in the reordered collection that matches `belongsInSecondPartition`.
/// If no elements in the collection match `belongsInSecondPartition`, the
/// returned index is equal to the collection's `endIndex`.
/// ///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection. /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable @inlinable
public mutating func stablePartition( public mutating func stablePartition(
subrange: Range<Index>, subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index { ) rethrows -> Index {
try stablePartition( try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound), count: distance(from: subrange.lowerBound, to: subrange.upperBound),
subrange: subrange, subrange: subrange,
by: belongsInSecondPartition) by: belongsInSecondPartition)
} }
/// Moves all elements satisfying the given predicate into a suffix of this /// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both /// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix. /// partitions, and returns the start of the resulting suffix.
@@ -80,15 +75,11 @@ extension MutableCollection {
/// - Parameter belongsInSecondPartition: A predicate used to partition the /// - Parameter belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after /// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it. /// all elements not satisfying it.
/// - Returns: The pivot index `p`, which is the index of the first element
/// in the reordered collection that matches `belongsInSecondPartition`.
/// If no elements in the collection match `belongsInSecondPartition`, the
/// returned index is equal to the collection's `endIndex`.
/// ///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection. /// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable @inlinable
public mutating func stablePartition( public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws -> Bool by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index { ) rethrows -> Index {
try stablePartition( try stablePartition(
subrange: startIndex..<endIndex, subrange: startIndex..<endIndex,
@@ -101,25 +92,9 @@ extension MutableCollection {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension MutableCollection { extension MutableCollection {
/// Moves all elements satisfying the given closure into a suffix of the /// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix. /// collection, returning the start position of the resulting suffix.
/// ///
/// After partitioning a collection, there is a pivot index `p` where no
/// element before `p` satisfies the `belongsInSecondPartition` predicate and
/// every element at or after `p` satisfies `belongsInSecondPartition`. This
/// operation isn't guaranteed to be stable, so the relative ordering of
/// elements within the partitions might change.
///
/// - Parameters:
/// - subrange: The range of elements within this collection to partition.
/// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
/// - Returns: The pivot index `p`, which is the index of the first element
/// in the reordered collection that matches `belongsInSecondPartition`.
/// If no elements in the collection match `belongsInSecondPartition`, the
/// returned index is equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*) where n is the length of the collection. /// - Complexity: O(*n*) where n is the length of the collection.
@inlinable @inlinable
public mutating func partition( public mutating func partition(
@@ -129,8 +104,8 @@ extension MutableCollection {
// This version of `partition(subrange:)` is half stable; the elements in // This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order. // the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound } else { return subrange.upperBound }
var j = index(after: i) var j = index(after: i)
while j != subrange.upperBound { while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) { if try !belongsInSecondPartition(self[j]) {
@@ -139,31 +114,15 @@ extension MutableCollection {
} }
formIndex(after: &j) formIndex(after: &j)
} }
return i return i
} }
} }
extension MutableCollection where Self: BidirectionalCollection { extension MutableCollection where Self: BidirectionalCollection {
/// Moves all elements satisfying the given closure into a suffix of the /// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix. /// collection, returning the start position of the resulting suffix.
/// ///
/// After partitioning a collection, there is a pivot index `p` where no
/// element before `p` satisfies the `belongsInSecondPartition` predicate and
/// every element at or after `p` satisfies `belongsInSecondPartition`. This
/// operation isn't guaranteed to be stable, so the relative ordering of
/// elements within the partitions might change.
///
/// - Parameters:
/// - subrange: The range of elements within this collection to partition.
/// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
/// - Returns: The pivot index `p`, which is the index of the first element
/// in the reordered collection that matches `belongsInSecondPartition`.
/// If no elements in the collection match `belongsInSecondPartition`, the
/// returned index is equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*) where n is the length of the collection. /// - Complexity: O(*n*) where n is the length of the collection.
@inlinable @inlinable
public mutating func partition( public mutating func partition(
@@ -231,7 +190,7 @@ extension Collection {
) rethrows -> Index { ) rethrows -> Index {
var n = count var n = count
var l = startIndex var l = startIndex
while n > 0 { while n > 0 {
let half = n / 2 let half = n / 2
let mid = index(l, offsetBy: half) let mid = index(l, offsetBy: half)
@@ -265,23 +224,24 @@ extension Sequence {
/// // Prints "["Kim", "Karl"]" /// // Prints "["Kim", "Karl"]"
/// ///
/// - Parameter predicate: A closure that takes an element of the sequence as /// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the element /// its argument and returns a Boolean value indicating whether the element
/// should be included in the second returned array. Otherwise, the element /// should be included in the second returned array. Otherwise, the element
/// will appear in the first returned array. /// will appear in the first returned array.
///
/// - Returns: Two arrays with all of the elements of the receiver. The /// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and /// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed. The /// the second array contains all the elements that `predicate` allowed. The
/// order of the elements in the arrays matches the order of the elements in /// order of the elements in the arrays matches the order of the elements in
/// the original sequence. /// the original sequence.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable
public func partitioned( public func partitioned(
by predicate: (Element) throws -> Bool by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) { ) rethrows -> (falseElements: [Element], trueElements: [Element]) {
var lhs: [Element] = [] var lhs = [Element]()
var rhs: [Element] = [] var rhs = [Element]()
for element in self { for element in self {
if try predicate(element) { if try predicate(element) {
rhs.append(element) rhs.append(element)
@@ -289,7 +249,7 @@ extension Sequence {
lhs.append(element) lhs.append(element)
} }
} }
return (lhs, rhs) return (lhs, rhs)
} }
} }
@@ -309,14 +269,15 @@ extension Collection {
/// // Prints "["Kim", "Karl"]" /// // Prints "["Kim", "Karl"]"
/// ///
/// - Parameter predicate: A closure that takes an element of the collection /// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns a Boolean value indicating whether the /// as its argument and returns a Boolean value indicating whether the element
/// element should be included in the second returned array. Otherwise, the /// should be included in the second returned array. Otherwise, the element
/// element will appear in the first returned array. /// will appear in the first returned array.
///
/// - Returns: Two arrays with all of the elements of the receiver. The /// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and /// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed. The /// the second array contains all the elements that `predicate` allowed. The
/// order of the elements in the arrays matches the order of the elements in /// order of the elements in the arrays matches the order of the elements in
/// the original collection. /// the original collection.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable
@@ -326,26 +287,23 @@ extension Collection {
guard !self.isEmpty else { guard !self.isEmpty else {
return ([], []) return ([], [])
} }
// Since collections have known sizes, we can allocate one array of size // Since collections have known sizes, we can allocate one array of size
// `self.count`, then insert items at the beginning or end of that contiguous // `self.count`, then insert items at the beginning or end of that contiguous
// block. This way, we don’t have to do any dynamic array resizing. Since we // block. This way, we don’t have to do any dynamic array resizing. Since we
// insert the right elements on the right side in reverse order, we need to // insert the right elements on the right side in reverse order, we need to
// reverse them back to the original order at the end. // reverse them back to the original order at the end.
let count = self.count let count = self.count
// Inside of the `initializer` closure, we set what the actual mid-point is. // Inside of the `initializer` closure, we set what the actual mid-point is.
// We will use this to partition the single array into two. // We will use this to partition the single array into two.
var midPoint: Int = 0 var midPoint: Int = 0
let elements = try [Element]( let elements = try [Element](
unsafeUninitializedCapacity: count, unsafeUninitializedCapacity: count,
initializingWith: { buffer, initializedCount in initializingWith: { buffer, initializedCount in
// swift-format-ignore: NeverForceUnwrap var lhs = buffer.baseAddress!
// Non-empty check above.
let bufferStart = buffer.baseAddress!
var lhs = bufferStart
var rhs = lhs + buffer.count var rhs = lhs + buffer.count
do { do {
for element in self { for element in self {
@@ -357,28 +315,26 @@ extension Collection {
lhs += 1 lhs += 1
} }
} }
precondition( precondition(lhs == rhs, """
lhs == rhs,
"""
Collection's `count` differed from the number of elements iterated. Collection's `count` differed from the number of elements iterated.
""" """
) )
let rhsIndex = rhs - bufferStart let rhsIndex = rhs - buffer.baseAddress!
buffer[rhsIndex...].reverse() buffer[rhsIndex...].reverse()
initializedCount = buffer.count initializedCount = buffer.count
midPoint = rhsIndex midPoint = rhsIndex
} catch { } catch {
let lhsCount = lhs - bufferStart let lhsCount = lhs - buffer.baseAddress!
let rhsCount = (bufferStart + buffer.count) - rhs let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
bufferStart.deinitialize(count: lhsCount) buffer.baseAddress!.deinitialize(count: lhsCount)
rhs.deinitialize(count: rhsCount) rhs.deinitialize(count: rhsCount)
throw error throw error
} }
}) })
let lhs = elements[..<midPoint] let lhs = elements[..<midPoint]
let rhs = elements[midPoint...] let rhs = elements[midPoint...]
return ( return (
+65 -81
View File
@@ -14,7 +14,8 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension MutableCollection extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable { where Self: BidirectionalCollection, Element: Comparable
{
/// Permutes this collection's elements through all the lexical orderings. /// Permutes this collection's elements through all the lexical orderings.
/// ///
/// Call `nextPermutation()` repeatedly starting with the collection in sorted /// Call `nextPermutation()` repeatedly starting with the collection in sorted
@@ -33,27 +34,26 @@ where Self: BidirectionalCollection, Element: Comparable {
guard !isEmpty else { return false } guard !isEmpty else { return false }
var i = index(before: endIndex) var i = index(before: endIndex)
if i == startIndex { return false } if i == startIndex { return false }
let upperBound = upperBound ?? endIndex let upperBound = upperBound ?? endIndex
while true { while true {
let ip1 = i let ip1 = i
formIndex(before: &i) formIndex(before: &i)
// Find the last ascending pair (ie. ..., a, b, ... where a < b) // Find the last ascending pair (ie. ..., a, b, ... where a < b)
if self[i] < self[ip1] { if self[i] < self[ip1] {
// Find the last element greater than self[i] // Find the last element greater than self[i]
// swift-format-ignore: NeverForceUnwrap
// This is _always_ at most `ip1` due to if statement above // This is _always_ at most `ip1` due to if statement above
let j = lastIndex(where: { self[i] < $0 })! let j = lastIndex(where: { self[i] < $0 })!
// At this point we have something like this: // At this point we have something like this:
// 0, 1, 4, 3, 2 // 0, 1, 4, 3, 2
// ^ ^ // ^ ^
// i j // i j
swapAt(i, j) swapAt(i, j)
self.reverse(subrange: ip1..<endIndex) self.reverse(subrange: ip1 ..< endIndex)
// Only return if we've made a change within ..<upperBound region // Only return if we've made a change within ..<upperBound region
if i < upperBound { if i < upperBound {
return true return true
@@ -62,7 +62,7 @@ where Self: BidirectionalCollection, Element: Comparable {
continue continue
} }
} }
if i == startIndex { if i == startIndex {
self.reverse() self.reverse()
return false return false
@@ -80,17 +80,17 @@ public struct PermutationsSequence<Base: Collection> {
/// The base collection to iterate over for permutations. /// The base collection to iterate over for permutations.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let baseCount: Int internal let baseCount: Int
/// The range of accepted sizes of permutations. /// The range of accepted sizes of permutations.
/// ///
/// - Note: This may be empty if the attempted range entirely exceeds the /// - Note: This may be empty if the attempted range entirely exceeds the
/// bounds of the size of the `base` collection. /// bounds of the size of the `base` collection.
@usableFromInline @usableFromInline
internal let kRange: Range<Int> internal let kRange: Range<Int>
/// Initializes a `PermutationsSequence` for all permutations of `base` of /// Initializes a `PermutationsSequence` for all permutations of `base` of
/// size `k`. /// size `k`.
/// ///
@@ -102,13 +102,13 @@ public struct PermutationsSequence<Base: Collection> {
internal init(_ base: Base, k: Int? = nil) { internal init(_ base: Base, k: Int? = nil) {
let kRange: ClosedRange<Int>? let kRange: ClosedRange<Int>?
if let countToChoose = k { if let countToChoose = k {
kRange = countToChoose...countToChoose kRange = countToChoose ... countToChoose
} else { } else {
kRange = nil kRange = nil
} }
self.init(base, kRange: kRange) self.init(base, kRange: kRange)
} }
/// Initializes a `PermutationsSequence` for all combinations of `base` of /// Initializes a `PermutationsSequence` for all combinations of `base` of
/// sizes within a given range. /// sizes within a given range.
/// ///
@@ -118,18 +118,17 @@ public struct PermutationsSequence<Base: Collection> {
/// iterate over all permutations of the same size as the base collection. /// iterate over all permutations of the same size as the base collection.
@inlinable @inlinable
internal init<R: RangeExpression>( internal init<R: RangeExpression>(
_ base: Base, _ base: Base, kRange: R?
kRange: R?
) where R.Bound == Int { ) where R.Bound == Int {
self.base = base self.base = base
let baseCount = base.count let baseCount = base.count
self.baseCount = baseCount self.baseCount = baseCount
let upperBound = baseCount + 1 let upperBound = baseCount + 1
self.kRange = self.kRange = kRange?.relative(to: 0 ..< .max)
kRange?.relative(to: 0 ..< .max) .clamped(to: 0 ..< upperBound) ??
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound baseCount ..< upperBound
} }
/// The total number of permutations. /// The total number of permutations.
@inlinable @inlinable
public var count: Int { public var count: Int {
@@ -144,26 +143,26 @@ extension PermutationsSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let baseCount: Int internal let baseCount: Int
/// The current range of accepted sizes of permutations. /// The current range of accepted sizes of permutations.
/// - Note: The range is contracted until empty while iterating over /// - Note: The range is contracted until empty while iterating over
/// permutations of different sizes. When the range is empty, iteration is /// permutations of different sizes. When the range is empty, iteration is
/// finished. /// finished.
@usableFromInline @usableFromInline
internal var kRange: Range<Int> internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty). /// Whether or not iteration is finished (`kRange` is empty)
@inlinable @inlinable
internal var isFinished: Bool { internal var isFinished: Bool {
kRange.isEmpty return kRange.isEmpty
} }
@usableFromInline @usableFromInline
internal var indexes: [Base.Index] internal var indexes: [Base.Index]
@inlinable @inlinable
internal init(_ permutations: PermutationsSequence) { internal init(_ permutations: PermutationsSequence) {
self.base = permutations.base self.base = permutations.base
@@ -171,7 +170,7 @@ extension PermutationsSequence: Sequence {
self.kRange = permutations.kRange self.kRange = permutations.kRange
self.indexes = Array(permutations.base.indices) self.indexes = Array(permutations.base.indices)
} }
/// Advances the `indexes` array such that the first `countToChoose` /// Advances the `indexes` array such that the first `countToChoose`
/// elements contain the next lexicographic ordering of elements. /// elements contain the next lexicographic ordering of elements.
/// ///
@@ -187,49 +186,44 @@ extension PermutationsSequence: Sequence {
internal mutating func nextState() -> Bool { internal mutating func nextState() -> Bool {
let countToChoose = self.kRange.lowerBound let countToChoose = self.kRange.lowerBound
let edge = countToChoose - 1 let edge = countToChoose - 1
// Find first index greater than the one at `edge`. // Find first index greater than the one at `edge`.
if let i = indexes[countToChoose...] if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
.firstIndex(where: { indexes[edge] < $0 })
{
indexes.swapAt(edge, i) indexes.swapAt(edge, i)
} else { } else {
indexes.reverse(subrange: countToChoose..<indexes.endIndex) indexes.reverse(subrange: countToChoose ..< indexes.endIndex)
// Find last increasing pair below `edge`. // Find last increasing pair below `edge`.
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...) // TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
var lastAscent = edge - 1 var lastAscent = edge - 1
while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] while (lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) {
{
lastAscent -= 1 lastAscent -= 1
} }
if lastAscent < 0 { if lastAscent < 0 {
return false return false
} }
// Find rightmost index less than that at `lastAscent`. // Find rightmost index less than that at `lastAscent`.
if let i = indexes[lastAscent...] if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
.lastIndex(where: { indexes[lastAscent] < $0 })
{
indexes.swapAt(lastAscent, i) indexes.swapAt(lastAscent, i)
} }
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex) indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex)
} }
return true return true
} }
@inlinable @inlinable
public mutating func next() -> [Base.Element]? { public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil } guard !isFinished else { return nil }
/// Advances `kRange` by incrementing its `lowerBound` until the range is /// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished. /// empty, when iteration is finished.
func advanceKRange() { func advanceKRange() {
kRange.removeFirst() kRange.removeFirst()
indexes = Array(base.indices) indexes = Array(base.indices)
} }
let countToChoose = self.kRange.lowerBound let countToChoose = self.kRange.lowerBound
if countToChoose == 0 { if countToChoose == 0 {
defer { defer {
@@ -237,7 +231,7 @@ extension PermutationsSequence: Sequence {
} }
return [] return []
} }
let permutesFullCollection = (countToChoose == baseCount) let permutesFullCollection = (countToChoose == baseCount)
if permutesFullCollection { if permutesFullCollection {
// If we're permuting the full collection, each iteration is just a // If we're permuting the full collection, each iteration is just a
@@ -262,7 +256,7 @@ extension PermutationsSequence: Sequence {
} }
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(self) Iterator(self)
@@ -270,7 +264,7 @@ extension PermutationsSequence: Sequence {
} }
extension PermutationsSequence: LazySequenceProtocol extension PermutationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// permutations(ofCount:) // permutations(ofCount:)
@@ -329,8 +323,6 @@ extension Collection {
/// clamped to the number of elements in this collection. Passing a range /// clamped to the number of elements in this collection. Passing a range
/// covering sizes greater than the number of elements in this collection /// covering sizes greater than the number of elements in this collection
/// results in an empty sequence. /// results in an empty sequence.
/// - Returns: A sequence of the permutations of this collection's elements,
/// for all sizes in `kRange`, from smallest to largest.
/// ///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since /// is the number of elements in the base collection, since
@@ -341,7 +333,7 @@ extension Collection {
) -> PermutationsSequence<Self> where R.Bound == Int { ) -> PermutationsSequence<Self> where R.Bound == Int {
PermutationsSequence(self, kRange: kRange) PermutationsSequence(self, kRange: kRange)
} }
/// Returns a collection of the permutations of this collection of the /// Returns a collection of the permutations of this collection of the
/// specified length. /// specified length.
/// ///
@@ -387,15 +379,12 @@ extension Collection {
/// If `k` is `nil`, the resulting sequence represents permutations of this /// If `k` is `nil`, the resulting sequence represents permutations of this
/// entire collection. If `k` is greater than the number of elements in /// entire collection. If `k` is greater than the number of elements in
/// this collection, the resulting sequence is empty. /// this collection, the resulting sequence is empty.
/// - Returns: A sequence of the permutations of this collection's elements.
/// ///
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n* /// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since /// is the number of elements in the base collection, since
/// `PermutationsSequence` accesses the `count` of the base collection. /// `PermutationsSequence` accesses the `count` of the base collection.
@inlinable @inlinable
public func permutations( public func permutations(ofCount k: Int? = nil) -> PermutationsSequence<Self> {
ofCount k: Int? = nil
) -> PermutationsSequence<Self> {
precondition( precondition(
k ?? 0 >= 0, k ?? 0 >= 0,
"Can't have permutations with a negative number of elements.") "Can't have permutations with a negative number of elements.")
@@ -416,10 +405,10 @@ public struct UniquePermutationsSequence<Base: Collection> {
/// The base collection to iterate over for permutations. /// The base collection to iterate over for permutations.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal var indexes: [Base.Index] internal var indexes: [Base.Index]
@usableFromInline @usableFromInline
internal let kRange: Range<Int> internal let kRange: Range<Int>
} }
@@ -429,31 +418,30 @@ extension UniquePermutationsSequence where Base.Element: Hashable {
internal static func _indexes(_ base: Base) -> [Base.Index] { internal static func _indexes(_ base: Base) -> [Base.Index] {
let firstIndexesAndCountsByElement = Dictionary( let firstIndexesAndCountsByElement = Dictionary(
base.indices.lazy.map { (base[$0], ($0, 1)) }, base.indices.lazy.map { (base[$0], ($0, 1)) },
uniquingKeysWith: { indexAndCount, _ in uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
(indexAndCount.0, indexAndCount.1 + 1)
})
return firstIndexesAndCountsByElement return firstIndexesAndCountsByElement
.values.sorted(by: { $0.0 < $1.0 }) .values.sorted(by: { $0.0 < $1.0 })
.flatMap { index, count in repeatElement(index, count: count) } .flatMap { index, count in repeatElement(index, count: count) }
} }
@inlinable @inlinable
internal init(_ elements: Base) { internal init(_ elements: Base) {
self.indexes = Self._indexes(elements) self.indexes = Self._indexes(elements)
self.base = elements self.base = elements
self.kRange = self.indexes.count..<(self.indexes.count + 1) self.kRange = self.indexes.count ..< (self.indexes.count + 1)
} }
@inlinable @inlinable
internal init<R: RangeExpression>(_ base: Base, _ range: R) internal init<R: RangeExpression>(_ base: Base, _ range: R)
where R.Bound == Int { where R.Bound == Int
{
self.indexes = Self._indexes(base) self.indexes = Self._indexes(base)
self.base = base self.base = base
let upperBound = self.indexes.count + 1 let upperBound = self.indexes.count + 1
self.kRange = range.relative(to: 0 ..< .max) self.kRange = range.relative(to: 0 ..< .max)
.clamped(to: 0..<upperBound) .clamped(to: 0 ..< upperBound)
} }
} }
@@ -462,10 +450,10 @@ extension UniquePermutationsSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal var indexes: [Base.Index] internal var indexes: [Base.Index]
@usableFromInline @usableFromInline
internal var lengths: Range<Int> internal var lengths: Range<Int>
@@ -473,20 +461,19 @@ extension UniquePermutationsSequence: Sequence {
internal var initial = true internal var initial = true
@inlinable @inlinable
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
{
self.base = elements self.base = elements
self.indexes = indexes self.indexes = indexes
self.lengths = lengths self.lengths = lengths
} }
@inlinable @inlinable
public mutating func next() -> [Base.Element]? { public mutating func next() -> [Base.Element]? {
// In the end case, `lengths` is an empty range. // In the end case, `lengths` is an empty range.
if lengths.isEmpty { if lengths.isEmpty {
return nil return nil
} }
// The first iteration must produce the original sorted array, before any // The first iteration must produce the original sorted array, before any
// permutations. We skip the permutation the first time so that we can // permutations. We skip the permutation the first time so that we can
// always mutate the array _before_ returning a slice, which avoids // always mutate the array _before_ returning a slice, which avoids
@@ -503,11 +490,11 @@ extension UniquePermutationsSequence: Sequence {
return nil return nil
} }
} }
return indexes[..<lengths.lowerBound].map { base[$0] } return indexes[..<lengths.lowerBound].map { base[$0] }
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(base, indexes: indexes, lengths: kRange) Iterator(base, indexes: indexes, lengths: kRange)
@@ -515,7 +502,7 @@ extension UniquePermutationsSequence: Sequence {
} }
extension UniquePermutationsSequence: LazySequenceProtocol extension UniquePermutationsSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension Collection where Element: Hashable { extension Collection where Element: Hashable {
/// Returns a sequence of the unique permutations of this sequence of the /// Returns a sequence of the unique permutations of this sequence of the
@@ -553,8 +540,6 @@ extension Collection where Element: Hashable {
/// If `k` is `nil`, the resulting sequence represents permutations of this /// If `k` is `nil`, the resulting sequence represents permutations of this
/// entire collection. If `k` is greater than the number of elements in /// entire collection. If `k` is greater than the number of elements in
/// this collection, the resulting sequence is empty. /// this collection, the resulting sequence is empty.
/// - Returns: A sequence of the unique permutations of this collection's
/// elements.
/// ///
/// - Complexity: O(*n*), where *n* is the number of elements in this /// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection. /// collection.
@@ -562,10 +547,11 @@ extension Collection where Element: Hashable {
public func uniquePermutations(ofCount k: Int? = nil) public func uniquePermutations(ofCount k: Int? = nil)
-> UniquePermutationsSequence<Self> -> UniquePermutationsSequence<Self>
{ {
guard let k = k else { if let k = k {
return UniquePermutationsSequence(self, k ..< (k + 1))
} else {
return UniquePermutationsSequence(self) return UniquePermutationsSequence(self)
} }
return UniquePermutationsSequence(self, k..<(k + 1))
} }
/// Returns a collection of the unique permutations of this sequence with /// Returns a collection of the unique permutations of this sequence with
@@ -594,8 +580,6 @@ extension Collection where Element: Hashable {
/// clamped to the number of elements in this collection. Passing a range /// clamped to the number of elements in this collection. Passing a range
/// covering sizes greater than the number of elements in this collection /// covering sizes greater than the number of elements in this collection
/// results in an empty sequence. /// results in an empty sequence.
/// - Returns: A sequence of the unique permutations of this collection's
/// elements, for all sizes in `kRange`, from smallest to largest.
/// ///
/// - Complexity: O(*n*), where *n* is the number of elements in this /// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection. /// collection.
+101 -139
View File
@@ -14,11 +14,11 @@ public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product. /// The outer sequence in the product.
@usableFromInline @usableFromInline
internal let base1: Base1 internal let base1: Base1
/// The inner sequence in the product. /// The inner sequence in the product.
@usableFromInline @usableFromInline
internal let base2: Base2 internal let base2: Base2
@inlinable @inlinable
internal init(_ base1: Base1, _ base2: Base2) { internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1 self.base1 = base1
@@ -28,7 +28,7 @@ public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
extension Product2Sequence: Sequence { extension Product2Sequence: Sequence {
public typealias Element = (Base1.Element, Base2.Element) public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2Sequence` sequence. /// The iterator for a `Product2Sequence` sequence.
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
@@ -47,12 +47,10 @@ extension Product2Sequence: Sequence {
self.i2 = c.base2.makeIterator() self.i2 = c.base2.makeIterator()
self.element1 = nil self.element1 = nil
} }
@inlinable @inlinable
public mutating func next() -> ( public mutating func next() -> (Base1.Element,
Base1.Element, Base2.Element)? {
Base2.Element
)? {
// This is the initial state, where i1.next() has never // This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has // been called, or the final state, where i1.next() has
// already returned nil. // already returned nil.
@@ -61,29 +59,27 @@ extension Product2Sequence: Sequence {
// once Base1 is exhausted, return `nil` forever // once Base1 is exhausted, return `nil` forever
if element1 == nil { return nil } if element1 == nil { return nil }
} }
// Get the next element from the second sequence, if not // Get the next element from the second sequence, if not
// at end. // at end.
if let element2 = i2.next() { if let element2 = i2.next() {
// swift-format-ignore: NeverForceUnwrap
// `element1` has a nil check above.
return (element1!, element2) return (element1!, element2)
} }
// We've reached the end of the second sequence, so: // We've reached the end of the second sequence, so:
// 1) Get the next element of the first sequence, if exists // 1) Get the next element of the first sequence, if exists
// 2) Restart iteration of the second sequence // 2) Restart iteration of the second sequence
// 3) Get the first element of the second sequence, if exists // 3) Get the first element of the second sequence, if exists
element1 = i1.next() element1 = i1.next()
guard let element1 else { guard let element1 = element1
return nil else { return nil }
}
i2 = base2.makeIterator() i2 = base2.makeIterator()
guard let element2 = i2.next() else { if let element2 = i2.next() {
return (element1, element2)
} else {
return nil return nil
} }
return (element1, element2)
} }
} }
@@ -100,45 +96,43 @@ extension Product2Sequence: Collection where Base1: Collection {
internal var i1: Base1.Index internal var i1: Base1.Index
@usableFromInline @usableFromInline
internal var i2: Base2.Index internal var i2: Base2.Index
@inlinable @inlinable
internal init(i1: Base1.Index, i2: Base2.Index) { internal init(i1: Base1.Index, i2: Base2.Index) {
self.i1 = i1 self.i1 = i1
self.i2 = i2 self.i2 = i2
} }
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2) (lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
} }
} }
@inlinable @inlinable
public var count: Int { public var count: Int {
base1.count * base2.count base1.count * base2.count
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index( Index(
i1: base2.isEmpty ? base1.endIndex : base1.startIndex, i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
i2: base2.startIndex) i2: base2.startIndex)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
// `base2.startIndex` simplifies index calculations. // `base2.startIndex` simplifies index calculations.
Index(i1: base1.endIndex, i2: base2.startIndex) Index(i1: base1.endIndex, i2: base2.startIndex)
} }
@inlinable @inlinable
public subscript(position: Index) -> ( public subscript(position: Index) -> (Base1.Element,
Base1.Element, Base2.Element) {
Base2.Element
) {
(base1[position.i1], base2[position.i2]) (base1[position.i1], base2[position.i2])
} }
/// Forms an index from a pair of base indices, normalizing /// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if /// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary. /// necessary.
@@ -148,24 +142,24 @@ extension Product2Sequence: Collection where Base1: Collection {
? Index(i1: base1.index(after: i1), i2: base2.startIndex) ? Index(i1: base1.index(after: i1), i2: base2.startIndex)
: Index(i1: i1, i2: i2) : Index(i1: i1, i2: i2)
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex") precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
return normalizeIndex(i.i1, base2.index(after: i.i2)) return normalizeIndex(i.i1, base2.index(after: i.i2))
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
guard start.i1 <= end.i1 guard start.i1 <= end.i1
else { return -distance(from: end, to: start) } else { return -distance(from: end, to: start) }
guard start.i1 != end.i1 guard start.i1 != end.i1
else { return base2.distance(from: start.i2, to: end.i2) } else { return base2.distance(from: start.i2, to: end.i2) }
// The number of full cycles through `base2` between `start` and `end`, // The number of full cycles through `base2` between `start` and `end`,
// excluding the cycles that `start` and `end` are on. // excluding the cycles that `start` and `end` are on.
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1 let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
if start.i2 <= end.i2 { if start.i2 <= end.i2 {
// start.i2 // start.i2
// v // v
@@ -176,11 +170,11 @@ extension Product2Sequence: Collection where Base1: Collection {
// end.i1 > [l l l c c c c c c|r r r] // end.i1 > [l l l c c c c c c|r r r]
// ^ // ^
// end.i2 // end.i2
let left = base2[..<start.i2].count let left = base2[..<start.i2].count
let center = base2[start.i2..<end.i2].count let center = base2[start.i2..<end.i2].count
let right = base2[end.i2...].count let right = base2[end.i2...].count
return center + right return center + right
+ fullBase2Cycles * (left + center + right) + fullBase2Cycles * (left + center + right)
+ left + center + left + center
@@ -194,30 +188,30 @@ extension Product2Sequence: Collection where Base1: Collection {
// end.i1 > [l l l|c c c c c c r r r] // end.i1 > [l l l|c c c c c c r r r]
// ^ // ^
// end.i2 // end.i2
let left = base2[..<end.i2].count let left = base2[..<end.i2].count
let right = base2[start.i2...].count let right = base2[start.i2...].count
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end` // We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
// are on consecutive cycles. // are on consecutive cycles.
guard fullBase2Cycles > 0 else { return right + left } guard fullBase2Cycles > 0 else { return right + left }
let center = base2[end.i2..<start.i2].count let center = base2[end.i2..<start.i2].count
return right return right
+ fullBase2Cycles * (left + center + right) + fullBase2Cycles * (left + center + right)
+ left + left
} }
} }
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
return distance > 0 return distance > 0
? offsetForward(i, by: distance) ? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance) : offsetBackward(i, by: -distance)
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index,
@@ -238,55 +232,51 @@ extension Product2Sequence: Collection where Base1: Collection {
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit >= i) assert(limit >= i)
if limit.i1 == i.i1 { if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`. // Delegate to `base2` if the offset is limited to `i.i1`.
// //
// i.i2 limit.i2 // i.i2 limit.i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2) return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) } .map { i2 in Index(i1: i.i1, i2: i2) }
} }
if let i2 =
base2 if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex)
{
// `distance` does not overflow `base2[i.i2...]`. // `distance` does not overflow `base2[i.i2...]`.
// //
// i.i2 i2 // i.i2 i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
// [ |> > > > > >| ] (`distance`) // [ |> > > > > >| ] (`distance`)
return normalizeIndex(i.i1, i2) return normalizeIndex(i.i1, i2)
} }
let suffixCount = base2[i.i2...].count let suffixCount = base2[i.i2...].count
let remaining = distance - suffixCount let remaining = distance - suffixCount
let nextI1 = base1.index(after: i.i1) let nextI1 = base1.index(after: i.i1)
if limit.i1 == nextI1 { if limit.i1 == nextI1 {
// Delegate to `base2` if the offset is limited to `nextI1`. // Delegate to `base2` if the offset is limited to `nextI1`.
// //
@@ -296,17 +286,12 @@ extension Product2Sequence: Collection where Base1: Collection {
// nextI1 > [x x x x x x x x x|x x x] // nextI1 > [x x x x x x x x x|x x x]
// ^ // ^
// limit.i2 // limit.i2
return return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
base2
.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: nextI1, i2: i2) } .map { i2 in Index(i1: nextI1, i2: i2) }
} }
if let i2 = if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
base2
.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2)
{
// `remaining` does not overflow `base2[..<i.i2]`. // `remaining` does not overflow `base2[..<i.i2]`.
// //
// i.i2 // i.i2
@@ -317,66 +302,58 @@ extension Product2Sequence: Collection where Base1: Collection {
// nextI1 > [x x x|x x x x x x x x x] // nextI1 > [x x x|x x x x x x x x x]
// ^ // ^
// i2 // i2
return Index(i1: nextI1, i2: i2) return Index(i1: nextI1, i2: i2)
} }
let prefixCount = base2[..<i.i2].count let prefixCount = base2[..<i.i2].count
let base2Count = prefixCount + suffixCount let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count let base1Distance = remaining / base2Count
guard guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1) else { return nil }
else { return nil }
// The distance from `base2.startIndex` to the target. // The distance from `base2.startIndex` to the target.
let base2Distance = remaining % base2Count let base2Distance = remaining % base2Count
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
return return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
base2
.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) } .map { i2 in Index(i1: i1, i2: i2) }
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance >= 0) assert(distance >= 0)
assert(limit <= i) assert(limit <= i)
if limit.i1 == i.i1 { if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`. // Delegate to `base2` if the offset is limited to `i.i1`.
// //
// limit.i2 i.i2 // limit.i2 i.i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2) return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) } .map { i2 in Index(i1: i.i1, i2: i2) }
} }
if let i2 = if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
base2
.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex)
{
// `distance` does not underflow `base2[..<i.i2]`. // `distance` does not underflow `base2[..<i.i2]`.
// //
// i2 i.i2 // i2 i.i2
// v v // v v
// i.i1 > [x x x|x x x x x x|x x x] // i.i1 > [x x x|x x x x x x|x x x]
// [ |< < < < < <| ] (`distance`) // [ |< < < < < <| ] (`distance`)
return Index(i1: i.i1, i2: i2) return Index(i1: i.i1, i2: i2)
} }
let prefixCount = base2[..<i.i2].count let prefixCount = base2[..<i.i2].count
let remaining = distance - prefixCount let remaining = distance - prefixCount
let previousI1 = base1.index(i.i1, offsetBy: -1) let previousI1 = base1.index(i.i1, offsetBy: -1)
if limit.i1 == previousI1 { if limit.i1 == previousI1 {
// Delegate to `base2` if the offset is limited to `previousI1`. // Delegate to `base2` if the offset is limited to `previousI1`.
// //
@@ -386,17 +363,12 @@ extension Product2Sequence: Collection where Base1: Collection {
// i.i1 > [x x x x x x x x x|x x x] // i.i1 > [x x x x x x x x x|x x x]
// ^ // ^
// i.i2 // i.i2
return return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
base2
.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: previousI1, i2: i2) } .map { i2 in Index(i1: previousI1, i2: i2) }
} }
if let i2 = if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
base2
.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2)
{
// `remaining` does not underflow `base2[i.i2...]`. // `remaining` does not underflow `base2[i.i2...]`.
// //
// i2 // i2
@@ -407,17 +379,17 @@ extension Product2Sequence: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x] // i.i1 > [x x x|x x x x x x x x x]
// ^ // ^
// i.i2 // i.i2
return Index(i1: previousI1, i2: i2) return Index(i1: previousI1, i2: i2)
} }
let suffixCount = base2[i.i2...].count let suffixCount = base2[i.i2...].count
let base2Count = prefixCount + suffixCount let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count let base1Distance = remaining / base2Count
// The distance from `base2.endIndex` to the target. // The distance from `base2.endIndex` to the target.
let base2Distance = remaining % base2Count let base2Distance = remaining % base2Count
if base2Distance == 0 { if base2Distance == 0 {
// We end up exactly between two cycles, so `base1Distance` would // We end up exactly between two cycles, so `base1Distance` would
// overshoot the target by 1. // overshoot the target by 1.
@@ -430,54 +402,46 @@ extension Product2Sequence: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x] // i.i1 > [x x x|x x x x x x x x x]
// ^ // ^
// i.i2 // i.i2
guard if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
let i1 = base1.index( let index = Index(i1: i1, i2: base2.startIndex)
previousI1, return index < limit ? nil : index
offsetBy: -(base1Distance - 1), } else {
limitedBy: limit.i1)
else {
return nil return nil
} }
let index = Index(i1: i1, i2: base2.startIndex)
return index < limit ? nil : index
} }
guard guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
let i1 = else { return nil }
base1
.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
else { return nil }
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
return return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
base2
.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) } .map { i2 in Index(i1: i1, i2: i2) }
} }
} }
extension Product2Sequence: BidirectionalCollection extension Product2Sequence: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection { where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition( precondition(i != startIndex,
i != startIndex, "Can't move before startIndex")
"Can't move before startIndex") if i.i2 == base2.startIndex {
guard i.i2 == base2.startIndex else { return Index(
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
} else {
return Index(i1: i.i1, i2: base2.index(before: i.i2)) return Index(i1: i.i1, i2: base2.index(before: i.i2))
} }
return Index(
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
} }
} }
extension Product2Sequence: RandomAccessCollection extension Product2Sequence: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2Sequence.Index: Hashable extension Product2Sequence.Index: Hashable
where Base1.Index: Hashable, Base2.Index: Hashable {} where Base1.Index: Hashable, Base2.Index: Hashable {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// product(_:_:) // product(_:_:)
@@ -490,6 +454,7 @@ where Base1.Index: Hashable, Base2.Index: Hashable {}
/// element of the tuple is from the first collection and the second element is /// element of the tuple is from the first collection and the second element is
/// from the second collection. /// from the second collection.
/// ///
///
/// let numbers = 1...3 /// let numbers = 1...3
/// let colors = ["cerise", "puce", "heliotrope"] /// let colors = ["cerise", "puce", "heliotrope"]
/// for (number, color) in product(numbers, colors) { /// for (number, color) in product(numbers, colors) {
@@ -513,14 +478,11 @@ where Base1.Index: Hashable, Base2.Index: Hashable {}
/// - Parameters: /// - Parameters:
/// - s1: The first sequence to iterate over. /// - s1: The first sequence to iterate over.
/// - s2: The second sequence to iterate over. /// - s2: The second sequence to iterate over.
/// - Returns: A sequence of tuples, with every combination of the elements
/// of `s1` and `s2`, in order.
/// ///
/// - Complexity: O(1) /// - Complexity: O(1)
@inlinable @inlinable
public func product<Base1: Sequence, Base2: Collection>( public func product<Base1: Sequence, Base2: Collection>(
_ s1: Base1, _ s1: Base1, _ s2: Base2
_ s2: Base2
) -> Product2Sequence<Base1, Base2> { ) -> Product2Sequence<Base1, Base2> {
Product2Sequence(s1, s2) Product2Sequence(s1, s2)
} }
+27 -31
View File
@@ -18,7 +18,7 @@ extension Double {
internal static func root(_ x: Double, _ n: Int) -> Double { internal static func root(_ x: Double, _ n: Int) -> Double {
guard x >= 0 || n % 2 != 0 else { return .nan } guard x >= 0 || n % 2 != 0 else { return .nan }
if n == 3 { return cbrt(x) } if n == 3 { return cbrt(x) }
return Double(signOf: x, magnitudeOf: pow(x.magnitude, 1 / Double(n))) return Double(signOf: x, magnitudeOf: pow(x.magnitude, 1/Double(n)))
} }
@_transparent @_transparent
@@ -36,7 +36,8 @@ internal import RealModule
#elseif swift(>=5.10) #elseif swift(>=5.10)
import RealModule import RealModule
#else #else
@_implementationOnly import RealModule @_implementationOnly
import RealModule
#endif #endif
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@@ -56,17 +57,16 @@ extension Collection {
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable
public func randomStableSample<G: RandomNumberGenerator>( public func randomStableSample<G: RandomNumberGenerator>(
count k: Int, count k: Int, using rng: inout G
using rng: inout G
) -> [Element] { ) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var remainingCount = count var remainingCount = count
guard k < remainingCount else { return Array(self) } guard k < remainingCount else { return Array(self) }
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
var i = startIndex var i = startIndex
var countToSelect = k var countToSelect = k
while countToSelect > 0 { while countToSelect > 0 {
@@ -79,10 +79,10 @@ extension Collection {
formIndex(after: &i) formIndex(after: &i)
remainingCount -= 1 remainingCount -= 1
} }
return result return result
} }
/// Randomly selects the specified number of elements from this collection, /// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order. /// maintaining their relative order.
/// ///
@@ -111,16 +111,14 @@ extension Collection {
@usableFromInline @usableFromInline
internal func nextW<G: RandomNumberGenerator>( internal func nextW<G: RandomNumberGenerator>(
k: Int, k: Int, using rng: inout G
using rng: inout G
) -> Double { ) -> Double {
Double.root(.random(in: 0..<1, using: &rng), k) Double.root(.random(in: 0..<1, using: &rng), k)
} }
@usableFromInline @usableFromInline
internal func nextOffset<G: RandomNumberGenerator>( internal func nextOffset<G: RandomNumberGenerator>(
w: Double, w: Double, using rng: inout G
using rng: inout G
) -> Int { ) -> Int {
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w) let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
return offset < Double(Int.max) ? Int(offset) : Int.max return offset < Double(Int.max) ? Int(offset) : Int.max
@@ -141,30 +139,29 @@ extension Collection {
/// where *n* is the length of the collection. /// where *n* is the length of the collection.
@inlinable @inlinable
public func randomSample<G: RandomNumberGenerator>( public func randomSample<G: RandomNumberGenerator>(
count k: Int, count k: Int, using rng: inout G
using rng: inout G
) -> [Element] { ) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var w = 1.0 var w = 1.0
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements. // Fill the reservoir with the first `k` elements.
var i = startIndex var i = startIndex
while i != endIndex, result.count < k { while i != endIndex, result.count < k {
result.append(self[i]) result.append(self[i])
formIndex(after: &i) formIndex(after: &i)
} }
while i != endIndex { while i != endIndex {
// Calculate the next value of w. // Calculate the next value of w.
w *= nextW(k: k, using: &rng) w *= nextW(k: k, using: &rng)
// Find index of the next element to swap into the reservoir. // Find index of the next element to swap into the reservoir.
let offset = nextOffset(w: w, using: &rng) let offset = nextOffset(w: w, using: &rng)
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
if i != endIndex { if i != endIndex {
// Swap selected element with a randomly chosen one in the reservoir. // Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng) let j = Int.random(in: 0..<result.count, using: &rng)
@@ -172,12 +169,12 @@ extension Collection {
formIndex(after: &i) formIndex(after: &i)
} }
} }
// FIXME: necessary? // FIXME: necessary?
result.shuffle(using: &rng) result.shuffle(using: &rng)
return result return result
} }
/// Randomly selects the specified number of elements from this collection. /// Randomly selects the specified number of elements from this collection.
/// ///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in /// This method is equivalent to calling `randomSample(k:using:)`, passing in
@@ -211,15 +208,14 @@ extension Sequence {
/// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable @inlinable
public func randomSample<G: RandomNumberGenerator>( public func randomSample<G: RandomNumberGenerator>(
count k: Int, count k: Int, using rng: inout G
using rng: inout G
) -> [Element] { ) -> [Element] {
guard k > 0 else { return [] } guard k > 0 else { return [] }
var w = 1.0 var w = 1.0
var result: [Element] = [] var result: [Element] = []
result.reserveCapacity(k) result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements. // Fill the reservoir with the first `k` elements.
var iterator = makeIterator() var iterator = makeIterator()
while result.count < k, let el = iterator.next() { while result.count < k, let el = iterator.next() {
@@ -229,26 +225,26 @@ extension Sequence {
while true { while true {
// Calculate the next value of w. // Calculate the next value of w.
w *= nextW(k: k, using: &rng) w *= nextW(k: k, using: &rng)
// Find the offset of the next element to swap into the reservoir. // Find the offset of the next element to swap into the reservoir.
var offset = nextOffset(w: w, using: &rng) var offset = nextOffset(w: w, using: &rng)
// Skip over `offset` elements to find the selected element. // Skip over `offset` elements to find the selected element.
while offset > 0, iterator.next() != nil { while offset > 0, let _ = iterator.next() {
offset -= 1 offset -= 1
} }
guard let nextElement = iterator.next() else { break } guard let nextElement = iterator.next() else { break }
// Swap selected element with a randomly chosen one in the reservoir. // Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng) let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = nextElement result[j] = nextElement
} }
// FIXME: necessary? // FIXME: necessary?
result.shuffle(using: &rng) result.shuffle(using: &rng)
return result return result
} }
/// Randomly selects the specified number of elements from this sequence. /// Randomly selects the specified number of elements from this sequence.
/// ///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in /// This method is equivalent to calling `randomSample(k:using:)`, passing in
+19 -18
View File
@@ -161,7 +161,7 @@ extension Sequence {
_ transform: (inout Result, Element) throws -> Void _ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] { ) rethrows -> [Result] {
var output: [Result] = [] var output = [Result]()
output.reserveCapacity(underestimatedCount + 1) output.reserveCapacity(underestimatedCount + 1)
output.append(initial) output.append(initial)
@@ -249,7 +249,7 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
case base(Base.Index, Result) case base(Base.Index, Result)
case end case end
} }
@usableFromInline @usableFromInline
internal let representation: Representation internal let representation: Representation
@@ -257,7 +257,7 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
internal init(_ representation: Representation) { internal init(_ representation: Representation) {
self.representation = representation self.representation = representation
} }
@inlinable @inlinable
public static func == (lhs: Self, rhs: Self) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) { switch (lhs.representation, rhs.representation) {
@@ -269,7 +269,7 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
return false return false
} }
} }
@inlinable @inlinable
public static func < (lhs: Self, rhs: Self) -> Bool { public static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs.representation, rhs.representation) { switch (lhs.representation, rhs.representation) {
@@ -319,11 +319,11 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) { switch (start.representation, end.representation) {
case (.base(let start, _), .base(let end, _)): case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end) return base.distance(from: start, to: end)
case (.base(let index, _), .end): case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex) + 1 return base.distance(from: index, to: base.endIndex) + 1
case (.end, .base(let index, _)): case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index) - 1 return base.distance(from: base.endIndex, to: index) - 1
case (.end, .end): case (.end, .end):
return 0 return 0
@@ -334,10 +334,11 @@ extension ExclusiveReductionsSequence: Collection where Base: Collection {
extension ExclusiveReductionsSequence: LazySequenceProtocol {} extension ExclusiveReductionsSequence: LazySequenceProtocol {}
extension ExclusiveReductionsSequence: LazyCollectionProtocol extension ExclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {} where Base: Collection {}
extension ExclusiveReductionsSequence.Index: Hashable extension ExclusiveReductionsSequence.Index: Hashable
where Base.Index: Hashable { where Base.Index: Hashable
{
@inlinable @inlinable
public func hash(into hasher: inout Hasher) { public func hash(into hasher: inout Hasher) {
switch representation { switch representation {
@@ -482,7 +483,7 @@ extension InclusiveReductionsSequence: Collection where Base: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal let base: Base.Index internal let base: Base.Index
@usableFromInline @usableFromInline
internal let result: Element? internal let result: Element?
@@ -496,7 +497,7 @@ extension InclusiveReductionsSequence: Collection where Base: Collection {
public static func < (lhs: Self, rhs: Self) -> Bool { public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.base < rhs.base lhs.base < rhs.base
} }
@inlinable @inlinable
public static func == (lhs: Self, rhs: Self) -> Bool { public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.base == rhs.base lhs.base == rhs.base
@@ -518,7 +519,7 @@ extension InclusiveReductionsSequence: Collection where Base: Collection {
guard let result = index.result else { guard let result = index.result else {
fatalError("Can't subscript using endIndex") fatalError("Can't subscript using endIndex")
} }
return result return result
} }
@@ -527,13 +528,12 @@ extension InclusiveReductionsSequence: Collection where Base: Collection {
guard let result = index.result else { guard let result = index.result else {
fatalError("Can't advance past endIndex") fatalError("Can't advance past endIndex")
} }
let index = base.index(after: index.base) let index = base.index(after: index.base)
let nextResult = let nextResult = index == base.endIndex
index == base.endIndex
? nil ? nil
: transform(result, base[index]) : transform(result, base[index])
return Index(base: index, result: nextResult) return Index(base: index, result: nextResult)
} }
@@ -546,10 +546,11 @@ extension InclusiveReductionsSequence: Collection where Base: Collection {
extension InclusiveReductionsSequence: LazySequenceProtocol {} extension InclusiveReductionsSequence: LazySequenceProtocol {}
extension InclusiveReductionsSequence: LazyCollectionProtocol extension InclusiveReductionsSequence: LazyCollectionProtocol
where Base: Collection {} where Base: Collection {}
extension InclusiveReductionsSequence.Index: Hashable extension InclusiveReductionsSequence.Index: Hashable
where Base.Index: Hashable { where Base.Index: Hashable
{
@inlinable @inlinable
public func hash(into hasher: inout Hasher) { public func hash(into hasher: inout Hasher) {
hasher.combine(base) hasher.combine(base)
+20 -26
View File
@@ -15,10 +15,8 @@
extension MutableCollection where Self: BidirectionalCollection { extension MutableCollection where Self: BidirectionalCollection {
/// Reverses the elements of the collection, moving from each end until /// Reverses the elements of the collection, moving from each end until
/// `limit` is reached from either direction. /// `limit` is reached from either direction. The returned indices are the
/// /// start and end of the range of unreversed elements.
/// The returned indices are the start and end of the range of unreversed
/// elements.
/// ///
/// Input: /// Input:
/// [a b c d e f g h i j k l m n o p] /// [a b c d e f g h i j k l m n o p]
@@ -30,12 +28,11 @@ extension MutableCollection where Self: BidirectionalCollection {
/// lower upper /// lower upper
/// ///
/// - Postcondition: For returned indices `(lower, upper)`: /// - Postcondition: For returned indices `(lower, upper)`:
/// `lower == limit || upper == limit`. /// `lower == limit || upper == limit`
@inlinable @inlinable
@discardableResult @discardableResult
internal mutating func _reverse( internal mutating func _reverse(
subrange: Range<Index>, subrange: Range<Index>, until limit: Index
until limit: Index
) -> (Index, Index) { ) -> (Index, Index) {
var lower = subrange.lowerBound var lower = subrange.lowerBound
var upper = subrange.upperBound var upper = subrange.upperBound
@@ -46,7 +43,7 @@ extension MutableCollection where Self: BidirectionalCollection {
} }
return (lower, upper) return (lower, upper)
} }
/// Reverses the elements within the given subrange. /// Reverses the elements within the given subrange.
/// ///
/// This example reverses the numbers within the subrange at the start of the /// This example reverses the numbers within the subrange at the start of the
@@ -78,10 +75,8 @@ extension MutableCollection where Self: BidirectionalCollection {
extension MutableCollection { extension MutableCollection {
/// Swaps the elements of the two given subranges, up to the upper bound of /// Swaps the elements of the two given subranges, up to the upper bound of
/// the smaller subrange. /// the smaller subrange. The returned indices are the ends of the two ranges
/// /// that were actually swapped.
/// The returned indices are the ends of the two ranges that were actually
/// swapped.
/// ///
/// Input: /// Input:
/// [a b c d e f g h i j k l m n o p] /// [a b c d e f g h i j k l m n o p]
@@ -101,19 +96,19 @@ extension MutableCollection {
/// - p == lhs.upperBound || q == rhs.upperBound /// - p == lhs.upperBound || q == rhs.upperBound
@inlinable @inlinable
internal mutating func _swapNonemptySubrangePrefixes( internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ lhs: Range<Index>, _ rhs: Range<Index>
_ rhs: Range<Index>
) -> (Index, Index) { ) -> (Index, Index) {
assert(!lhs.isEmpty) assert(!lhs.isEmpty)
assert(!rhs.isEmpty) assert(!rhs.isEmpty)
var p = lhs.lowerBound var p = lhs.lowerBound
var q = rhs.lowerBound var q = rhs.lowerBound
repeat { repeat {
swapAt(p, q) swapAt(p, q)
formIndex(after: &p) formIndex(after: &p)
formIndex(after: &q) formIndex(after: &q)
} while p != lhs.upperBound && q != rhs.upperBound }
while p != lhs.upperBound && q != rhs.upperBound
return (p, q) return (p, q)
} }
@@ -144,14 +139,13 @@ extension MutableCollection {
subrange: Range<Index>, subrange: Range<Index>,
toStartAt newStart: Index toStartAt newStart: Index
) -> Index { ) -> Index {
var m = newStart var m = newStart, s = subrange.lowerBound
var s = subrange.lowerBound
let e = subrange.upperBound let e = subrange.upperBound
// Handle the trivial cases // Handle the trivial cases
if s == m { return e } if s == m { return e }
if m == e { return s } if m == e { return s }
// We have two regions of possibly-unequal length that need to be exchanged. // We have two regions of possibly-unequal length that need to be exchanged.
// The return value of this method is going to be the position following // The return value of this method is going to be the position following
// that of the element that is currently last (element j). // that of the element that is currently last (element j).
@@ -160,7 +154,7 @@ extension MutableCollection {
// ^ ^ ^ ^ ^ ^ // ^ ^ ^ ^ ^ ^
// s m e s m e // s m e s m e
// //
var ret = e // start with a known incorrect result. var ret = e // start with a known incorrect result.
while true { while true {
// Exchange the leading elements of each region (up to the length of the // Exchange the leading elements of each region (up to the length of the
// shorter region). // shorter region).
@@ -172,7 +166,7 @@ extension MutableCollection {
// s s1 m m1/e s s1/m m1 e // s s1 m m1/e s s1/m m1 e
// //
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e) let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
if m1 == e { if m1 == e {
// Left-hand case: we have moved element j into position. If we haven't // Left-hand case: we have moved element j into position. If we haven't
// already, we can capture the return value which is in s1. // already, we can capture the return value which is in s1.
@@ -181,11 +175,11 @@ extension MutableCollection {
// once the return value is known. I'm not sure it's a worthwhile // once the return value is known. I'm not sure it's a worthwhile
// optimization, though. // optimization, though.
if ret == e { ret = s1 } if ret == e { ret = s1 }
// If both regions were the same size, we're done. // If both regions were the same size, we're done.
if s1 == m { break } if s1 == m { break }
} }
// Now we have a smaller problem that is also a rotation, so we can adjust // Now we have a smaller problem that is also a rotation, so we can adjust
// our bounds and repeat. // our bounds and repeat.
// //
@@ -195,10 +189,10 @@ extension MutableCollection {
s = s1 s = s1
if s == m { m = m1 } if s == m { m = m1 }
} }
return ret return ret
} }
/// Rotates the elements of this collection so that the element at the /// Rotates the elements of this collection so that the element at the
/// specified index becomes the start of the collection. /// specified index becomes the start of the collection.
/// ///
+12 -11
View File
@@ -86,7 +86,7 @@ extension SplitSequence: Sequence {
self.omittingEmptySubsequences = omittingEmptySubsequences self.omittingEmptySubsequences = omittingEmptySubsequences
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator( Iterator(
@@ -101,25 +101,25 @@ extension SplitSequence: Sequence {
extension SplitSequence.Iterator: IteratorProtocol { extension SplitSequence.Iterator: IteratorProtocol {
@inlinable @inlinable
public mutating func next() -> Element? { public mutating func next() -> Element? {
var nextElement = base.next() var currentElement = base.next()
var subsequence: Element = [] var subsequence: Element = []
// Add the next elements of the base sequence to this subsequence, until we // 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 // reach a separator, unless we've already split the maximum number of
// times. In all cases, stop at the end of the base sequence. // times. In all cases, stop at the end of the base sequence.
while let currentElement = nextElement { while currentElement != nil {
if splitCount < maxSplits && isSeparator(currentElement) { if splitCount < maxSplits && isSeparator(currentElement!) {
if omittingEmptySubsequences && subsequence.isEmpty { if omittingEmptySubsequences && subsequence.isEmpty {
// Keep going if we don't want to return an empty subsequence. // Keep going if we don't want to return an empty subsequence.
nextElement = base.next() currentElement = base.next()
continue continue
} else { } else {
splitCount += 1 splitCount += 1
break break
} }
} else { } else {
subsequence.append(currentElement) subsequence.append(currentElement!)
nextElement = base.next() currentElement = base.next()
} }
} }
@@ -127,7 +127,7 @@ extension SplitSequence.Iterator: IteratorProtocol {
// and we've either returned the maximum number of subsequences (one more // 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 // than the number of separators), or the only subsequence left to return is
// empty and we're omitting those. // empty and we're omitting those.
if nextElement == nil if currentElement == nil
&& (sequenceLength == splitCount + 1 && (sequenceLength == splitCount + 1
|| omittingEmptySubsequences && subsequence.isEmpty) || omittingEmptySubsequences && subsequence.isEmpty)
{ {
@@ -219,7 +219,7 @@ extension LazySequenceProtocol {
/// satisfying the `isSeparator` predicate and for each element at the /// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the sequence satisfying the `isSeparator` /// start or end of the sequence satisfying the `isSeparator`
/// predicate. The default value is `true`. /// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and /// - whereSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the sequence should be /// returns a Boolean value indicating whether the sequence should be
/// split at that element. /// split at that element.
/// - Returns: A lazy sequence of subsequences, split from this sequence's /// - Returns: A lazy sequence of subsequences, split from this sequence's
@@ -634,7 +634,7 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
/// satisfying the `isSeparator` predicate and for each element at the /// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator` /// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`. /// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and /// - whereSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be /// returns a Boolean value indicating whether the collection should be
/// split at that element. /// split at that element.
/// - Returns: A lazy collection of subsequences, split from this collection's /// - Returns: A lazy collection of subsequences, split from this collection's
@@ -659,7 +659,8 @@ extension LazySequenceProtocol where Self: Collection, Elements: Collection {
} }
extension LazySequenceProtocol extension LazySequenceProtocol
where Self: Collection, Elements: Collection, Element: Equatable { where Self: Collection, Elements: Collection, Element: Equatable
{
/// Lazily returns the longest possible subsequences of the collection, in /// Lazily returns the longest possible subsequences of the collection, in
/// order, around elements equal to the given element. /// order, around elements equal to the given element.
/// ///
+51 -57
View File
@@ -15,7 +15,7 @@
extension Sequence { extension Sequence {
/// Returns a sequence stepping through the elements every `step` starting at /// Returns a sequence stepping through the elements every `step` starting at
/// the first value. /// 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: 2) // == [0, 2, 4, 6, 8, 10]
/// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// (0...10).striding(by: 3) // == [0, 3, 6, 9]
@@ -24,9 +24,8 @@ extension Sequence {
/// striding `step`. /// striding `step`.
/// ///
/// - Parameter step: The amount to step with each iteration. /// - Parameter step: The amount to step with each iteration.
/// - Returns: A sequence for stepping through the elements by the specified /// - Returns: Returns a sequence for stepping through the elements by the
/// amount. Any remaining elements after the last multiple of the stride /// specified amount.
/// are omitted.
@inlinable @inlinable
public func striding(by step: Int) -> StridingSequence<Self> { public func striding(by step: Int) -> StridingSequence<Self> {
StridingSequence(base: self, stride: step) StridingSequence(base: self, stride: step)
@@ -35,18 +34,18 @@ extension Sequence {
extension Collection { extension Collection {
/// Returns a sequence stepping through the elements every `step` starting at /// Returns a sequence stepping through the elements every `step` starting at
/// the first value. /// 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: 2) // == [0, 2, 4, 6, 8, 10]
/// (0...10).striding(by: 3) // == [0, 3, 6, 9] /// (0...10).striding(by: 3) // == [0, 3, 6, 9]
/// ///
/// - Complexity: O(1). Access to successive values is O(k) where _k_ is the /// - Complexity: O(1). Access to successive values is O(1) if the collection
/// striding `step`. /// conforms to `RandomAccessCollection`; otherwise, O(_k_), where _k_ is
/// the striding `step`.
/// ///
/// - Parameter step: The amount to step with each iteration. /// - Parameter step: The amount to step with each iteration.
/// - Returns: A sequence for stepping through the elements by the specified /// - Returns: Returns a collection for stepping through the elements by the
/// amount. Any remaining elements after the last multiple of the stride /// specified amount.
/// are omitted.
@inlinable @inlinable
public func striding(by step: Int) -> StridingCollection<Self> { public func striding(by step: Int) -> StridingCollection<Self> {
StridingCollection(base: self, stride: step) StridingCollection(base: self, stride: step)
@@ -57,10 +56,10 @@ extension Collection {
public struct StridingSequence<Base: Sequence> { public struct StridingSequence<Base: Sequence> {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let stride: Int internal let stride: Int
@inlinable @inlinable
internal init(base: Base, stride: Int) { internal init(base: Base, stride: Int) {
precondition(stride > 0, "Stride must be greater than zero") precondition(stride > 0, "Stride must be greater than zero")
@@ -81,19 +80,19 @@ extension StridingSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var iterator: Base.Iterator internal var iterator: Base.Iterator
@usableFromInline @usableFromInline
internal let stride: Int internal let stride: Int
@usableFromInline @usableFromInline
internal var striding: Bool = false internal var striding: Bool = false
@inlinable @inlinable
internal init(iterator: Base.Iterator, stride: Int) { internal init(iterator: Base.Iterator, stride: Int) {
self.iterator = iterator self.iterator = iterator
self.stride = stride self.stride = stride
} }
@inlinable @inlinable
public mutating func next() -> Base.Element? { public mutating func next() -> Base.Element? {
guard striding else { guard striding else {
@@ -106,7 +105,7 @@ extension StridingSequence: Sequence {
return iterator.next() return iterator.next()
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), stride: stride) Iterator(iterator: base.makeIterator(), stride: stride)
@@ -114,16 +113,16 @@ extension StridingSequence: Sequence {
} }
extension StridingSequence: LazySequenceProtocol extension StridingSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
/// A wrapper that strides over a base collection. /// A wrapper that strides over a base collection.
public struct StridingCollection<Base: Collection> { public struct StridingCollection<Base: Collection> {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let stride: Int internal let stride: Int
@inlinable @inlinable
internal init(base: Base, stride: Int) { internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero") precondition(stride > 0, "striding must be greater than zero")
@@ -144,39 +143,39 @@ extension StridingCollection: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal let base: Base.Index internal let base: Base.Index
@usableFromInline @usableFromInline
internal init(_ base: Base.Index) { internal init(_ base: Base.Index) {
self.base = base self.base = base
} }
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base lhs.base < rhs.base
} }
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
Index(base.startIndex) Index(base.startIndex)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(base.endIndex) Index(base.endIndex)
} }
@inlinable @inlinable
public subscript(i: Index) -> Base.Element { public subscript(i: Index) -> Base.Element {
base[i.base] base[i.base]
} }
@inlinable @inlinable
public func index(after i: Index) -> Index { public func index(after i: Index) -> Index {
precondition(i.base != base.endIndex, "Advancing past end index") precondition(i.base != base.endIndex, "Advancing past end index")
return index(i, offsetBy: 1) return index(i, offsetBy: 1)
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index,
@@ -185,12 +184,12 @@ extension StridingCollection: Collection {
) -> Index? { ) -> Index? {
guard n != 0 else { return i } guard n != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
return n > 0 return n > 0
? offsetForward(i, offsetBy: n, limitedBy: limit) ? offsetForward(i, offsetBy: n, limitedBy: limit)
: offsetBackward(i, offsetBy: -n, limitedBy: limit) : offsetBackward(i, offsetBy: -n, limitedBy: limit)
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index,
@@ -198,17 +197,16 @@ extension StridingCollection: Collection {
limitedBy limit: Index limitedBy limit: Index
) -> Index? { ) -> Index? {
if limit < i { if limit < i {
guard if let idx = base.index(
let idx = base.index( i.base,
i.base, offsetBy: n * stride,
offsetBy: n * stride, limitedBy: base.endIndex
limitedBy: base.endIndex ) {
) return Index(idx)
else { } else {
assert(distance(from: i, to: endIndex) == n, "Advancing past end index") assert(distance(from: i, to: endIndex) == n, "Advancing past end index")
return endIndex return endIndex
} }
return Index(idx)
} else if let idx = base.index( } else if let idx = base.index(
i.base, i.base,
offsetBy: n * stride, offsetBy: n * stride,
@@ -221,7 +219,7 @@ extension StridingCollection: Collection {
: nil : nil
} }
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index,
@@ -238,41 +236,37 @@ extension StridingCollection: Collection {
distance = n * -stride distance = n * -stride
} }
return base.index( return base.index(
i.base, i.base,
offsetBy: distance, offsetBy: distance,
limitedBy: limit.base limitedBy: limit.base
).map(Index.init) ).map(Index.init)
} }
@inlinable @inlinable
public var count: Int { public var count: Int {
base.isEmpty ? 0 : (base.count - 1) / stride + 1 base.isEmpty ? 0 : (base.count - 1) / stride + 1
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
let distance = base.distance(from: start.base, to: end.base) let distance = base.distance(from: start.base, to: end.base)
return distance / stride + (distance % stride).signum() return distance / stride + (distance % stride).signum()
} }
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition( precondition(distance <= 0 || i.base != base.endIndex, "Advancing past end index")
distance <= 0 || i.base != base.endIndex, "Advancing past end index") precondition(distance >= 0 || i.base != base.startIndex, "Incrementing past start index")
precondition(
distance >= 0 || i.base != base.startIndex,
"Incrementing past start index")
let limit = distance > 0 ? endIndex : startIndex let limit = distance > 0 ? endIndex : startIndex
guard let idx = index(i, offsetBy: distance, limitedBy: limit) else { let idx = index(i, offsetBy: distance, limitedBy: limit)
preconditionFailure( precondition(idx != nil, "The distance \(distance) is not valid for this collection")
"The distance \(distance) is not valid for this collection") return idx!
}
return idx
} }
} }
extension StridingCollection: BidirectionalCollection extension StridingCollection: BidirectionalCollection
where Base: RandomAccessCollection { where Base: RandomAccessCollection {
@inlinable @inlinable
public func index(before i: Index) -> Index { public func index(before i: Index) -> Index {
precondition(i.base != base.startIndex, "Incrementing past start index") precondition(i.base != base.startIndex, "Incrementing past start index")
@@ -281,9 +275,9 @@ where Base: RandomAccessCollection {
} }
extension StridingCollection: RandomAccessCollection extension StridingCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol extension StridingCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension StridingCollection.Index: Hashable where Base.Index: Hashable {} extension StridingCollection.Index: Hashable where Base.Index: Hashable {}
+2 -9
View File
@@ -14,16 +14,13 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension BidirectionalCollection { extension BidirectionalCollection {
/// Returns a subsequence containing the suffix of this collection where /// Returns a subsequence containing the elements from the end until
/// all elements pass the given closure. /// `predicate` returns `false` and skipping the remaining elements.
/// ///
/// - Parameter predicate: A closure that takes an element of the sequence as /// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns `true` if the element should be included or /// its argument and returns `true` if the element should be included or
/// `false` if it should be excluded. Once the predicate returns `false` it /// `false` if it should be excluded. Once the predicate returns `false` it
/// will not be called again. /// will not be called again.
/// - Returns: A subsequence that is a suffix of the collection, where
/// `predicate` returns `true` for all the elements of the returned
/// subsequence.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable
@@ -46,8 +43,6 @@ extension Collection {
/// as its argument and returns `true` if the element is part of the prefix /// 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 /// or `false` if it is not. Once the predicate returns `false` it will not
/// be called again. /// be called again.
/// - Returns: The index of the first element for which `predicate` does not
/// succeed, or `endIndex` if all the collection's elements pass.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable
@@ -74,8 +69,6 @@ extension BidirectionalCollection {
/// as its argument and returns `true` if the element is part of the suffix /// 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 /// or `false` if it is not. Once the predicate returns `false` it will not
/// be called again. /// be called again.
/// - Returns: The index of the last element for which `predicate` does not
/// succeed, or `startIndex` if all the collection's elements pass.
/// ///
/// - Complexity: O(*n*), where *n* is the length of the collection. /// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable @inlinable
+34 -36
View File
@@ -7,7 +7,6 @@
// //
// See https://swift.org/LICENSE.txt for license information // See https://swift.org/LICENSE.txt for license information
// //
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// trimmingPrefix(while:) // trimmingPrefix(while:)
@@ -15,21 +14,19 @@
extension Collection { extension Collection {
/// Returns a `SubSequence` formed by discarding all elements at the start of /// Returns a `SubSequence` formed by discarding all elements at the start of
/// the collection that satisfy the given predicate. /// the collection which satisfy the given predicate.
/// ///
/// This example uses `trimmingPrefix(while:)` to get a substring without the /// This example uses `trimmingPrefix(while:)` to get a substring without the
/// white space at the beginning of the string: /// white space at the beginning of the string:
/// ///
/// let myString = " hello, world " /// let myString = " hello, world "
/// print(myString.trimmingPrefix(while: \.isWhitespace)) /// print(myString.trimmingPrefix(while: \.isWhitespace)) // "hello, world "
/// // Prints "hello, world "
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// omitted from the result. /// omitted from the resulting slice.
/// - Returns: A subsequence of this collection, starting at the first element
/// for which `predicate` returns `false`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public func trimmingPrefix( public func trimmingPrefix(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
@@ -44,7 +41,7 @@ extension Collection {
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
extension Collection where Self: RangeReplaceableCollection { extension Collection where Self: RangeReplaceableCollection {
/// Mutates the collection by discarding all elements at the start that /// Mutates a `Collection` by discarding all elements at the start of it which
/// satisfy the given predicate. /// satisfy the given predicate.
/// ///
/// This example uses `trimPrefix(while:)` to remove the white space at the /// This example uses `trimPrefix(while:)` to remove the white space at the
@@ -52,13 +49,13 @@ extension Collection where Self: RangeReplaceableCollection {
/// ///
/// let myString = " hello, world " /// let myString = " hello, world "
/// myString.trimPrefix(while: \.isWhitespace) /// myString.trimPrefix(while: \.isWhitespace)
/// print(myString) /// print(myString) // "hello, world "
/// // Prints "hello, world "
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// removed from the result. /// removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
@_disfavoredOverload @_disfavoredOverload
public mutating func trimPrefix( public mutating func trimPrefix(
@@ -70,7 +67,7 @@ extension Collection where Self: RangeReplaceableCollection {
} }
extension Collection where Self == Self.SubSequence { extension Collection where Self == Self.SubSequence {
/// Mutates the collection by discarding all elements at the start that /// Mutates a `Collection` by discarding all elements at the start of it which
/// satisfy the given predicate. /// satisfy the given predicate.
/// ///
/// This example uses `trimPrefix(while:)` to remove the white space at the /// This example uses `trimPrefix(while:)` to remove the white space at the
@@ -80,10 +77,11 @@ extension Collection where Self == Self.SubSequence {
/// myString.trimPrefix(while: \.isWhitespace) /// myString.trimPrefix(while: \.isWhitespace)
/// print(myString) // "hello, world " /// print(myString) // "hello, world "
/// ///
/// - Parameters predicate: A closure that determines if the element should /// - Parameters predicate: A closure which determines if the element should
/// be removed from the string. /// be removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public mutating func trimPrefix( public mutating func trimPrefix(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
@@ -98,31 +96,28 @@ extension Collection where Self == Self.SubSequence {
extension BidirectionalCollection { extension BidirectionalCollection {
/// Returns a `SubSequence` formed by discarding all elements at the start and /// Returns a `SubSequence` formed by discarding all elements at the start and
/// end of the collection that satisfy the given predicate. /// end of the collection which satisfy the given predicate.
/// ///
/// This example uses `trimming(while:)` to get a substring without the white /// This example uses `trimming(while:)` to get a substring without the white
/// space at the beginning and end of the string: /// space at the beginning and end of the string:
/// ///
/// let myString = " hello, world " /// let myString = " hello, world "
/// print(myString.trimming(while: \.isWhitespace)) /// print(myString.trimming(while: \.isWhitespace)) // "hello, world"
/// // Prints "hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// omitted from the resulting slice. /// omitted from the resulting slice.
/// - Returns: A subsequence of this collection, starting at the first element
/// for which `predicate` returns `false` and ending at the last element for
/// which `predicate` returns `true`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public func trimming( public func trimming(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
) rethrows -> SubSequence { ) rethrows -> SubSequence {
try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate) try trimmingPrefix(while: predicate).trimmingSuffix(while: predicate)
} }
/// Returns a `SubSequence` formed by discarding all elements at the end of /// Returns a `SubSequence` formed by discarding all elements at the end of
/// the collection that satisfy the given predicate. /// the collection which satisfy the given predicate.
/// ///
/// This example uses `trimmingSuffix(while:)` to get a substring without the /// This example uses `trimmingSuffix(while:)` to get a substring without the
/// white space at the end of the string: /// white space at the end of the string:
@@ -130,12 +125,11 @@ extension BidirectionalCollection {
/// let myString = " hello, world " /// let myString = " hello, world "
/// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world" /// print(myString.trimmingSuffix(while: \.isWhitespace)) // " hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// omitted from the resulting slice. /// omitted from the resulting slice.
/// - Returns: A subsequence of this collection, ending at the last element
/// for which `predicate` returns `true`.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public func trimmingSuffix( public func trimmingSuffix(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
@@ -151,7 +145,7 @@ extension BidirectionalCollection {
extension BidirectionalCollection where Self: RangeReplaceableCollection { extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// Mutates a `BidirectionalCollection` by discarding all elements at the /// Mutates a `BidirectionalCollection` by discarding all elements at the
/// start and at the end of it that satisfy the given predicate. /// start and at the end of it which satisfy the given predicate.
/// ///
/// This example uses `trim(while:)` to remove the white space at the /// This example uses `trim(while:)` to remove the white space at the
/// beginning of the string: /// beginning of the string:
@@ -160,10 +154,11 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// myString.trim(while: \.isWhitespace) /// myString.trim(while: \.isWhitespace)
/// print(myString) // "hello, world" /// print(myString) // "hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// removed from the string. /// removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
@_disfavoredOverload @_disfavoredOverload
public mutating func trim( public mutating func trim(
@@ -172,9 +167,9 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
try trimSuffix(while: predicate) try trimSuffix(while: predicate)
try trimPrefix(while: predicate) try trimPrefix(while: predicate)
} }
/// Mutates a `BidirectionalCollection` by discarding all elements at the end /// Mutates a `BidirectionalCollection` by discarding all elements at the end
/// of it that satisfy the given predicate. /// of it which satisfy the given predicate.
/// ///
/// This example uses `trimSuffix(while:)` to remove the white space at the /// This example uses `trimSuffix(while:)` to remove the white space at the
/// beginning of the string: /// beginning of the string:
@@ -183,10 +178,11 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
/// myString.trimSuffix(while: \.isWhitespace) /// myString.trimSuffix(while: \.isWhitespace)
/// print(myString) // " hello, world" /// print(myString) // " hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// removed from the string. /// removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
@_disfavoredOverload @_disfavoredOverload
public mutating func trimSuffix( public mutating func trimSuffix(
@@ -199,7 +195,7 @@ extension BidirectionalCollection where Self: RangeReplaceableCollection {
extension BidirectionalCollection where Self == Self.SubSequence { extension BidirectionalCollection where Self == Self.SubSequence {
/// Mutates a `BidirectionalCollection` by discarding all elements at the /// Mutates a `BidirectionalCollection` by discarding all elements at the
/// start and at the end of it that satisfy the given predicate. /// start and at the end of it which satisfy the given predicate.
/// ///
/// This example uses `trim(while:)` to remove the white space at the /// This example uses `trim(while:)` to remove the white space at the
/// beginning of the string: /// beginning of the string:
@@ -208,10 +204,11 @@ extension BidirectionalCollection where Self == Self.SubSequence {
/// myString.trim(while: \.isWhitespace) /// myString.trim(while: \.isWhitespace)
/// print(myString) // "hello, world" /// print(myString) // "hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// removed from the string. /// removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public mutating func trim( public mutating func trim(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
@@ -220,7 +217,7 @@ extension BidirectionalCollection where Self == Self.SubSequence {
} }
/// Mutates a `BidirectionalCollection` by discarding all elements at the end /// Mutates a `BidirectionalCollection` by discarding all elements at the end
/// of it that satisfy the given predicate. /// of it which satisfy the given predicate.
/// ///
/// This example uses `trimSuffix(while:)` to remove the white space at the /// This example uses `trimSuffix(while:)` to remove the white space at the
/// beginning of the string: /// beginning of the string:
@@ -229,10 +226,11 @@ extension BidirectionalCollection where Self == Self.SubSequence {
/// myString.trimSuffix(while: \.isWhitespace) /// myString.trimSuffix(while: \.isWhitespace)
/// print(myString) // " hello, world" /// print(myString) // " hello, world"
/// ///
/// - Parameter predicate: A closure that determines if the element should be /// - Parameter predicate: A closure which determines if the element should be
/// removed from the string. /// removed from the string.
/// ///
/// - Complexity: O(*n*), where *n* is the length of this collection. /// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable @inlinable
public mutating func trimSuffix( public mutating func trimSuffix(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
+8 -8
View File
@@ -14,11 +14,11 @@ public struct UniquedSequence<Base: Sequence, Subject: Hashable> {
/// The base collection. /// The base collection.
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
/// The projection function. /// The projection function.
@usableFromInline @usableFromInline
internal let projection: (Base.Element) -> Subject internal let projection: (Base.Element) -> Subject
@usableFromInline @usableFromInline
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) { internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
self.base = base self.base = base
@@ -31,13 +31,13 @@ extension UniquedSequence: Sequence {
public struct Iterator: IteratorProtocol { public struct Iterator: IteratorProtocol {
@usableFromInline @usableFromInline
internal var base: Base.Iterator internal var base: Base.Iterator
@usableFromInline @usableFromInline
internal let projection: (Base.Element) -> Subject internal let projection: (Base.Element) -> Subject
@usableFromInline @usableFromInline
internal var seen: Set<Subject> = [] internal var seen: Set<Subject> = []
@usableFromInline @usableFromInline
internal init( internal init(
base: Base.Iterator, base: Base.Iterator,
@@ -46,7 +46,7 @@ extension UniquedSequence: Sequence {
self.base = base self.base = base
self.projection = projection self.projection = projection
} }
@inlinable @inlinable
public mutating func next() -> Base.Element? { public mutating func next() -> Base.Element? {
while let element = base.next() { while let element = base.next() {
@@ -57,7 +57,7 @@ extension UniquedSequence: Sequence {
return nil return nil
} }
} }
@inlinable @inlinable
public func makeIterator() -> Iterator { public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator(), projection: projection) Iterator(base: base.makeIterator(), projection: projection)
@@ -65,7 +65,7 @@ extension UniquedSequence: Sequence {
} }
extension UniquedSequence: LazySequenceProtocol extension UniquedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// uniqued() // uniqued()
+83 -88
View File
@@ -49,10 +49,10 @@ extension Collection {
public struct WindowsOfCountCollection<Base: Collection> { public struct WindowsOfCountCollection<Base: Collection> {
@usableFromInline @usableFromInline
internal let base: Base internal let base: Base
@usableFromInline @usableFromInline
internal let windowSize: Int internal let windowSize: Int
@usableFromInline @usableFromInline
internal var endOfFirstWindow: Base.Index? internal var endOfFirstWindow: Base.Index?
@@ -62,8 +62,7 @@ public struct WindowsOfCountCollection<Base: Collection> {
self.base = base self.base = base
self.windowSize = windowSize self.windowSize = windowSize
self.endOfFirstWindow = self.endOfFirstWindow =
base base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
} }
} }
@@ -72,40 +71,41 @@ extension WindowsOfCountCollection: Collection {
public struct Index: Comparable { public struct Index: Comparable {
@usableFromInline @usableFromInline
internal var lowerBound: Base.Index internal var lowerBound: Base.Index
@usableFromInline @usableFromInline
internal var upperBound: Base.Index internal var upperBound: Base.Index
@inlinable @inlinable
internal init(lowerBound: Base.Index, upperBound: Base.Index) { internal init(lowerBound: Base.Index, upperBound: Base.Index) {
self.lowerBound = lowerBound self.lowerBound = lowerBound
self.upperBound = upperBound self.upperBound = upperBound
} }
@inlinable @inlinable
public static func == (lhs: Index, rhs: Index) -> Bool { public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound == rhs.lowerBound lhs.lowerBound == rhs.lowerBound
} }
@inlinable @inlinable
public static func < (lhs: Index, rhs: Index) -> Bool { public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound lhs.lowerBound < rhs.lowerBound
} }
} }
@inlinable @inlinable
public var startIndex: Index { public var startIndex: Index {
guard let upperBound = endOfFirstWindow else { if let upperBound = endOfFirstWindow {
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else {
return endIndex return endIndex
} }
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} }
@inlinable @inlinable
public var endIndex: Index { public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex) Index(lowerBound: base.endIndex, upperBound: base.endIndex)
} }
@inlinable @inlinable
public subscript(index: Index) -> Base.SubSequence { public subscript(index: Index) -> Base.SubSequence {
precondition( precondition(
@@ -113,29 +113,28 @@ extension WindowsOfCountCollection: Collection {
"Windows index is out of range") "Windows index is out of range")
return base[index.lowerBound..<index.upperBound] return base[index.lowerBound..<index.upperBound]
} }
@inlinable @inlinable
public func index(after index: Index) -> Index { public func index(after index: Index) -> Index {
precondition(index != endIndex, "Advancing past end index") precondition(index != endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex } guard index.upperBound < base.endIndex else { return endIndex }
let lowerBound = let lowerBound = windowSize == 1
windowSize == 1
? index.upperBound ? index.upperBound
: base.index(after: index.lowerBound) : base.index(after: index.lowerBound)
let upperBound = base.index(after: index.upperBound) let upperBound = base.index(after: index.upperBound)
return Index(lowerBound: lowerBound, upperBound: upperBound) return Index(lowerBound: lowerBound, upperBound: upperBound)
} }
@inlinable @inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index { public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i } guard distance != 0 else { return i }
return distance > 0 return distance > 0
? offsetForward(i, by: distance) ? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance) : offsetBackward(i, by: -distance)
} }
@inlinable @inlinable
public func index( public func index(
_ i: Index, _ i: Index,
@@ -144,7 +143,7 @@ extension WindowsOfCountCollection: Collection {
) -> Index? { ) -> Index? {
guard distance != 0 else { return i } guard distance != 0 else { return i }
guard limit != i else { return nil } guard limit != i else { return nil }
if distance > 0 { if distance > 0 {
return limit > i return limit > i
? offsetForward(i, by: distance, limitedBy: limit) ? offsetForward(i, by: distance, limitedBy: limit)
@@ -155,30 +154,28 @@ extension WindowsOfCountCollection: Collection {
: offsetBackward(i, by: -distance) : offsetBackward(i, by: -distance)
} }
} }
@inlinable @inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index { internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index { internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") } else { fatalError("Index is out of bounds") }
return index return index
} }
@inlinable @inlinable
internal func offsetForward( internal func offsetForward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int,
limitedBy limit: Index
) -> Index? { ) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit > i) assert(limit > i)
// `endIndex` and the index before it both have `base.endIndex` as their // `endIndex` and the index before it both have `base.endIndex` as their
// upper bound, so we first advance to the base index _before_ the upper // upper bound, so we first advance to the base index _before_ the upper
// bound of the output, in order to avoid advancing past the end of `base` // bound of the output, in order to avoid advancing past the end of `base`
@@ -189,31 +186,31 @@ extension WindowsOfCountCollection: Collection {
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x] // input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
// |> > >|>| or |> > >| // |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`) // output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
if distance >= windowSize { if distance >= windowSize {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower // Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
// bound of the output is greater than or equal to the upper bound of the // bound of the output is greater than or equal to the upper bound of the
// input. // input.
// input: [x|x x x x|x x x x x x x] // input: [x|x x x x|x x x x x x x]
// |> >|> > >|>| // |> >|> > >|>|
// output: [x x x x x x x|x x x x|x] // output: [x x x x x x x|x x x x|x]
guard limit.lowerBound >= i.upperBound, guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index( let lowerBound = base.index(
i.upperBound, i.upperBound,
offsetBy: distance - windowSize, offsetBy: distance - windowSize,
limitedBy: limit.lowerBound), limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index( let indexBeforeUpperBound = base.index(
lowerBound, lowerBound,
offsetBy: windowSize - 1, offsetBy: windowSize - 1,
limitedBy: limit.upperBound) limitedBy: limit.upperBound)
else { return nil } else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`. // `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex } guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index( return Index(
lowerBound: lowerBound, lowerBound: lowerBound,
upperBound: base.index(after: indexBeforeUpperBound)) upperBound: base.index(after: indexBeforeUpperBound))
@@ -221,38 +218,35 @@ extension WindowsOfCountCollection: Collection {
// input: [x|x x x x x x|x x x x x] // input: [x|x x x x x x|x x x x x]
// |> > > >| |> > >|>| // |> > > >| |> > >|>|
// output: [x x x x x|x x x x x x|x] // output: [x x x x x|x x x x x x|x]
guard guard let indexBeforeUpperBound = base.index(
let indexBeforeUpperBound = base.index( i.upperBound,
i.upperBound, offsetBy: distance - 1,
offsetBy: distance - 1, limitedBy: limit.upperBound)
limitedBy: limit.upperBound)
else { return nil } else { return nil }
// If `indexBeforeUpperBound` equals the limit, the upper bound itself // If `indexBeforeUpperBound` equals the limit, the upper bound itself
// exceeds it. // exceeds it.
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
else { return nil } else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to // If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`. // `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex } guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index( return Index(
lowerBound: base.index(i.lowerBound, offsetBy: distance), lowerBound: base.index(i.lowerBound, offsetBy: distance),
upperBound: base.index(after: indexBeforeUpperBound)) upperBound: base.index(after: indexBeforeUpperBound))
} }
} }
@inlinable @inlinable
internal func offsetBackward( internal func offsetBackward(
_ i: Index, _ i: Index, by distance: Int, limitedBy limit: Index
by distance: Int, ) -> Index? {
limitedBy limit: Index
) -> Index? {
assert(distance > 0) assert(distance > 0)
assert(limit < i) assert(limit < i)
if i == endIndex { if i == endIndex {
// Advance `base.endIndex` by `distance - 1`, because the index before // Advance `base.endIndex` by `distance - 1`, because the index before
// `endIndex` also has `base.endIndex` as its upper bound. // `endIndex` also has `base.endIndex` as its upper bound.
@@ -262,14 +256,13 @@ extension WindowsOfCountCollection: Collection {
// input: [x x x x x x x x x x] (`endIndex`) // input: [x x x x x x x x x x] (`endIndex`)
// |< < < < <|< < <| // |< < < < <|< < <|
// output: [x x|x x x x x|x x x] // output: [x x|x x x x x|x x x]
guard guard let upperBound = base.index(
let upperBound = base.index( base.endIndex,
base.endIndex, offsetBy: -(distance - 1),
offsetBy: -(distance - 1), limitedBy: limit.upperBound)
limitedBy: limit.upperBound)
else { return nil } else { return nil }
return Index( return Index(
lowerBound: base.index(upperBound, offsetBy: -windowSize), lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound) upperBound: upperBound)
@@ -281,14 +274,14 @@ extension WindowsOfCountCollection: Collection {
// input: [x x x x x x x|x x x x|x] // input: [x x x x x x x|x x x x|x]
// |< < < <|< <| // |< < < <|< <|
// output: [x|x x x x|x x x x x x x] // output: [x|x x x x|x x x x x x x]
guard limit.upperBound <= i.lowerBound, guard limit.upperBound <= i.lowerBound,
let upperBound = base.index( let upperBound = base.index(
i.lowerBound, i.lowerBound,
offsetBy: -(distance - windowSize), offsetBy: -(distance - windowSize),
limitedBy: limit.upperBound) limitedBy: limit.upperBound)
else { return nil } else { return nil }
return Index( return Index(
lowerBound: base.index(upperBound, offsetBy: -windowSize), lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound) upperBound: upperBound)
@@ -296,20 +289,19 @@ extension WindowsOfCountCollection: Collection {
// input: [x x x x x|x x x x x x|x] // input: [x x x x x|x x x x x x|x]
// |< < < <| |< < < <| // |< < < <| |< < < <|
// output: [x|x x x x x x|x x x x x] // output: [x|x x x x x x|x x x x x]
guard guard let lowerBound = base.index(
let lowerBound = base.index( i.lowerBound,
i.lowerBound, offsetBy: -distance,
offsetBy: -distance, limitedBy: limit.lowerBound)
limitedBy: limit.lowerBound)
else { return nil } else { return nil }
return Index( return Index(
lowerBound: lowerBound, lowerBound: lowerBound,
upperBound: base.index(i.lowerBound, offsetBy: -distance)) upperBound: base.index(i.lowerBound, offsetBy: -distance))
} }
} }
@inlinable @inlinable
public func distance(from start: Index, to end: Index) -> Int { public func distance(from start: Index, to end: Index) -> Int {
guard start <= end else { return -distance(from: end, to: start) } guard start <= end else { return -distance(from: end, to: start) }
@@ -327,39 +319,42 @@ extension WindowsOfCountCollection: Collection {
// start: [x|x x x x|x x x x x x x] // start: [x|x x x x|x x x x x x x]
// |- - - -|> >| // |- - - -|> >|
// end: [x x x x x x x|x x x x|x] // end: [x x x x x x x|x x x x|x]
return windowSize + base[start.upperBound..<end.lowerBound].count return windowSize + base[start.upperBound..<end.lowerBound].count
} else { } else {
// start: [x|x x x x x x|x x x x x] // start: [x|x x x x x x|x x x x x]
// |> > > >| // |> > > >|
// end: [x x x x x|x x x x x x|x] // end: [x x x x x|x x x x x x|x]
return base[start.lowerBound..<end.lowerBound].count return base[start.lowerBound..<end.lowerBound].count
} }
} }
} }
extension WindowsOfCountCollection: BidirectionalCollection extension WindowsOfCountCollection: BidirectionalCollection
where Base: BidirectionalCollection { where Base: BidirectionalCollection
{
@inlinable @inlinable
public func index(before index: Index) -> Index { public func index(before index: Index) -> Index {
precondition(index != startIndex, "Decrementing past start index") precondition(index != startIndex, "Incrementing past start index")
if index == endIndex { if index == endIndex {
return Index( return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize), lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
upperBound: index.upperBound) upperBound: index.upperBound
)
} else { } else {
return Index( return Index(
lowerBound: base.index(before: index.lowerBound), lowerBound: base.index(before: index.lowerBound),
upperBound: base.index(before: index.upperBound)) upperBound: base.index(before: index.upperBound)
)
} }
} }
} }
extension WindowsOfCountCollection: RandomAccessCollection extension WindowsOfCountCollection: RandomAccessCollection
where Base: RandomAccessCollection {} where Base: RandomAccessCollection {}
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {} where Base: LazySequenceProtocol {}
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {} extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}
@@ -9,63 +9,63 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class AdjacentPairsTests: XCTestCase { final class AdjacentPairsTests: XCTestCase {
func testEmptySequence() { func testEmptySequence() {
let pairs = (0...).prefix(0).adjacentPairs() let pairs = (0...).prefix(0).adjacentPairs()
expectEqualSequences(pairs, [], by: ==) XCTAssertEqualSequences(pairs, [], by: ==)
} }
func testOneElementSequence() { func testOneElementSequence() {
let pairs = (0...).prefix(1).adjacentPairs() let pairs = (0...).prefix(1).adjacentPairs()
expectEqualSequences(pairs, [], by: ==) XCTAssertEqualSequences(pairs, [], by: ==)
} }
func testTwoElementSequence() { func testTwoElementSequence() {
let pairs = (0...).prefix(2).adjacentPairs() let pairs = (0...).prefix(2).adjacentPairs()
expectEqualSequences(pairs, [(0, 1)], by: ==) XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
} }
func testThreeElementSequence() { func testThreeElementSequence() {
let pairs = (0...).prefix(3).adjacentPairs() let pairs = (0...).prefix(3).adjacentPairs()
expectEqualSequences(pairs, [(0, 1), (1, 2)], by: ==) XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
} }
func testManySequences() { func testManySequences() {
for n in 4...100 { for n in 4...100 {
let pairs = (0...).prefix(n).adjacentPairs() let pairs = (0...).prefix(n).adjacentPairs()
expectEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==) XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
} }
} }
func testZeroElements() { func testZeroElements() {
let pairs = (0..<0).adjacentPairs() let pairs = (0..<0).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex) XCTAssertEqual(pairs.startIndex, pairs.endIndex)
expectEqualSequences(pairs, [], by: ==) XCTAssertEqualSequences(pairs, [], by: ==)
} }
func testOneElement() { func testOneElement() {
let pairs = (0..<1).adjacentPairs() let pairs = (0..<1).adjacentPairs()
XCTAssertEqual(pairs.startIndex, pairs.endIndex) XCTAssertEqual(pairs.startIndex, pairs.endIndex)
expectEqualSequences(pairs, [], by: ==) XCTAssertEqualSequences(pairs, [], by: ==)
} }
func testTwoElements() { func testTwoElements() {
let pairs = (0..<2).adjacentPairs() let pairs = (0..<2).adjacentPairs()
expectEqualSequences(pairs, [(0, 1)], by: ==) XCTAssertEqualSequences(pairs, [(0, 1)], by: ==)
} }
func testThreeElements() { func testThreeElements() {
let pairs = (0..<3).adjacentPairs() let pairs = (0..<3).adjacentPairs()
expectEqualSequences(pairs, [(0, 1), (1, 2)], by: ==) XCTAssertEqualSequences(pairs, [(0, 1), (1, 2)], by: ==)
} }
func testManyElements() { func testManyElements() {
for n in 4...100 { for n in 4...100 {
let pairs = (0..<n).adjacentPairs() let pairs = (0..<n).adjacentPairs()
expectEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==) XCTAssertEqualSequences(pairs, zip(0..., 1...).prefix(n - 1), by: ==)
} }
} }
@@ -76,9 +76,9 @@ final class AdjacentPairsTests: XCTestCase {
validator.validate((0..<2).adjacentPairs(), expectedCount: 1) validator.validate((0..<2).adjacentPairs(), expectedCount: 1)
validator.validate((0..<5).adjacentPairs(), expectedCount: 4) validator.validate((0..<5).adjacentPairs(), expectedCount: 4)
} }
func testLaziness() { func testLaziness() {
requireLazySequence((0...).lazy.adjacentPairs()) XCTAssertLazySequence((0...).lazy.adjacentPairs())
requireLazyCollection((0..<100).lazy.adjacentPairs()) XCTAssertLazyCollection((0..<100).lazy.adjacentPairs())
} }
} }
+14 -15
View File
@@ -10,32 +10,31 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class ChainTests: XCTestCase { final class ChainTests: XCTestCase {
func testChainSequences() { func testChainSequences() {
let run = chain((1...).prefix(10), 20...) let run = chain((1...).prefix(10), 20...)
expectEqualSequences(run.prefix(20), Array(1...10) + (20..<30)) XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30))
} }
func testChainForwardCollection() { func testChainForwardCollection() {
let s1 = Set(0...10) let s1 = Set(0...10)
let s2 = Set(20...30) let s2 = Set(20...30)
let c = chain(s1, s2) let c = chain(s1, s2)
expectEqualSequences(c, Array(s1) + Array(s2)) XCTAssertEqualSequences(c, Array(s1) + Array(s2))
} }
func testChainBidirectionalCollection() { func testChainBidirectionalCollection() {
let s1 = "ABCDEFGHIJ" let s1 = "ABCDEFGHIJ"
let s2 = "klmnopqrstuv" let s2 = "klmnopqrstuv"
let c = chain(s1, s2) let c = chain(s1, s2)
expectEqualSequences(c, "ABCDEFGHIJklmnopqrstuv") XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv")
expectEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed()) XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed())
expectEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv") XCTAssertEqualSequences(chain(s1.reversed(), s2), "JIHGFEDCBAklmnopqrstuv")
} }
func testChainIndexTraversals() { func testChainIndexTraversals() {
let validator = IndexValidator<Chain2Sequence<String, String>>( let validator = IndexValidator<Chain2Sequence<String, String>>(
indicesIncludingEnd: { chain in indicesIncludingEnd: { chain in
@@ -43,27 +42,27 @@ final class ChainTests: XCTestCase {
+ chain.base2.indices.map { .init(second: $0) } + chain.base2.indices.map { .init(second: $0) }
+ [.init(second: chain.base2.endIndex)] + [.init(second: chain.base2.endIndex)]
}) })
validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3) validator.validate(chain("abcd", "XYZ"), expectedCount: 4 + 3)
validator.validate(chain("abcd", ""), expectedCount: 4 + 0) validator.validate(chain("abcd", ""), expectedCount: 4 + 0)
validator.validate(chain("", "XYZ"), expectedCount: 0 + 3) validator.validate(chain("", "XYZ"), expectedCount: 0 + 3)
validator.validate(chain("", ""), expectedCount: 0 + 0) validator.validate(chain("", ""), expectedCount: 0 + 0)
} }
func testChainIndexOffsetAcrossBoundary() { func testChainIndexOffsetAcrossBoundary() {
let c = chain("abc", "XYZ") let c = chain("abc", "XYZ")
do { do {
let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex) let i = c.index(c.startIndex, offsetBy: 3, limitedBy: c.startIndex)
XCTAssertNil(i) XCTAssertNil(i)
} }
do { do {
let i = c.index(c.startIndex, offsetBy: 4) let i = c.index(c.startIndex, offsetBy: 4)
let j = c.index(i, offsetBy: -2) let j = c.index(i, offsetBy: -2)
XCTAssertEqual(c[j], "c") XCTAssertEqual(c[j], "c")
} }
do { do {
let i = c.index(c.startIndex, offsetBy: 3) let i = c.index(c.startIndex, offsetBy: 3)
let j = c.index(i, offsetBy: -1, limitedBy: i) let j = c.index(i, offsetBy: -1, limitedBy: i)
+74 -87
View File
@@ -9,22 +9,23 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class ChunkedTests: XCTestCase { final class ChunkedTests: XCTestCase {
let fruits = [ let fruits = [
"Apple", "Apricot", "Avocado", "Banana", "Apple", "Apricot", "Avocado", "Banana",
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
"Currant", "Cherry", "Cherimoya", "Clementine", "Currant", "Cherry", "Cherimoya", "Clementine",
"Date", "Damson", "Dragonfruit", "Durian", "Date", "Damson", "Dragonfruit", "Durian",
"Eggplant", "Elderberry", "Feijoa", "Eggplant", "Elderberry", "Feijoa",
"Grape", "Grapefruit", "Guava", "Grape", "Grapefruit", "Guava",
] ]
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C) func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
where C.Element == ArraySlice<String> { where C.Element == ArraySlice<String>
let expectedChunks: [ArraySlice<String>] = [ {
let expectedChunks: Array<ArraySlice<String>> = [
fruits[0..<3], fruits[0..<3],
fruits[3..<8], fruits[3..<8],
fruits[8..<12], fruits[8..<12],
@@ -33,17 +34,16 @@ final class ChunkedTests: XCTestCase {
fruits[18..<19], fruits[18..<19],
fruits[19..<22], fruits[19..<22],
] ]
expectEqualSequences(expectedChunks, fruitChunks, by: ==) XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
XCTAssertEqual(fruits[19..<22], fruitChunks.last) XCTAssertEqual(fruits[19..<22], fruitChunks.last)
XCTAssertEqual( XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
"Currant", fruitChunks.first(where: { $0.count == 4 })?.first)
XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first) XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first)
XCTAssertNil(fruitChunks.first(where: { $0.count == 0 })) XCTAssertNil(fruitChunks.first(where: { $0.count == 0 }))
XCTAssertNil(fruitChunks.last(where: { $0.count == 0 })) XCTAssertNil(fruitChunks.last(where: { $0.count == 0 }))
} }
func testSimple() { func testSimple() {
// Example // Example
let names = ["David", "Kyle", "Karoy", "Nate"] let names = ["David", "Kyle", "Karoy", "Nate"]
@@ -51,10 +51,9 @@ final class ChunkedTests: XCTestCase {
let expected: [(Character, ArraySlice<String>)] = [ let expected: [(Character, ArraySlice<String>)] = [
("D", ["David"]), ("D", ["David"]),
("K", ["Kyle", "Karoy"]), ("K", ["Kyle", "Karoy"]),
("N", ["Nate"]), ("N", ["Nate"])]
] XCTAssertEqualSequences(expected, chunks, by: ==)
expectEqualSequences(expected, chunks, by: ==)
// Empty sequence // Empty sequence
XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count) XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count)
@@ -62,10 +61,10 @@ final class ChunkedTests: XCTestCase {
let namesStartingWithD = ["David", "Don", "Darren"] let namesStartingWithD = ["David", "Don", "Darren"]
XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count) XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count)
} }
func testChunkedOn() { func testChunkedOn() {
validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 }) validateFruitChunks(fruits.chunked(on: { $0.first }).map { $1 })
let lazyChunks = fruits.lazy.chunked(on: { $0.first }) let lazyChunks = fruits.lazy.chunked(on: { $0.first })
validateFruitChunks(lazyChunks.map { $1 }) validateFruitChunks(lazyChunks.map { $1 })
IndexValidator().validate(lazyChunks) IndexValidator().validate(lazyChunks)
@@ -73,83 +72,73 @@ final class ChunkedTests: XCTestCase {
func testChunkedBy() { func testChunkedBy() {
validateFruitChunks(fruits.chunked(by: { $0.first == $1.first })) validateFruitChunks(fruits.chunked(by: { $0.first == $1.first }))
let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first }) let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first })
validateFruitChunks(lazyChunks) validateFruitChunks(lazyChunks)
IndexValidator().validate(lazyChunks) IndexValidator().validate(lazyChunks)
} }
func testChunkedByComparesConsecutiveElements() { func testChunkedByComparesConsecutiveElements() {
expectEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 6, 7, 8, 9].chunked(by: { $1 - $0 == 1 }), [1, 2, 3, 4, 6, 7, 8, 9].chunked(by: { $1 - $0 == 1 }),
[[1, 2, 3, 4], [6, 7, 8, 9]]) [[1, 2, 3, 4], [6, 7, 8, 9]])
expectEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }), [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }),
[[1, 2, 3, 4], [6, 7, 8, 9]]) [[1, 2, 3, 4], [6, 7, 8, 9]])
expectEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(), [1, 2, 3, 4, 6, 7, 8, 9].lazy.chunked(by: { $1 - $0 == 1 }).reversed(),
[[6, 7, 8, 9], [1, 2, 3, 4]]) [[6, 7, 8, 9], [1, 2, 3, 4]])
IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 })) IndexValidator().validate([1, 2, 3].lazy.chunked(by: { $1 - $0 == 1 }))
} }
func testChunkedLazy() { func testChunkedLazy() {
requireLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first })) XCTAssertLazySequence(fruits.lazy.chunked(by: { $0.first == $1.first }))
requireLazySequence(fruits.lazy.chunked(on: { $0.first })) XCTAssertLazySequence(fruits.lazy.chunked(on: { $0.first }))
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// Tests for `chunks(ofCount:)` // Tests for `chunks(ofCount:)`
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
func testChunksOfCount() { func testChunksOfCount() {
expectEqualSequences([Int]().chunks(ofCount: 1), []) XCTAssertEqualSequences([Int]().chunks(ofCount: 1), [])
expectEqualSequences([Int]().chunks(ofCount: 5), []) XCTAssertEqualSequences([Int]().chunks(ofCount: 5), [])
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expectEqualSequences( XCTAssertEqualSequences(collection1.chunks(ofCount: 1),
collection1.chunks(ofCount: 1), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) XCTAssertEqualSequences(collection1.chunks(ofCount: 3),
expectEqualSequences( [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
collection1.chunks(ofCount: 3), XCTAssertEqualSequences(collection1.chunks(ofCount: 5),
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
expectEqualSequences( XCTAssertEqualSequences(collection1.chunks(ofCount: 11),
collection1.chunks(ofCount: 5), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
expectEqualSequences(
collection1.chunks(ofCount: 11),
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
expectEqualSequences( XCTAssertEqualSequences(collection2.chunks(ofCount: 3),
collection2.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
} }
func testChunksOfCountBidirectional() { func testChunksOfCountBidirectional() {
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expectEqualSequences( XCTAssertEqualSequences(collection1.chunks(ofCount: 1).reversed(),
collection1.chunks(ofCount: 1).reversed(), [[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]]) XCTAssertEqualSequences(collection1.chunks(ofCount: 3).reversed(),
expectEqualSequences( [[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
collection1.chunks(ofCount: 3).reversed(), XCTAssertEqualSequences(collection1.chunks(ofCount: 5).reversed(),
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]]) [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
expectEqualSequences( XCTAssertEqualSequences(collection1.chunks(ofCount: 11).reversed(),
collection1.chunks(ofCount: 5).reversed(), [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
expectEqualSequences(
collection1.chunks(ofCount: 11).reversed(),
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let collection2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
expectEqualSequences( XCTAssertEqualSequences(collection2.chunks(ofCount: 3).reversed(),
collection2.chunks(ofCount: 3).reversed(), [[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
} }
func testChunksOfCountCount() { func testChunksOfCountCount() {
XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0) XCTAssertEqual([Int]().chunks(ofCount: 1).count, 0)
XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0) XCTAssertEqual([Int]().chunks(ofCount: 5).count, 0)
@@ -159,20 +148,20 @@ final class ChunkedTests: XCTestCase {
XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4) XCTAssertEqual(collection1.chunks(ofCount: 3).count, 4)
XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2) XCTAssertEqual(collection1.chunks(ofCount: 5).count, 2)
XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1) XCTAssertEqual(collection1.chunks(ofCount: 11).count, 1)
let collection2 = (1...50).map { $0 } let collection2 = (1...50).map { $0 }
XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6) XCTAssertEqual(collection2.chunks(ofCount: 9).count, 6)
} }
func testEmptyChunksOfCountTraversal() { func testEmptyChunksOfCountTraversal() {
let emptyChunks = [Int]().chunks(ofCount: 1) let emptyChunks = [Int]().chunks(ofCount: 1)
IndexValidator().validate(emptyChunks, expectedCount: 0) IndexValidator().validate(emptyChunks, expectedCount: 0)
} }
func testChunksOfCountTraversal() { func testChunksOfCountTraversal() {
let validator = IndexValidator<ChunksOfCountCollection<ClosedRange<Int>>>() let validator = IndexValidator<ChunksOfCountCollection<ClosedRange<Int>>>()
for i in 1...10 { for i in 1...10 {
let range = 1...50 let range = 1...50
let chunks = range.chunks(ofCount: i) let chunks = range.chunks(ofCount: i)
@@ -181,29 +170,29 @@ final class ChunkedTests: XCTestCase {
expectedCount: range.count / i + (range.count % i).signum()) expectedCount: range.count / i + (range.count % i).signum())
} }
} }
func testEvenChunks() { func testEvenChunks() {
expectEqualSequences( XCTAssertEqualSequences(
(0..<10).evenlyChunked(in: 4), (0..<10).evenlyChunked(in: 4),
[0..<3, 3..<6, 6..<8, 8..<10]) [0..<3, 3..<6, 6..<8, 8..<10])
expectEqualSequences( XCTAssertEqualSequences(
(0..<3).evenlyChunked(in: 5), (0..<3).evenlyChunked(in: 5),
[0..<1, 1..<2, 2..<3, 3..<3, 3..<3]) [0..<1, 1..<2, 2..<3, 3..<3, 3..<3])
expectEqualSequences( XCTAssertEqualSequences(
"".evenlyChunked(in: 0), "".evenlyChunked(in: 0),
[]) [])
expectEqualSequences( XCTAssertEqualSequences(
"".evenlyChunked(in: 1), "".evenlyChunked(in: 1),
[""]) [""])
} }
func testEvenChunksIndexTraversals() { func testEvenChunksIndexTraversals() {
let validator = IndexValidator<EvenlyChunkedCollection<Range<Int>>>() let validator = IndexValidator<EvenlyChunkedCollection<Range<Int>>>()
for chunks in [ [
(0..<10).evenlyChunked(in: 1), (0..<10).evenlyChunked(in: 1),
(0..<10).evenlyChunked(in: 2), (0..<10).evenlyChunked(in: 2),
(0..<10).evenlyChunked(in: 3), (0..<10).evenlyChunked(in: 3),
@@ -212,8 +201,6 @@ final class ChunkedTests: XCTestCase {
(0..<0).evenlyChunked(in: 0), (0..<0).evenlyChunked(in: 0),
(0..<0).evenlyChunked(in: 1), (0..<0).evenlyChunked(in: 1),
(0..<0).evenlyChunked(in: 10), (0..<0).evenlyChunked(in: 10),
] { ].forEach { validator.validate($0) }
validator.validate(chunks)
}
} }
} }
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class CombinationsTests: XCTestCase { final class CombinationsTests: XCTestCase {
func testCount() { func testCount() {
@@ -20,8 +20,8 @@ final class CombinationsTests: XCTestCase {
/// the given `file` and `line`. /// the given `file` and `line`.
func check( func check(
_ x: CombinationsSequence<String>, countsAre l: Int, _ x: CombinationsSequence<String>, countsAre l: Int,
file: StaticString, line: UInt file: StaticString, line: UInt)
) { {
XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line) XCTAssertEqual(x.count, l, "unexpected count", file: file, line: line)
XCTAssertEqual( XCTAssertEqual(
x.underestimatedCount, l, "unexpected underestimatedCount", x.underestimatedCount, l, "unexpected underestimatedCount",
@@ -34,8 +34,8 @@ final class CombinationsTests: XCTestCase {
func check( func check(
cHas n: Int, cHas n: Int,
combinationsOfLength l: Int, combinationsOfLength l: Int,
file: StaticString = #filePath, line: UInt = #line file: StaticString = #filePath, line: UInt = #line)
) { {
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line) check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
} }
@@ -45,8 +45,8 @@ final class CombinationsTests: XCTestCase {
func check<R: RangeExpression>( func check<R: RangeExpression>(
cHas n: Int, cHas n: Int,
combinationsOfLengths l: R, combinationsOfLengths l: R,
file: StaticString = #filePath, line: UInt = #line file: StaticString = #filePath, line: UInt = #line) where R.Bound == Int
) where R.Bound == Int { {
check(c.combinations(ofCount: l), countsAre: n, file: file, line: line) check(c.combinations(ofCount: l), countsAre: n, file: file, line: line)
} }
@@ -63,92 +63,70 @@ final class CombinationsTests: XCTestCase {
// `k` greater than element count results in same number of combinations // `k` greater than element count results in same number of combinations
check(cHas: 5, combinationsOfLengths: 3...10) check(cHas: 5, combinationsOfLengths: 3...10)
// `k` greater than element count results in same number of combinations // `k` greater than element count results in same number of combinations
check(cHas: 1, combinationsOfLengths: 4...10) check(cHas: 1, combinationsOfLengths: 4...10)
// `k` entirely greater than element count results in no combinations // `k` entirely greater than element count results in no combinations
check(cHas: 0, combinationsOfLengths: 5...10) check(cHas: 0, combinationsOfLengths: 5...10)
check(cHas: 16, combinationsOfLengths: 0...) check(cHas: 16, combinationsOfLengths: 0...)
check(cHas: 15, combinationsOfLengths: ...3) check(cHas: 15, combinationsOfLengths: ...3)
} }
func testCombinations() { func testCombinations() {
let c = "ABCD" let c = "ABCD"
let c1 = c.combinations(ofCount: 1) let c1 = c.combinations(ofCount: 1)
XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) }) XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) })
let c2 = c.combinations(ofCount: 2) let c2 = c.combinations(ofCount: 2)
XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) }) XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) })
let c3 = c.combinations(ofCount: 3) let c3 = c.combinations(ofCount: 3)
XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) }) XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) })
let c4 = c.combinations(ofCount: 4) let c4 = c.combinations(ofCount: 4)
XCTAssertEqual(["ABCD"], c4.map { String($0) }) XCTAssertEqual(["ABCD"], c4.map { String($0) })
let c5 = c.combinations(ofCount: 2...4) let c5 = c.combinations(ofCount: 2...4)
XCTAssertEqual( XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c5.map { String($0) })
["AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"],
c5.map { String($0) })
let c6 = c.combinations(ofCount: 0...4) let c6 = c.combinations(ofCount: 0...4)
XCTAssertEqual( XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c6.map { String($0) })
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC",
"ABD", "ACD", "BCD", "ABCD",
], c6.map { String($0) })
let c7 = c.combinations(ofCount: 0...) let c7 = c.combinations(ofCount: 0...)
XCTAssertEqual( XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c7.map { String($0) })
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC",
"ABD", "ACD", "BCD", "ABCD",
], c7.map { String($0) })
let c8 = c.combinations(ofCount: ...4) let c8 = c.combinations(ofCount: ...4)
XCTAssertEqual( XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c8.map { String($0) })
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC",
"ABD", "ACD", "BCD", "ABCD",
], c8.map { String($0) })
let c9 = c.combinations(ofCount: ...3) let c9 = c.combinations(ofCount: ...3)
XCTAssertEqual( XCTAssertEqual(["", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD"], c9.map { String($0) })
[
"", "A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC",
"ABD", "ACD", "BCD",
], c9.map { String($0) })
let c10 = c.combinations(ofCount: 1...) let c10 = c.combinations(ofCount: 1...)
XCTAssertEqual( XCTAssertEqual(["A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD", "ACD", "BCD", "ABCD"], c10.map { String($0) })
[
"A", "B", "C", "D", "AB", "AC", "AD", "BC", "BD", "CD", "ABC", "ABD",
"ACD", "BCD", "ABCD",
], c10.map { String($0) })
} }
func testEmpty() { func testEmpty() {
// `k == 0` results in one zero-length combination // `k == 0` results in one zero-length combination
expectEqualSequences([[]], "".combinations(ofCount: 0)) XCTAssertEqualSequences([[]], "".combinations(ofCount: 0))
expectEqualSequences([[]], "".combinations(ofCount: 0...0)) XCTAssertEqualSequences([[]], "".combinations(ofCount: 0...0))
expectEqualSequences([[]], "ABCD".combinations(ofCount: 0)) XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0))
expectEqualSequences([[]], "ABCD".combinations(ofCount: 0...0)) XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0...0))
// `k` greater than element count results in zero combinations // `k` greater than element count results in zero combinations
expectEqualSequences([], "".combinations(ofCount: 5)) XCTAssertEqualSequences([], "".combinations(ofCount: 5))
expectEqualSequences([], "".combinations(ofCount: 5...10)) XCTAssertEqualSequences([], "".combinations(ofCount: 5...10))
expectEqualSequences([], "ABCD".combinations(ofCount: 5)) XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5))
expectEqualSequences([], "ABCD".combinations(ofCount: 5...10)) XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5...10))
} }
func testCombinationsLazy() { func testCombinationsLazy() {
requireLazySequence("ABC".lazy.combinations(ofCount: 1)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1))
requireLazySequence("ABC".lazy.combinations(ofCount: 1...3)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...3))
requireLazySequence("ABC".lazy.combinations(ofCount: 1...)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 1...))
requireLazySequence("ABC".lazy.combinations(ofCount: ...3)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: ...3))
requireLazySequence("ABC".lazy.combinations(ofCount: 0...)) XCTAssertLazySequence("ABC".lazy.combinations(ofCount: 0...))
} }
} }
@@ -9,34 +9,33 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class CompactedTests: XCTestCase { final class CompactedTests: XCTestCase {
let tests: [[Int?]] = let tests: [[Int?]] =
[nil, nil, nil, 0, 1, 2] [nil, nil, nil, 0, 1, 2]
.uniquePermutations(ofCount: 0...) .uniquePermutations(ofCount: 0...)
.map(Array.init) .map(Array.init)
func testCompactedCompacted() { func testCompactedCompacted() {
for collection in self.tests { for collection in self.tests {
let seq = AnySequence(collection) let seq = AnySequence(collection)
expectEqualSequences( XCTAssertEqualSequences(
seq.compactMap({ $0 }), seq.compacted()) seq.compactMap({ $0 }), seq.compacted())
expectEqualSequences( XCTAssertEqualSequences(
collection.compactMap({ $0 }), collection.compacted()) collection.compactMap({ $0 }), collection.compacted())
} }
} }
func testCompactedBidirectionalCollection() { func testCompactedBidirectionalCollection() {
for array in self.tests { for array in self.tests {
expectEqualSequences( XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(),
array.compactMap({ $0 }).reversed(), array.compacted().reversed())
array.compacted().reversed())
} }
} }
func testCollectionTraversals() { func testCollectionTraversals() {
let validator = IndexValidator<CompactedCollection<[Int?], Int>>() let validator = IndexValidator<CompactedCollection<[Int?], Int>>()
for array in self.tests { for array in self.tests {
+7 -8
View File
@@ -9,13 +9,13 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class CycleTests: XCTestCase { final class CycleTests: XCTestCase {
func testCycle() { func testCycle() {
let cycle = (1...4).cycled() let cycle = (1...4).cycled()
expectEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
cycle.prefix(20) cycle.prefix(20)
) )
@@ -32,12 +32,12 @@ final class CycleTests: XCTestCase {
} }
func testCycleLazy() { func testCycleLazy() {
requireLazySequence((1...4).lazy.cycled()) XCTAssertLazySequence((1...4).lazy.cycled())
} }
func testRepeated() { func testRepeated() {
let repeats = (1...4).cycled(times: 3) let repeats = (1...4).cycled(times: 3)
expectEqualSequences( XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
repeats) repeats)
} }
@@ -58,7 +58,7 @@ final class CycleTests: XCTestCase {
} }
func testRepeatedLazy() { func testRepeatedLazy() {
requireLazySequence((1...4).lazy.cycled(times: 3)) XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
} }
func testRepeatedIndexMethods() { func testRepeatedIndexMethods() {
@@ -73,9 +73,8 @@ final class CycleTests: XCTestCase {
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)! nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8) XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
let outOfBounds = cycle.index( let outOfBounds = cycle.index(nextIndex, offsetBy: 1,
nextIndex, offsetBy: 1, limitedBy: cycle.endIndex)
limitedBy: cycle.endIndex)
XCTAssertNil(outOfBounds) XCTAssertNil(outOfBounds)
let previousIndex = cycle.index(before: nextIndex) let previousIndex = cycle.index(before: nextIndex)
@@ -1,97 +0,0 @@
//===----------------------------------------------------------------------===//
//
// 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
final class EndsWithTests: XCTestCase {
func testEndsWithCorrectSuffix() {
let a = 8...10
let b = 1...10
XCTAssertTrue(b.ends(with: a))
}
func testDoesntEndWithWrongSuffix() {
let a = 8...9
let b = 1...10
XCTAssertFalse(b.ends(with: a))
}
func testDoesntEndWithTooLongSuffix() {
XCTAssertFalse((2...5).ends(with: (1...10)))
}
func testEndsWithEmpty() {
let a = 8...10
let empty: [Int] = []
XCTAssertTrue(a.ends(with: empty))
}
func testEmptyEndsWithEmpty() {
let empty: [Int] = []
XCTAssertTrue(empty.ends(with: empty))
}
func testEmptyDoesNotEndWithNonempty() {
XCTAssertFalse([].ends(with: 1...10))
}
}
final class EndsWithNonEquatableTests: XCTestCase {
func testEndsWithCorrectSuffix() {
let a = nonEq(8...10)
let b = nonEq(1...10)
XCTAssertTrue(b.ends(with: a, by: areEquivalent))
}
func testDoesntEndWithWrongSuffix() {
let a = nonEq(8...9)
let b = nonEq(1...10)
XCTAssertFalse(b.ends(with: a, by: areEquivalent))
}
func testDoesntEndWithTooLongSuffix() {
XCTAssertFalse(nonEq(2...5).ends(with: nonEq(1...10), by: areEquivalent))
}
func testEndsWithEmpty() {
let a = nonEq(8...10)
let empty: [NotEquatable<Int>] = []
XCTAssertTrue(a.ends(with: empty, by: areEquivalent))
}
func testEmptyEndsWithEmpty() {
let empty: [NotEquatable<Int>] = []
XCTAssertTrue(empty.ends(with: empty, by: areEquivalent))
}
func testEmptyDoesNotEndWithNonempty() {
XCTAssertFalse([].ends(with: nonEq(1...10), by: areEquivalent))
}
private func nonEq(_ range: ClosedRange<Int>) -> [NotEquatable<Int>] {
range.map(NotEquatable.init)
}
private func areEquivalent<T: Equatable>(
lhs: NotEquatable<T>, rhs: NotEquatable<T>
) -> Bool {
lhs.value == rhs.value
}
private struct NotEquatable<T> {
let value: T
}
}
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class FirstNonNilTests: XCTestCase { final class FirstNonNilTests: XCTestCase {
func testFirstNonNil() { func testFirstNonNil() {
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class GroupedTests: XCTestCase { final class GroupedTests: XCTestCase {
private final class SampleError: Error {} private final class SampleError: Error {}
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class IndexedTests: XCTestCase { final class IndexedTests: XCTestCase {
func testIndexed() { func testIndexed() {
@@ -27,8 +27,8 @@ final class IndexedTests: XCTestCase {
let indexOfI = si.last(where: { $0.element == "I" })!.index let indexOfI = si.last(where: { $0.element == "I" })!.index
XCTAssertEqual("I", s[indexOfI]) XCTAssertEqual("I", s[indexOfI])
} }
func testIndexedLazy() { func testIndexedLazy() {
requireLazyCollection("ABCD".lazy.indexed()) XCTAssertLazyCollection("ABCD".lazy.indexed())
} }
} }
@@ -10,50 +10,49 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class IntersperseTests: XCTestCase { final class IntersperseTests: XCTestCase {
func testSequence() { func testSequence() {
let interspersed = (1...).prefix(5).interspersed(with: 0) let interspersed = (1...).prefix(5).interspersed(with: 0)
expectEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4, 0, 5]) XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4,0,5])
} }
func testSequenceEmpty() { func testSequenceEmpty() {
let interspersed = (1...).prefix(0).interspersed(with: 0) let interspersed = (1...).prefix(0).interspersed(with: 0)
expectEqualSequences(interspersed, []) XCTAssertEqualSequences(interspersed, [])
} }
func testString() { func testString() {
let interspersed = "ABCDE".interspersed(with: "-") let interspersed = "ABCDE".interspersed(with: "-")
expectEqualSequences(interspersed, "A-B-C-D-E") XCTAssertEqualSequences(interspersed, "A-B-C-D-E")
} }
func testStringEmpty() { func testStringEmpty() {
let interspersed = "".interspersed(with: "-") let interspersed = "".interspersed(with: "-")
expectEqualSequences(interspersed, "") XCTAssertEqualSequences(interspersed, "")
} }
func testArray() { func testArray() {
let interspersed = [1, 2, 3, 4].interspersed(with: 0) let interspersed = [1,2,3,4].interspersed(with: 0)
expectEqualSequences(interspersed, [1, 0, 2, 0, 3, 0, 4]) XCTAssertEqualSequences(interspersed, [1,0,2,0,3,0,4])
} }
func testArrayEmpty() { func testArrayEmpty() {
let interspersed = [].interspersed(with: 0) let interspersed = [].interspersed(with: 0)
expectEqualSequences(interspersed, []) XCTAssertEqualSequences(interspersed, [])
} }
func testCollection() { func testCollection() {
let interspersed = ["A", "B", "C", "D"].interspersed(with: "-") let interspersed = ["A","B","C","D"].interspersed(with: "-")
XCTAssertEqual(interspersed.count, 7) XCTAssertEqual(interspersed.count, 7)
} }
func testBidirectionalCollection() { func testBidirectionalCollection() {
let reversed = "ABCDE".interspersed(with: "-").reversed() let reversed = "ABCDE".interspersed(with: "-").reversed()
expectEqualSequences(reversed, "E-D-C-B-A") XCTAssertEqualSequences(reversed, "E-D-C-B-A")
} }
func testIndexTraversals() { func testIndexTraversals() {
let validator = IndexValidator<InterspersedSequence<String>>() let validator = IndexValidator<InterspersedSequence<String>>()
validator.validate("".interspersed(with: "-"), expectedCount: 0) validator.validate("".interspersed(with: "-"), expectedCount: 0)
@@ -63,44 +62,42 @@ final class IntersperseTests: XCTestCase {
} }
func testIntersperseLazy() { func testIntersperseLazy() {
requireLazySequence((1...).prefix(0).lazy.interspersed(with: 0)) XCTAssertLazySequence((1...).prefix(0).lazy.interspersed(with: 0))
requireLazyCollection("ABCDE".lazy.interspersed(with: "-")) XCTAssertLazyCollection("ABCDE".lazy.interspersed(with: "-"))
} }
func testInterspersedMap() { func testInterspersedMap() {
expectEqualSequences( XCTAssertEqualSequences(
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
[]) [])
expectEqualSequences( XCTAssertEqualSequences(
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }),
[0]) [0])
expectEqualSequences( XCTAssertEqualSequences(
(0..<5).lazy.interspersedMap({ $0 }, with: { $0 + $1 + 100 }), (0..<5).lazy.interspersedMap({ $0 }, with: { $0 + $1 + 100 }),
[0, 101, 1, 103, 2, 105, 3, 107, 4]) [0, 101, 1, 103, 2, 105, 3, 107, 4])
} }
func testInterspersedMapLazy() { func testInterspersedMapLazy() {
requireLazySequence( XCTAssertLazySequence(AnySequence([]).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
AnySequence([]).lazy.interspersedMap({ $0 }, with: { _, _ in 100 })) XCTAssertLazyCollection((0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
requireLazyCollection(
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }))
} }
func testInterspersedMapIndexTraversals() { func testInterspersedMapIndexTraversals() {
let validator = IndexValidator<InterspersedMapSequence<Range<Int>, Int>>() let validator = IndexValidator<InterspersedMapSequence<Range<Int>, Int>>()
validator.validate( validator.validate(
(0..<0).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<0).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
expectedCount: 0) expectedCount: 0)
validator.validate( validator.validate(
(0..<1).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<1).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
expectedCount: 1) expectedCount: 1)
validator.validate( validator.validate(
(0..<2).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<2).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
expectedCount: 3) expectedCount: 3)
validator.validate( validator.validate(
(0..<5).lazy.interspersedMap({ $0 }, with: { _, _ in 100 }), (0..<5).lazy.interspersedMap({ $0 }, with: {_, _ in 100 }),
expectedCount: 9) expectedCount: 9)
} }
} }
+49 -64
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class JoinedTests: XCTestCase { final class JoinedTests: XCTestCase {
@@ -22,124 +21,110 @@ final class JoinedTests: XCTestCase {
["foo", "bar"], ["foo", "bar"],
["", "", "foo", "", "bar", "baz", ""], ["", "", "foo", "", "bar", "baz", ""],
] ]
func testJoined() { func testJoined() {
let expected = ["", "", "", "foo", "foobar", "foobarbaz"] let expected = ["", "", "", "foo", "foobar", "foobarbaz"]
for (strings, expected) in zip(stringArrays, expected) { for (strings, expected) in zip(stringArrays, expected) {
// regular sequence // regular sequence
expectEqualSequences(AnySequence(strings).joined(), expected) XCTAssertEqualSequences(AnySequence(strings).joined(), expected)
// lazy sequence // lazy sequence
expectEqualSequences(AnySequence(strings).lazy.joined(), expected) XCTAssertEqualSequences(AnySequence(strings).lazy.joined(), expected)
// regular collection // regular collection
expectEqualSequences(strings.joined(), expected) XCTAssertEqualSequences(strings.joined(), expected)
// lazy collection // lazy collection
expectEqualSequences( XCTAssertEqualSequences(strings.lazy.joined() as FlattenCollection, expected)
strings.lazy.joined() as FlattenCollection, expected)
} }
} }
func testJoinedByElement() { func testJoinedByElement() {
let separator: Character = " " let separator: Character = " "
let expected = ["", "", " ", "foo", "foo bar", " foo bar baz "] let expected = ["", "", " ", "foo", "foo bar", " foo bar baz "]
for (strings, expected) in zip(stringArrays, expected) { for (strings, expected) in zip(stringArrays, expected) {
expectEqualSequences( XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
AnySequence(strings).joined(by: separator), expected) XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
expectEqualSequences( XCTAssertEqualSequences(strings.joined(by: separator), expected)
AnySequence(strings).lazy.joined(by: separator), expected) XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
expectEqualSequences(strings.joined(by: separator), expected)
expectEqualSequences(strings.lazy.joined(by: separator), expected)
} }
} }
func testJoinedBySequence() { func testJoinedBySequence() {
let separator = ", " let separator = ", "
let expected = ["", "", ", ", "foo", "foo, bar", ", , foo, , bar, baz, "] let expected = ["", "", ", ", "foo", "foo, bar", ", , foo, , bar, baz, "]
for (strings, expected) in zip(stringArrays, expected) { for (strings, expected) in zip(stringArrays, expected) {
expectEqualSequences( XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
AnySequence(strings).joined(by: separator), expected) XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
expectEqualSequences( XCTAssertEqualSequences(strings.joined(by: separator), expected)
AnySequence(strings).lazy.joined(by: separator), expected) XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
expectEqualSequences(strings.joined(by: separator), expected)
expectEqualSequences(strings.lazy.joined(by: separator), expected)
} }
} }
func testJoinedByElementClosure() { func testJoinedByElementClosure() {
let separator = { (left: String, right: String) -> Character in let separator = { (left: String, right: String) -> Character in
left.isEmpty || right.isEmpty ? " " : "-" left.isEmpty || right.isEmpty ? " " : "-"
} }
let expected = ["", "", " ", "foo", "foo-bar", " foo bar-baz "] let expected = ["", "", " ", "foo", "foo-bar", " foo bar-baz "]
for (strings, expected) in zip(stringArrays, expected) { for (strings, expected) in zip(stringArrays, expected) {
expectEqualSequences( XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
AnySequence(strings).joined(by: separator), expected) XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
expectEqualSequences( XCTAssertEqualSequences(strings.joined(by: separator), expected)
AnySequence(strings).lazy.joined(by: separator), expected) XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
expectEqualSequences(strings.joined(by: separator), expected)
expectEqualSequences(strings.lazy.joined(by: separator), expected)
} }
} }
func testJoinedBySequenceClosure() { func testJoinedBySequenceClosure() {
let separator = { (left: String, right: String) in let separator = { (left: String, right: String) in
"(\(left.count), \(right.count))" "(\(left.count), \(right.count))"
} }
let expected = [ let expected = [
"", "",
"", "",
"(0, 0)", "(0, 0)",
"foo", "foo",
"foo(3, 3)bar", "foo(3, 3)bar",
"(0, 0)(0, 3)foo(3, 0)(0, 3)bar(3, 3)baz(3, 0)", "(0, 0)(0, 3)foo(3, 0)(0, 3)bar(3, 3)baz(3, 0)"
] ]
for (strings, expected) in zip(stringArrays, expected) { for (strings, expected) in zip(stringArrays, expected) {
expectEqualSequences( XCTAssertEqualSequences(AnySequence(strings).joined(by: separator), expected)
AnySequence(strings).joined(by: separator), expected) XCTAssertEqualSequences(AnySequence(strings).lazy.joined(by: separator), expected)
expectEqualSequences( XCTAssertEqualSequences(strings.joined(by: separator), expected)
AnySequence(strings).lazy.joined(by: separator), expected) XCTAssertEqualSequences(strings.lazy.joined(by: separator), expected)
expectEqualSequences(strings.joined(by: separator), expected)
expectEqualSequences(strings.lazy.joined(by: separator), expected)
} }
} }
func testJoinedLazy() { func testJoinedLazy() {
requireLazySequence(AnySequence([[1], [2]]).lazy.joined()) XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined())
requireLazySequence(AnySequence([[1], [2]]).lazy.joined(by: 1)) XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: 1))
requireLazySequence( XCTAssertLazySequence(AnySequence([[1], [2]]).lazy.joined(by: { _, _ in 1 }))
AnySequence([[1], [2]]).lazy.joined(by: { _, _ in 1 })) XCTAssertLazyCollection([[1], [2]].lazy.joined())
requireLazyCollection([[1], [2]].lazy.joined()) XCTAssertLazyCollection([[1], [2]].lazy.joined(by: 1))
requireLazyCollection([[1], [2]].lazy.joined(by: 1)) XCTAssertLazyCollection([[1], [2]].lazy.joined(by: { _, _ in 1 }))
requireLazyCollection([[1], [2]].lazy.joined(by: { _, _ in 1 }))
} }
func testJoinedIndexTraversals() { func testJoinedIndexTraversals() {
let validator = IndexValidator<FlattenCollection<[String]>>() let validator = IndexValidator<FlattenCollection<[String]>>()
// the last test case takes too long to run // the last test case takes too long to run
for strings in stringArrays.dropLast() { for strings in stringArrays.dropLast() {
validator.validate(strings.joined() as FlattenCollection) validator.validate(strings.joined() as FlattenCollection)
} }
} }
func testJoinedByIndexTraversals() { func testJoinedByIndexTraversals() {
let validator1 = IndexValidator<JoinedByCollection<[String], String>>() let validator1 = IndexValidator<JoinedByCollection<[String], String>>()
let validator2 = IndexValidator< let validator2 = IndexValidator<JoinedByClosureCollection<[String], String>>()
JoinedByClosureCollection<[String], String>
>()
// the last test case takes too long to run // the last test case takes too long to run
for (strings, separator) in product( for (strings, separator) in product(stringArrays.dropLast(), ["", " ", ", "]) {
stringArrays.dropLast(), ["", " ", ", "])
{
validator1.validate(strings.joined(by: separator)) validator1.validate(strings.joined(by: separator))
validator2.validate(strings.lazy.joined(by: { _, _ in separator })) validator2.validate(strings.lazy.joined(by: { _, _ in separator }))
} }
+5 -10
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class KeyedTests: XCTestCase { final class KeyedTests: XCTestCase {
private final class SampleError: Error {} private final class SampleError: Error {}
@@ -32,16 +32,13 @@ final class KeyedTests: XCTestCase {
func testNonUniqueKeys() throws { func testNonUniqueKeys() throws {
let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! }) let d = ["Apple", "Avocado", "Banana", "Cherry"].keyed(by: { $0.first! })
XCTAssertEqual(d.count, 3) XCTAssertEqual(d.count, 3)
XCTAssertEqual( XCTAssertEqual(d["A"]!, "Avocado", "On a key-collision, keyed(by:) should take the latest value.")
d["A"]!, "Avocado",
"On a key-collision, keyed(by:) should take the latest value.")
XCTAssertEqual(d["B"]!, "Banana") XCTAssertEqual(d["B"]!, "Banana")
XCTAssertEqual(d["C"]!, "Cherry") XCTAssertEqual(d["C"]!, "Cherry")
} }
func testNonUniqueKeysWithMergeFunction() { func testNonUniqueKeysWithMergeFunction() {
var resolveCallHistory: [(key: Character, current: String, new: String)] = var resolveCallHistory = [(key: Character, current: String, new: String)]()
[]
let expectedCallHistory = [ let expectedCallHistory = [
(key: "A", current: "Apple", new: "Avocado"), (key: "A", current: "Apple", new: "Avocado"),
(key: "C", current: "Cherry", new: "Coconut"), (key: "C", current: "Cherry", new: "Coconut"),
@@ -61,9 +58,8 @@ final class KeyedTests: XCTestCase {
XCTAssertEqual(d["C"]!, "Cherry-Coconut") XCTAssertEqual(d["C"]!, "Cherry-Coconut")
XCTAssertNil(d["D"]) XCTAssertNil(d["D"])
// Quick/dirty workaround: tuples aren't Equatable
XCTAssertEqual( XCTAssertEqual(
resolveCallHistory.map(String.init(describing:)), resolveCallHistory.map(String.init(describing:)), // quick/dirty workaround: tuples aren't Equatable
expectedCallHistory.map(String.init(describing:)) expectedCallHistory.map(String.init(describing:))
) )
} }
@@ -84,8 +80,7 @@ final class KeyedTests: XCTestCase {
let error = SampleError() let error = SampleError()
XCTAssertThrowsError( XCTAssertThrowsError(
try input.keyed( try input.keyed(by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error })
by: { $0.first! }, resolvingConflictsWith: { _, _, _ in throw error })
) { thrownError in ) { thrownError in
XCTAssertIdentical(error, thrownError as? SampleError) XCTAssertIdentical(error, thrownError as? SampleError)
} }
+55 -63
View File
@@ -9,41 +9,41 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class SortedPrefixTests: XCTestCase { final class SortedPrefixTests: XCTestCase {
func testMinCount() { func testMinCount() {
// Replacement at start and end // Replacement at start and end
let input = [10, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 0, 7, 8, 9] let input = [10, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 0, 7, 8, 9]
let min = input.min(count: 5) let min = input.min(count: 5)
expectEqualSequences(min, 0..<5) XCTAssertEqualSequences(min, 0..<5)
// Stability with all equal values // Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100) let maxZeroes = Array(repeating: 0, count: 100)
.enumerated() .enumerated()
.max(count: 5, sortedBy: { $0.element < $1.element }) .max(count: 5, sortedBy: { $0.element < $1.element })
expectEqualSequences(maxZeroes.map { $0.offset }, 95..<100) XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
} }
func testMaxCount() { func testMaxCount() {
// Replacement at start and end // Replacement at start and end
let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10] let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10]
let max = input.max(count: 5) let max = input.max(count: 5)
expectEqualSequences(max, 10..<15) XCTAssertEqualSequences(max, 10..<15)
// Stability with all equal values // Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100) let maxZeroes = Array(repeating: 0, count: 100)
.enumerated() .enumerated()
.max(count: 5, sortedBy: { $0.element < $1.element }) .max(count: 5, sortedBy: { $0.element < $1.element })
expectEqualSequences(maxZeroes.map { $0.offset }, 95..<100) XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
} }
func testEmpty() { func testEmpty() {
let array: [Int] = [] let array = [Int]()
XCTAssertEqual(array.min(count: 0), []) XCTAssertEqual(array.min(count: 0), [])
XCTAssertEqual(array.min(count: 100), []) XCTAssertEqual(array.min(count: 100), [])
XCTAssertEqual(array.max(count: 0), []) XCTAssertEqual(array.max(count: 0), [])
XCTAssertEqual(array.max(count: 100), []) XCTAssertEqual(array.max(count: 100), [])
} }
@@ -51,23 +51,23 @@ final class SortedPrefixTests: XCTestCase {
func testMinMaxSequences() { func testMinMaxSequences() {
let input = (1...100).shuffled().interspersed(with: 50) let input = (1...100).shuffled().interspersed(with: 50)
let seq = AnySequence(input) let seq = AnySequence(input)
expectEqualSequences(seq.min(count: 0), []) XCTAssertEqualSequences(seq.min(count: 0), [])
expectEqualSequences(seq.min(count: 5), 1...5) XCTAssertEqualSequences(seq.min(count: 5), 1...5)
expectEqualSequences(seq.max(count: 0), []) XCTAssertEqualSequences(seq.max(count: 0), [])
expectEqualSequences(seq.max(count: 5), 96...100) XCTAssertEqualSequences(seq.max(count: 5), 96...100)
} }
func testSortedPrefixComparable() { func testSortedPrefixComparable() {
let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90] let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90]
XCTAssertEqual(array.min(count: 0), []) XCTAssertEqual(array.min(count: 0), [])
XCTAssertEqual(array.min(count: 1), [1]) XCTAssertEqual(array.min(count: 1), [1])
expectEqualSequences(array.min(count: 5), array.sorted().prefix(5)) XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5))
XCTAssertEqual(array.min(count: 10), array.sorted()) XCTAssertEqual(array.min(count: 10), array.sorted())
} }
func testMinMaxWithHugeCount() { func testMinMaxWithHugeCount() {
XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4]) XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4])
XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4]) XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4])
@@ -83,20 +83,20 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.min(count: 1, sortedBy: <), [range.lowerBound]) XCTAssertEqual(input.min(count: 1, sortedBy: <), [range.lowerBound])
XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound]) XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound])
expectEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5)) XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5))
expectEqualSequences( XCTAssertEqualSequences(
input.min(count: 5, sortedBy: >), input.min(count: 5, sortedBy: >),
range.suffix(5).reversed()) range.suffix(5).reversed())
expectEqualSequences( XCTAssertEqualSequences(
input.min(count: 500, sortedBy: <), input.min(count: 500, sortedBy: <),
range.prefix(500)) range.prefix(500))
expectEqualSequences( XCTAssertEqualSequences(
input.min(count: 500, sortedBy: >), input.min(count: 500, sortedBy: >),
range.suffix(500).reversed()) range.suffix(500).reversed())
expectEqualSequences(input.min(count: 1000, sortedBy: <), range) XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range)
expectEqualSequences( XCTAssertEqualSequences(
input.min(count: 1000, sortedBy: >), input.min(count: 1000, sortedBy: >),
range.reversed()) range.reversed())
} }
@@ -111,60 +111,52 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.max(count: 1, sortedBy: <), [range.upperBound]) XCTAssertEqual(input.max(count: 1, sortedBy: <), [range.upperBound])
XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound]) XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound])
expectEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5)) XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5))
expectEqualSequences( XCTAssertEqualSequences(
input.max(count: 5, sortedBy: >), input.max(count: 5, sortedBy: >),
range.prefix(5).reversed()) range.prefix(5).reversed())
expectEqualSequences( XCTAssertEqualSequences(
input.max(count: 500, sortedBy: <), input.max(count: 500, sortedBy: <),
range.suffix(500)) range.suffix(500))
expectEqualSequences( XCTAssertEqualSequences(
input.max(count: 500, sortedBy: >), input.max(count: 500, sortedBy: >),
range.prefix(500).reversed()) range.prefix(500).reversed())
expectEqualSequences(input.max(count: 1000, sortedBy: <), range) XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range)
expectEqualSequences( XCTAssertEqualSequences(
input.max(count: 1000, sortedBy: >), input.max(count: 1000, sortedBy: >),
range.reversed()) range.reversed())
} }
func testStability() { func testStability() {
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 3) assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 3)
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 6) assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 6)
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 20) assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 20)
assertStability([1, 1, 1, 2, 5, 7, 3, 6, 2, 5, 7, 3, 6], withCount: 1000) assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 1000)
assertStability(Array(repeating: 0, count: 100), withCount: 0) assertStability(Array(repeating: 0, count: 100), withCount: 0)
assertStability(Array(repeating: 0, count: 100), withCount: 1) assertStability(Array(repeating: 0, count: 100), withCount: 1)
assertStability(Array(repeating: 0, count: 100), withCount: 2) assertStability(Array(repeating: 0, count: 100), withCount: 2)
assertStability(Array(repeating: 0, count: 100), withCount: 5) assertStability(Array(repeating: 0, count: 100), withCount: 5)
assertStability(Array(repeating: 0, count: 100), withCount: 20) assertStability(Array(repeating: 0, count: 100), withCount: 20)
assertStability(Array(repeating: 0, count: 100), withCount: 100) assertStability(Array(repeating: 0, count: 100), withCount: 100)
assertStability( assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 2)
Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5)
withCount: 2) assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20)
assertStability( assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50)
Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), assertStability([0,0], withCount: 1)
withCount: 5) assertStability([0,0], withCount: 2)
assertStability( assertStability([0,1,0,1,0,1], withCount: 2)
Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), assertStability([0,1,0,1,0,1], withCount: 6)
withCount: 20) assertStability([0,0,0,1,1,1], withCount: 1)
assertStability( assertStability([0,0,0,1,1,1], withCount: 3)
Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), assertStability([0,0,0,1,1,1], withCount: 4)
withCount: 50) assertStability([0,0,0,1,1,1], withCount: 6)
assertStability([0, 0], withCount: 1) assertStability([1,1,1,0,0,0], withCount: 1)
assertStability([0, 0], withCount: 2) assertStability([1,1,1,0,0,0], withCount: 3)
assertStability([0, 1, 0, 1, 0, 1], withCount: 2) assertStability([1,1,1,0,0,0], withCount: 4)
assertStability([0, 1, 0, 1, 0, 1], withCount: 6) assertStability([1,1,1,0,0,0], withCount: 6)
assertStability([0, 0, 0, 1, 1, 1], withCount: 1) assertStability([1,1,1,0,0,0], withCount: 5)
assertStability([0, 0, 0, 1, 1, 1], withCount: 3)
assertStability([0, 0, 0, 1, 1, 1], withCount: 4)
assertStability([0, 0, 0, 1, 1, 1], withCount: 6)
assertStability([1, 1, 1, 0, 0, 0], withCount: 1)
assertStability([1, 1, 1, 0, 0, 0], withCount: 3)
assertStability([1, 1, 1, 0, 0, 0], withCount: 4)
assertStability([1, 1, 1, 0, 0, 0], withCount: 6)
assertStability([1, 1, 1, 0, 0, 0], withCount: 5)
} }
func assertStability( func assertStability(
@@ -173,19 +165,19 @@ final class SortedPrefixTests: XCTestCase {
) { ) {
func stableOrder( func stableOrder(
a: (offset: Int, element: Int), a: (offset: Int, element: Int),
b: (offset: Int, element: Int) b: (offset: Int, element: Int)) -> Bool
) -> Bool { {
a.element == b.element a.element == b.element
? a.offset < b.offset ? a.offset < b.offset
: a.element < b.element : a.element < b.element
} }
do { do {
let sorted = actual.enumerated() let sorted = actual.enumerated()
.min(count: count) { $0.element < $1.element } .min(count: count) { $0.element < $1.element }
XCTAssert(sorted.isSorted(by: stableOrder)) XCTAssert(sorted.isSorted(by: stableOrder))
} }
do { do {
let sorted = actual.enumerated() let sorted = actual.enumerated()
.max(count: count) { $0.element < $1.element } .max(count: count) { $0.element < $1.element }
+47 -63
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class PartitionTests: XCTestCase { final class PartitionTests: XCTestCase {
func testStablePartition() { func testStablePartition() {
@@ -30,17 +30,17 @@ final class PartitionTests: XCTestCase {
var b = a var b = a
var r = b[p..<q].stablePartition(by: f) var r = b[p..<q].stablePartition(by: f)
expectEqualSequences(b[..<p], prefix) XCTAssertEqualSequences(b[..<p], prefix)
expectEqualSequences(b[q...], suffix) XCTAssertEqualSequences(b[q...], suffix)
expectEqualSequences(b[p..<r], subrange.filter(notf)) XCTAssertEqualSequences(b[p..<r], subrange.filter(notf))
expectEqualSequences(b[r..<q], subrange.filter(f)) XCTAssertEqualSequences(b[r..<q], subrange.filter(f))
b = a b = a
r = b[p..<q].stablePartition(by: notf) r = b[p..<q].stablePartition(by: notf)
expectEqualSequences(b[..<p], prefix) XCTAssertEqualSequences(b[..<p], prefix)
expectEqualSequences(b[q...], suffix) XCTAssertEqualSequences(b[q...], suffix)
expectEqualSequences(b[p..<r], subrange.filter(f)) XCTAssertEqualSequences(b[p..<r], subrange.filter(f))
expectEqualSequences(b[r..<q], subrange.filter(notf)) XCTAssertEqualSequences(b[r..<q], subrange.filter(notf))
} }
} }
@@ -49,18 +49,18 @@ final class PartitionTests: XCTestCase {
let notf = { !f($0) } let notf = { !f($0) }
var b = a var b = a
var r = b.stablePartition(by: f) var r = b.stablePartition(by: f)
expectEqualSequences(b[..<r], a.filter(notf)) XCTAssertEqualSequences(b[..<r], a.filter(notf))
expectEqualSequences(b[r...], a.filter(f)) XCTAssertEqualSequences(b[r...], a.filter(f))
b = a b = a
r = b.stablePartition(by: notf) r = b.stablePartition(by: notf)
expectEqualSequences(b[..<r], a.filter(f)) XCTAssertEqualSequences(b[..<r], a.filter(f))
expectEqualSequences(b[r...], a.filter(notf)) XCTAssertEqualSequences(b[r...], a.filter(notf))
} }
} }
} }
} }
func testStablePartitionWithSubrange() { func testStablePartitionWithSubrange() {
for length in 10...20 { for length in 10...20 {
let a = Array(0..<length) let a = Array(0..<length)
@@ -72,17 +72,13 @@ final class PartitionTests: XCTestCase {
let p = b.stablePartition(subrange: partitionRange, by: condition) let p = b.stablePartition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
expectEqualSequences( XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
b[partitionRange.lowerBound..<p], XCTAssertEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
a[partitionRange].filter { !condition($0) })
expectEqualSequences(
b[p..<partitionRange.upperBound],
a[partitionRange].filter(condition))
} }
} }
} }
} }
func testPartitioningIndex() { func testPartitioningIndex() {
for i in 0..<7 { for i in 0..<7 {
for j in i..<11 { for j in i..<11 {
@@ -95,27 +91,27 @@ final class PartitionTests: XCTestCase {
} }
} }
} }
func testPartitioningIndexWithEmptyInput() { func testPartitioningIndexWithEmptyInput() {
let input: [Int] = [] let input: [Int] = []
let a = input.partitioningIndex(where: { _ in true }) let a = input.partitioningIndex(where: { _ in return true })
XCTAssertEqual(a, input.startIndex) XCTAssertEqual(a, input.startIndex)
let b = input.partitioningIndex(where: { _ in false }) let b = input.partitioningIndex(where: { _ in return false })
XCTAssertEqual(b, input.endIndex) XCTAssertEqual(b, input.endIndex)
} }
func testPartitioningIndexWithOneEmptyPartition() { func testPartitioningIndexWithOneEmptyPartition() {
let input: Range<Int> = (0..<10) let input: Range<Int> = (0 ..< 10)
let a = input.partitioningIndex(where: { $0 > 10 }) let a = input.partitioningIndex(where: { $0 > 10 })
XCTAssertEqual(a, input.endIndex) XCTAssertEqual(a, input.endIndex)
let b = input.partitioningIndex(where: { $0 >= 0 }) let b = input.partitioningIndex(where: { $0 >= 0 })
XCTAssertEqual(b, input.startIndex) XCTAssertEqual(b, input.startIndex)
} }
func testPartitionWithSubrangeBidirectionalCollection() { func testPartitionWithSubrangeBidirectionalCollection() {
for length in 10...20 { for length in 10...20 {
let a = Array(0..<length) let a = Array(0..<length)
@@ -125,14 +121,10 @@ final class PartitionTests: XCTestCase {
let partitionRange = j..<i let partitionRange = j..<i
let condition = { $0 < i - 1 } let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition) let p = b.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
expectEqualSequences( XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
b[partitionRange.lowerBound..<p], XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
a[partitionRange].filter { !condition($0) })
expectUnorderedEqualSequences(
b[p..<partitionRange.upperBound],
a[partitionRange].filter(condition))
} }
} }
} }
@@ -149,59 +141,51 @@ final class PartitionTests: XCTestCase {
let condition = { $0 < i - 1 } let condition = { $0 < i - 1 }
let p = b.partition(subrange: partitionRange, by: condition) let p = b.partition(subrange: partitionRange, by: condition)
let bdcp = bdc.partition(subrange: partitionRange, by: condition) let bdcp = bdc.partition(subrange: partitionRange, by: condition)
XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1) XCTAssertEqual(p, partitionRange.count == 0 ? j : j + 1)
expectEqualSequences( XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], a[partitionRange].filter { !condition($0) })
b[partitionRange.lowerBound..<p], XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], a[partitionRange].filter(condition))
a[partitionRange].filter { !condition($0) })
expectUnorderedEqualSequences(
b[p..<partitionRange.upperBound],
a[partitionRange].filter(condition))
// Must produce the same result as the `BidirectionalCollection` specialized overload. // Must produce the same result as the `BidirectionalCollection` specialized overload.
expectEqualSequences( XCTAssertEqualSequences(b[partitionRange.lowerBound..<p], bdc[partitionRange.lowerBound..<bdcp])
b[partitionRange.lowerBound..<p], XCTAssertUnorderedEqualSequences(b[p..<partitionRange.upperBound], bdc[bdcp..<partitionRange.upperBound])
bdc[partitionRange.lowerBound..<bdcp])
expectUnorderedEqualSequences(
b[p..<partitionRange.upperBound],
bdc[bdcp..<partitionRange.upperBound])
} }
} }
} }
} }
func testPartitionedWithEmptyInput() { func testPartitionedWithEmptyInput() {
let input: [Int] = [] let input: [Int] = []
let s0 = input.partitioned(by: { _ in true }) let s0 = input.partitioned(by: { _ in return true })
XCTAssertTrue(s0.0.isEmpty) XCTAssertTrue(s0.0.isEmpty)
XCTAssertTrue(s0.1.isEmpty) XCTAssertTrue(s0.1.isEmpty)
} }
/// Test the example given in the `partitioned(by:)` documentation. /// Test the example given in the `partitioned(by:)` documentation
func testPartitionedExample() throws { func testPartitionedExample() throws {
let cast = ["Vivien", "Marlon", "Kim", "Karl"] let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 }) let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
XCTAssertEqual(longNames, ["Vivien", "Marlon"]) XCTAssertEqual(longNames, ["Vivien", "Marlon"])
XCTAssertEqual(shortNames, ["Kim", "Karl"]) XCTAssertEqual(shortNames, ["Kim", "Karl"])
} }
func testPartitionedWithPredicate() throws { func testPartitionedWithPredicate() throws {
let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() }) let s0 = ["A", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() }) let s1 = ["a", "B", "C", "D"].partitioned(by: { $0 == $0.lowercased() })
let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() }) let s2 = ["a", "B", "c", "D"].partitioned(by: { $0 == $0.lowercased() })
let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() }) let s3 = ["a", "B", "c", "d"].partitioned(by: { $0 == $0.lowercased() })
XCTAssertEqual(s0.0, ["A", "B", "C", "D"]) XCTAssertEqual(s0.0, ["A", "B", "C", "D"])
XCTAssertEqual(s0.1, []) XCTAssertEqual(s0.1, [])
XCTAssertEqual(s1.0, ["B", "C", "D"]) XCTAssertEqual(s1.0, ["B", "C", "D"])
XCTAssertEqual(s1.1, ["a"]) XCTAssertEqual(s1.1, ["a"])
XCTAssertEqual(s2.0, ["B", "D"]) XCTAssertEqual(s2.0, ["B", "D"])
XCTAssertEqual(s2.1, ["a", "c"]) XCTAssertEqual(s2.1, ["a", "c"])
XCTAssertEqual(s3.0, ["B"]) XCTAssertEqual(s3.0, ["B"])
XCTAssertEqual(s3.1, ["a", "c", "d"]) XCTAssertEqual(s3.1, ["a", "c", "d"])
} }
@@ -10,16 +10,15 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class PermutationsTests: XCTestCase { final class PermutationsTests: XCTestCase {
func testPermutations() { func testPermutations() {
let c = "ABCDE" let c = "ABCDE"
func t(count: Int?) { func t(count: Int?) {
let p = c.permutations(ofCount: count) let p = c.permutations(ofCount: count)
let count = count ?? c.count let count = count ?? c.count
let permCount = c.count.factorial() / (c.count - count).factorial() let permCount = c.count.factorial() / (c.count - count).factorial()
XCTAssertEqual(permCount, p.count) XCTAssertEqual(permCount, p.count)
@@ -27,20 +26,20 @@ final class PermutationsTests: XCTestCase {
XCTAssertTrue(p.allSatisfy { $0.count == count }) XCTAssertTrue(p.allSatisfy { $0.count == count })
XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) })) XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) }))
} }
func ts<R: RangeExpression>(count: R) where R.Bound == Int { func ts<R: RangeExpression>(count: R) where R.Bound == Int {
let p = count.relative(to: 0 ..< .max) let p = count.relative(to: 0 ..< .max)
.clamped(to: 0..<c.count + 1) .clamped(to: 0 ..< c.count + 1)
.flatMap { .flatMap {
c.permutations(ofCount: $0) c.permutations(ofCount: $0)
} }
let p2 = c.permutations(ofCount: count) let p2 = c.permutations(ofCount: count)
XCTAssertEqual(p.count, p2.count) XCTAssertEqual(p.count, p2.count)
expectEqualSequences(p, Array(p2)) XCTAssertEqualSequences(p, Array(p2))
} }
t(count: 0) t(count: 0)
t(count: 1) t(count: 1)
t(count: 2) t(count: 2)
@@ -48,7 +47,7 @@ final class PermutationsTests: XCTestCase {
t(count: 4) t(count: 4)
t(count: 5) t(count: 5)
t(count: nil) t(count: nil)
ts(count: 0...0) ts(count: 0...0)
ts(count: 1...1) ts(count: 1...1)
ts(count: 0...1) ts(count: 0...1)
@@ -61,7 +60,7 @@ final class PermutationsTests: XCTestCase {
ts(count: ...4) ts(count: ...4)
ts(count: ...6) ts(count: ...6)
} }
func testEmpty() { func testEmpty() {
// `k == 0` results in one zero-length permutation // `k == 0` results in one zero-length permutation
XCTAssertEqual(1, "".permutations().count) XCTAssertEqual(1, "".permutations().count)
@@ -71,7 +70,7 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]]) XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]]) XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]]) XCTAssertEqual(Array("ABCD".permutations(ofCount: 0...0)), [[]])
// `k` greater than element count results in zero permutations // `k` greater than element count results in zero permutations
XCTAssertEqual(0, "".permutations(ofCount: 5).count) XCTAssertEqual(0, "".permutations(ofCount: 5).count)
XCTAssertEqual(Array("".permutations(ofCount: 5)), []) XCTAssertEqual(Array("".permutations(ofCount: 5)), [])
@@ -80,10 +79,10 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), []) XCTAssertEqual(Array("ABCD".permutations(ofCount: 5..<7)), [])
XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), []) XCTAssertEqual(Array("ABCD".permutations(ofCount: 5...)), [])
} }
func testNextPermutation() { func testNextPermutation() {
var numbers = Array(1...7) var numbers = Array(1...7)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers) XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
@@ -96,122 +95,110 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers) XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers)
_ = numbers.nextPermutation() _ = numbers.nextPermutation()
XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers) XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers)
// Fast-forward to end of permutations. // Fast-forward to end of permutations.
while numbers.nextPermutation() {} while numbers.nextPermutation() {}
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers) XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
} }
func testPermutationsLazy() { func testPermutationsLazy() {
requireLazySequence("ABCD".lazy.permutations(ofCount: 2)) XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
} }
func testDocumentationExample1() { func testDocumentationExample1() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations() let permutations = numbers.permutations()
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, [10, 20, 30],
[ [10, 30, 20],
[10, 20, 30], [20, 10, 30],
[10, 30, 20], [20, 30, 10],
[20, 10, 30], [30, 10, 20],
[20, 30, 10], [30, 20, 10],
[30, 10, 20], ])
[30, 20, 10],
])
} }
func testDocumentationExample2() { func testDocumentationExample2() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations(ofCount: 2) let permutations = numbers.permutations(ofCount: 2)
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, [10, 20],
[ [10, 30],
[10, 20], [20, 10],
[10, 30], [20, 30],
[20, 10], [30, 10],
[20, 30], [30, 20],
[30, 10], ])
[30, 20],
])
} }
func testDocumentationExample3() { func testDocumentationExample3() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers2 = [20, 10, 10] let numbers2 = [20, 10, 10]
let permutations = numbers2.permutations() let permutations = numbers2.permutations()
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, [20, 10, 10],
[ [20, 10, 10],
[20, 10, 10], [10, 20, 10],
[20, 10, 10], [10, 10, 20],
[10, 20, 10], [10, 20, 10],
[10, 10, 20], [10, 10, 20],
[10, 20, 10], ])
[10, 10, 20],
])
} }
func testDocumentationExample4() { func testDocumentationExample4() {
// From Guides/Permutations.md // From Guides/Permutations.md
let numbers = [10, 20, 30] let numbers = [10, 20, 30]
let permutations = numbers.permutations(ofCount: 0...) let permutations = numbers.permutations(ofCount: 0...)
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, [],
[ [10],
[], [20],
[10], [30],
[20], [10, 20],
[30], [10, 30],
[10, 20], [20, 10],
[10, 30], [20, 30],
[20, 10], [30, 10],
[20, 30], [30, 20],
[30, 10], [10, 20, 30],
[30, 20], [10, 30, 20],
[10, 20, 30], [20, 10, 30],
[10, 30, 20], [20, 30, 10],
[20, 10, 30], [30, 10, 20],
[20, 30, 10], [30, 20, 10],
[30, 10, 20], ])
[30, 20, 10],
])
} }
func testDocumentationExample5() { func testDocumentationExample5() {
// From Permutations.swift // From Permutations.swift
let names = ["Alex", "Celeste", "Davide"] let names = ["Alex", "Celeste", "Davide"]
let permutations = names.permutations(ofCount: 2) let permutations = names.permutations(ofCount: 2)
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, ["Alex", "Celeste"],
[ ["Alex", "Davide"],
["Alex", "Celeste"], ["Celeste", "Alex"],
["Alex", "Davide"], ["Celeste", "Davide"],
["Celeste", "Alex"], ["Davide", "Alex"],
["Celeste", "Davide"], ["Davide", "Celeste"],
["Davide", "Alex"], ])
["Davide", "Celeste"],
])
} }
func testDocumentationExample6() { func testDocumentationExample6() {
// From Permutations.swift // From Permutations.swift
let names = ["Alex", "Celeste", "Davide"] let names = ["Alex", "Celeste", "Davide"]
let permutations = names.permutations(ofCount: 1...2) let permutations = names.permutations(ofCount: 1...2)
expectEqualSequences( XCTAssertEqualSequences(permutations, [
permutations, ["Alex"],
[ ["Celeste"],
["Alex"], ["Davide"],
["Celeste"], ["Alex", "Celeste"],
["Davide"], ["Alex", "Davide"],
["Alex", "Celeste"], ["Celeste", "Alex"],
["Alex", "Davide"], ["Celeste", "Davide"],
["Celeste", "Alex"], ["Davide", "Alex"],
["Celeste", "Davide"], ["Davide", "Celeste"],
["Davide", "Alex"], ])
["Davide", "Celeste"],
])
} }
} }
+10 -11
View File
@@ -10,35 +10,34 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class ProductTests: XCTestCase { final class ProductTests: XCTestCase {
func testProduct() { func testProduct() {
expectEqualSequences( XCTAssertEqualSequences(
[(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")], [(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")],
product(1...2, "AB"), product(1...2, "AB"),
by: ==) by: ==)
expectEqualSequences(product(1...10, ""), [], by: ==) XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
expectEqualSequences(product("", 1...10), [], by: ==) XCTAssertEqualSequences(product("", 1...10), [], by: ==)
} }
func testProductReversed() { func testProductReversed() {
expectEqualSequences( XCTAssertEqualSequences(
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")], [(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
product(1...2, "AB").reversed(), product(1...2, "AB").reversed(),
by: ==) by: ==)
expectEqualSequences(product(1...10, "").reversed(), [], by: ==) XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
expectEqualSequences(product("", 1...10).reversed(), [], by: ==) XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
} }
func testProductDistanceFromTo() { func testProductDistanceFromTo() {
let p = product([1, 2], "abc") let p = product([1, 2], "abc")
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6) XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
} }
func testProductIndexTraversals() { func testProductIndexTraversals() {
let validator = IndexValidator<Product2Sequence<[Int], String>>( let validator = IndexValidator<Product2Sequence<[Int], String>>(
indicesIncludingEnd: { product in indicesIncludingEnd: { product in
@@ -48,7 +47,7 @@ final class ProductTests: XCTestCase {
} }
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)] } + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
}) })
validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3) validator.validate(product([1, 2, 3, 4], "abc"), expectedCount: 4 * 3)
validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0) validator.validate(product([1, 2, 3, 4], ""), expectedCount: 4 * 0)
validator.validate(product([], "abc"), expectedCount: 0 * 3) validator.validate(product([], "abc"), expectedCount: 0 * 3)
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
func validateRandomSamples<S: Sequence>( func validateRandomSamples<S: Sequence>(
@@ -19,9 +18,8 @@ func validateRandomSamples<S: Sequence>(
expectedValue: Int, expectedValue: Int,
file: StaticString = (#file), line: UInt = #line file: StaticString = (#file), line: UInt = #line
) where S.Element == Int { ) where S.Element == Int {
let expectedRange = ((expectedValue / 3) * 2)...((expectedValue / 3) * 4) let expectedRange = ((expectedValue / 3) * 2) ... ((expectedValue / 3) * 4)
expectEqualSequences( XCTAssertEqualSequences(samples.keys.sorted(), elements,
samples.keys.sorted(), elements,
file: file, line: line) file: file, line: line)
for v in samples.values { for v in samples.values {
XCTAssert(expectedRange.contains(v), file: file, line: line) XCTAssert(expectedRange.contains(v), file: file, line: line)
@@ -43,44 +41,41 @@ final class RandomSampleTests: XCTestCase {
result[x, default: 0] += 1 result[x, default: 0] += 1
} }
} }
validateRandomSamples( validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
samples, elements: c, expectedValue: (k * iterations) / n)
} }
func testRandomSampleCollection() { func testRandomSampleCollection() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in c.randomSample(count: k) { for x in c.randomSample(count: k) {
result[x, default: 0] += 1 result[x, default: 0] += 1
} }
} }
validateRandomSamples( validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
samples, elements: c, expectedValue: (k * iterations) / n)
} }
func testRandomSampleSequence() { func testRandomSampleSequence() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in s.randomSample(count: k) { for x in s.randomSample(count: k) {
result[x, default: 0] += 1 result[x, default: 0] += 1
} }
} }
validateRandomSamples( validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
samples, elements: s, expectedValue: (k * iterations) / n)
} }
func testRandomSampleEdgeCases() { func testRandomSampleEdgeCases() {
XCTAssert(c.randomStableSample(count: 0).isEmpty) XCTAssert(c.randomStableSample(count: 0).isEmpty)
expectEqualSequences(c.randomStableSample(count: n), c) XCTAssertEqualSequences(c.randomStableSample(count: n), c)
expectEqualSequences(c.randomStableSample(count: n * 2), c) XCTAssertEqualSequences(c.randomStableSample(count: n * 2), c)
XCTAssert(c.randomSample(count: 0).isEmpty) XCTAssert(c.randomSample(count: 0).isEmpty)
expectEqualSequences(c.randomSample(count: n).sorted(), c) XCTAssertEqualSequences(c.randomSample(count: n).sorted(), c)
expectEqualSequences(c.randomSample(count: n * 2).sorted(), c) XCTAssertEqualSequences(c.randomSample(count: n * 2).sorted(), c)
XCTAssert(s.randomSample(count: 0).isEmpty) XCTAssert(s.randomSample(count: 0).isEmpty)
expectEqualSequences(s.randomSample(count: n).sorted(), c) XCTAssertEqualSequences(s.randomSample(count: n).sorted(), c)
expectEqualSequences(s.randomSample(count: n * 2).sorted(), c) XCTAssertEqualSequences(s.randomSample(count: n * 2).sorted(), c)
} }
func testRandomSampleRepeatable() { func testRandomSampleRepeatable() {
var generator = SplitMix64(seed: 0) var generator = SplitMix64(seed: 0)
let sample1a = c.randomSample(count: k, using: &generator) let sample1a = c.randomSample(count: k, using: &generator)
@@ -93,7 +88,7 @@ final class RandomSampleTests: XCTestCase {
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
let sample2b = s.randomSample(count: k, using: &generator) let sample2b = s.randomSample(count: k, using: &generator)
XCTAssertEqual(sample1b, sample2b) XCTAssertEqual(sample1b, sample2b)
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
let sample1c = c.randomStableSample(count: k, using: &generator) let sample1c = c.randomStableSample(count: k, using: &generator)
generator = SplitMix64(seed: 0) generator = SplitMix64(seed: 0)
@@ -106,7 +101,7 @@ final class RandomSampleTests: XCTestCase {
mutating func next() -> UInt64 { 0 } mutating func next() -> UInt64 { 0 }
} }
var zero = ZeroGenerator() var zero = ZeroGenerator()
_ = nextOffset(w: 1, using: &zero) // must not crash _ = nextOffset(w: 1, using: &zero) // must not crash
struct AlmostAllZeroGenerator: RandomNumberGenerator { struct AlmostAllZeroGenerator: RandomNumberGenerator {
private var forward: SplitMix64 private var forward: SplitMix64
@@ -124,8 +119,8 @@ final class RandomSampleTests: XCTestCase {
} }
var almostAllZero = AlmostAllZeroGenerator(seed: 0) var almostAllZero = AlmostAllZeroGenerator(seed: 0)
_ = s.randomSample(count: k, using: &almostAllZero) // must not crash _ = s.randomSample(count: k, using: &almostAllZero) // must not crash
almostAllZero = AlmostAllZeroGenerator(seed: 0) almostAllZero = AlmostAllZeroGenerator(seed: 0)
_ = c.randomSample(count: k, using: &almostAllZero) // must not crash _ = c.randomSample(count: k, using: &almostAllZero) // must not crash
} }
} }
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class ReductionsTests: XCTestCase { final class ReductionsTests: XCTestCase {
struct TestError: Error {} struct TestError: Error {}
@@ -18,26 +18,23 @@ final class ReductionsTests: XCTestCase {
// MARK: - Exclusive Reductions // MARK: - Exclusive Reductions
func testExclusiveLazy() { func testExclusiveLazy() {
expectEqualSequences( XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(0, +), [0, 1, 3, 6, 10])
(1...).prefix(4).lazy.reductions(0, +), [0, 1, 3, 6, 10]) XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(0, +), [0, 1])
expectEqualSequences((1...).prefix(1).lazy.reductions(0, +), [0, 1]) XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(0, +), [0])
expectEqualSequences((1...).prefix(0).lazy.reductions(0, +), [0])
expectEqualCollections( XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(0, +), [0, 1, 3, 6, 10])
[1, 2, 3, 4].lazy.reductions(0, +), [0, 1, 3, 6, 10]) XCTAssertEqualCollections([1].lazy.reductions(0, +), [0, 1])
expectEqualCollections([1].lazy.reductions(0, +), [0, 1]) XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
expectEqualCollections(EmptyCollection<Int>().lazy.reductions(0, +), [0])
XCTAssertEqual( XCTAssertEqual([1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
[1, 2, 3, 4].lazy.reductions(into: 0, +=), [0, 1, 3, 6, 10])
XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1]) XCTAssertEqual([1].lazy.reductions(into: 0, +=), [0, 1])
XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0]) XCTAssertEqual(EmptyCollection<Int>().lazy.reductions(into: 0, +=), [0])
requireLazySequence((1...).prefix(1).lazy.reductions(0, +)) XCTAssertLazySequence((1...).prefix(1).lazy.reductions(0, +))
requireLazySequence([1].lazy.reductions(0, +)) XCTAssertLazySequence([1].lazy.reductions(0, +))
requireLazyCollection([1].lazy.reductions(0, +)) XCTAssertLazyCollection([1].lazy.reductions(0, +))
} }
func testExclusiveEager() { func testExclusiveEager() {
@@ -54,11 +51,9 @@ final class ReductionsTests: XCTestCase {
XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() }) XCTAssertNoThrow(try [].reductions(0) { _, _ in throw TestError() })
XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() }) XCTAssertThrowsError(try [1].reductions(0) { _, _ in throw TestError() })
} }
func testExclusiveIndexTraversals() { func testExclusiveIndexTraversals() {
let validator = IndexValidator< let validator = IndexValidator<ExclusiveReductionsSequence<Range<Int>, Int>>()
ExclusiveReductionsSequence<Range<Int>, Int>
>()
validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1) validator.validate((0..<0).lazy.reductions(0, +), expectedCount: 1)
validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2) validator.validate((0..<1).lazy.reductions(0, +), expectedCount: 2)
validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5) validator.validate((0..<4).lazy.reductions(0, +), expectedCount: 5)
@@ -67,17 +62,17 @@ final class ReductionsTests: XCTestCase {
// MARK: - Inclusive Reductions // MARK: - Inclusive Reductions
func testInclusiveLazy() { func testInclusiveLazy() {
expectEqualSequences((1...).prefix(4).lazy.reductions(+), [1, 3, 6, 10]) XCTAssertEqualSequences((1...).prefix(4).lazy.reductions(+), [1, 3, 6, 10])
expectEqualSequences((1...).prefix(1).lazy.reductions(+), [1]) XCTAssertEqualSequences((1...).prefix(1).lazy.reductions(+), [1])
expectEqualSequences((1...).prefix(0).lazy.reductions(+), []) XCTAssertEqualSequences((1...).prefix(0).lazy.reductions(+), [])
expectEqualCollections([1, 2, 3, 4].lazy.reductions(+), [1, 3, 6, 10]) XCTAssertEqualCollections([1, 2, 3, 4].lazy.reductions(+), [1, 3, 6, 10])
expectEqualCollections([1].lazy.reductions(+), [1]) XCTAssertEqualCollections([1].lazy.reductions(+), [1])
expectEqualCollections(EmptyCollection<Int>().lazy.reductions(+), []) XCTAssertEqualCollections(EmptyCollection<Int>().lazy.reductions(+), [])
requireLazySequence((1...).prefix(1).lazy.reductions(+)) XCTAssertLazySequence((1...).prefix(1).lazy.reductions(+))
requireLazySequence([1].lazy.reductions(+)) XCTAssertLazySequence([1].lazy.reductions(+))
requireLazyCollection([1].lazy.reductions(+)) XCTAssertLazyCollection([1].lazy.reductions(+))
} }
func testInclusiveEager() { func testInclusiveEager() {
@@ -89,7 +84,7 @@ final class ReductionsTests: XCTestCase {
XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() }) XCTAssertNoThrow(try [1].reductions { _, _ in throw TestError() })
XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() }) XCTAssertThrowsError(try [1, 1].reductions { _, _ in throw TestError() })
} }
func testInclusiveIndexTraversals() { func testInclusiveIndexTraversals() {
let validator = IndexValidator<InclusiveReductionsSequence<Range<Int>>>() let validator = IndexValidator<InclusiveReductionsSequence<Range<Int>>>()
validator.validate((0..<0).lazy.reductions(+), expectedCount: 0) validator.validate((0..<0).lazy.reductions(+), expectedCount: 0)
+22 -32
View File
@@ -10,87 +10,77 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class RotateTests: XCTestCase { final class RotateTests: XCTestCase {
/// Tests the example given in the `_reverse(subrange:until:)` documentation. /// Tests the example given in `_reverse(subrange:until:)`’s documentation
func testUnderscoreReverse() { func testUnderscoreReverse() {
var input = [ var input = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p",
]
let limit: Int = 4 let limit: Int = 4
let (lower, upper) = input._reverse( let (lower, upper) = input._reverse(subrange: input.startIndex..<input.endIndex, until: input.startIndex.advanced(by: limit))
subrange: input.startIndex..<input.endIndex, let expected = ["p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b", "a"]
until: input.startIndex.advanced(by: limit))
let expected = [
"p", "o", "n", "m", "e", "f", "g", "h", "i", "j", "k", "l", "d", "c", "b",
"a",
]
XCTAssertEqual(input, expected) XCTAssertEqual(input, expected)
XCTAssertEqual(lower, input.startIndex.advanced(by: limit)) XCTAssertEqual(lower, input.startIndex.advanced(by: limit))
XCTAssertEqual(upper, input.endIndex.advanced(by: -limit)) XCTAssertEqual(upper, input.endIndex.advanced(by: -limit))
} }
/// Tests the example given in the `reverse(subrange:)` documentation. /// Tests the example given in `reverse(subrange:)`’s documentation
func testReverse() { func testReverse() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
numbers.reverse(subrange: 0..<4) numbers.reverse(subrange: 0..<4)
XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80]) XCTAssertEqual(numbers, [40, 30, 20, 10, 50, 60, 70, 80])
} }
/// Tests `rotate(subrange:toStartAt:)` with an empty subrange. /// Tests `rotate(subrange:toStartAt:)` with an empty subrange
/// The order of elements are unchanged
func testRotateEmptySubrange() { func testRotateEmptySubrange() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let oldStart = numbers.rotate(subrange: 3..<3, toStartAt: 3) let oldStart = numbers.rotate(subrange: 3..<3, toStartAt: 3)
// The order of elements are unchanged
XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80]) XCTAssertEqual(numbers, [10, 20, 30, 40, 50, 60, 70, 80])
XCTAssertEqual(numbers[oldStart], 40) XCTAssertEqual(numbers[oldStart], 40)
} }
/// Tests `rotate(subrange:toStartAt:)` with an empty collection. /// Tests `rotate(subrange:toStartAt:)` with an empty collection
func testRotateSubrangeOnEmptyCollection() { func testRotateSubrangeOnEmptyCollection() {
var numbers: [Int] = [] var numbers = [Int]()
let oldStart = numbers.rotate(subrange: 0..<0, toStartAt: 0) let oldStart = numbers.rotate(subrange: 0..<0, toStartAt: 0)
XCTAssertEqual(numbers, []) XCTAssertEqual(numbers, [])
XCTAssertEqual(oldStart, numbers.startIndex) XCTAssertEqual(oldStart, numbers.startIndex)
} }
/// Tests `rotate(subrange:toStartAt:)` with the full range of the collection. /// Tests `rotate(subrange:toStartAt:)` with the full range of the collection
func testRotateFullRange() { func testRotateFullRange() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let oldStart = numbers.rotate(subrange: 0..<8, toStartAt: 1) let oldStart = numbers.rotate(subrange: 0..<8, toStartAt: 1)
XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10]) XCTAssertEqual(numbers, [20, 30, 40, 50, 60, 70, 80, 10])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests the example given in the `rotate(subrange:toStartAt:)` /// Tests the example given in `rotate(subrange:toStartAt:)`’s documentation
/// documentation.
func testRotateSubrange() { func testRotateSubrange() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2) let oldStart = numbers.rotate(subrange: 0..<4, toStartAt: 2)
XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80]) XCTAssertEqual(numbers, [30, 40, 10, 20, 50, 60, 70, 80])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests the example given in the `rotate(toStartAt:)` documentation. /// Tests the example given in `rotate(toStartAt:)`’s documentation
func testRotateExample() { func testRotateExample() {
var numbers = [10, 20, 30, 40, 50, 60, 70, 80] var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
let oldStart = numbers.rotate(toStartAt: 3) let oldStart = numbers.rotate(toStartAt: 3)
XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30]) XCTAssertEqual(numbers, [40, 50, 60, 70, 80, 10, 20, 30])
XCTAssertEqual(numbers[oldStart], 10) XCTAssertEqual(numbers[oldStart], 10)
} }
/// Tests `rotate(toStartAt:)` on collections of varying lengths, at /// Tests `rotate(toStartAt:)` on collections of varying lengths, at different
/// different starting points. /// starting points
func testRotate() { func testRotate() {
for length in 0...15 { for length in 0...15 {
let a = Array(0..<length) let a = Array(0..<length)
var b = a var b = a
for j in 0..<length { for j in 0..<length {
let i = b.rotate(toStartAt: j) let i = b.rotate(toStartAt: j)
expectEqualSequences(a[j...] + a[..<j], b) XCTAssertEqualSequences(a[j...] + a[..<j], b)
b.rotate(toStartAt: i) b.rotate(toStartAt: i)
XCTAssertEqual(a, b) XCTAssertEqual(a, b)
} }
+36 -36
View File
@@ -112,7 +112,7 @@ final class SplitTests: XCTestCase {
func testAllEEES() { func testAllEEES() {
let permutations = [ let permutations = [
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]
] ]
for permutation in permutations { for permutation in permutations {
@@ -480,11 +480,11 @@ final class SplitTests: XCTestCase {
func testLaziness() { func testLaziness() {
let splitSequence = AnySequence([1, 2, 42, 3]).lazy.split(separator: 42) let splitSequence = AnySequence([1, 2, 42, 3]).lazy.split(separator: 42)
requireLazySequence(splitSequence) XCTAssertLazySequence(splitSequence)
let splitCollection = "foo.bar".lazy.split(separator: ".") let splitCollection = "foo.bar".lazy.split(separator: ".")
requireLazySequence(splitCollection) XCTAssertLazySequence(splitCollection)
requireLazyCollection(splitCollection) XCTAssertLazyCollection(splitCollection)
} }
// TODO: Need a version of `validateIndexTraversals` that doesn't require // TODO: Need a version of `validateIndexTraversals` that doesn't require
@@ -564,20 +564,20 @@ final class SplitTests: XCTestCase {
where T.Element == C.Element { where T.Element == C.Element {
// Default max splits, omitting empty sequences // Default max splits, omitting empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = s.split(separator: element).map { Array($0) } let expected = s.split(separator: element).map { Array($0) }
let actual = s.lazy.split(separator: element) let actual = s.lazy.split(separator: element)
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue)
) )
case .closure(let closure): case let .closure(closure):
let expected = s.split(whereSeparator: closure).map { Array($0) } let expected = s.split(whereSeparator: closure).map { Array($0) }
let actual = s.lazy.split(whereSeparator: closure) let actual = s.lazy.split(whereSeparator: closure)
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -588,7 +588,7 @@ final class SplitTests: XCTestCase {
// Provided max splits, omitting empty sequences // Provided max splits, omitting empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = s.split( let expected = s.split(
separator: element, separator: element,
maxSplits: maxSplits maxSplits: maxSplits
@@ -597,14 +597,14 @@ final class SplitTests: XCTestCase {
separator: element, separator: element,
maxSplits: maxSplits maxSplits: maxSplits
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue)
) )
case .closure(let closure): case let .closure(closure):
let expected = s.split( let expected = s.split(
maxSplits: maxSplits, maxSplits: maxSplits,
whereSeparator: closure whereSeparator: closure
@@ -613,7 +613,7 @@ final class SplitTests: XCTestCase {
maxSplits: maxSplits, maxSplits: maxSplits,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -624,7 +624,7 @@ final class SplitTests: XCTestCase {
// Default max splits, including empty sequences // Default max splits, including empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = s.split( let expected = s.split(
separator: element, separator: element,
omittingEmptySubsequences: false omittingEmptySubsequences: false
@@ -633,14 +633,14 @@ final class SplitTests: XCTestCase {
separator: element, separator: element,
omittingEmptySubsequences: false omittingEmptySubsequences: false
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false))
) )
case .closure(let closure): case let .closure(closure):
let expected = s.split( let expected = s.split(
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
@@ -649,7 +649,7 @@ final class SplitTests: XCTestCase {
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -660,7 +660,7 @@ final class SplitTests: XCTestCase {
// Provided max splits, including empty sequences // Provided max splits, including empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = s.split( let expected = s.split(
separator: element, separator: element,
maxSplits: maxSplits, maxSplits: maxSplits,
@@ -671,14 +671,14 @@ final class SplitTests: XCTestCase {
maxSplits: maxSplits, maxSplits: maxSplits,
omittingEmptySubsequences: false omittingEmptySubsequences: false
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false))
) )
case .closure(let closure): case let .closure(closure):
let expected = s.split( let expected = s.split(
maxSplits: maxSplits, maxSplits: maxSplits,
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
@@ -689,7 +689,7 @@ final class SplitTests: XCTestCase {
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -702,20 +702,20 @@ final class SplitTests: XCTestCase {
private func _validateAsCollection(_ c: C) { private func _validateAsCollection(_ c: C) {
// Default max splits, omitting empty sequences // Default max splits, omitting empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = c.split(separator: element) let expected = c.split(separator: element)
let actual = c.lazy.split(separator: element) let actual = c.lazy.split(separator: element)
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue)
) )
case .closure(let closure): case let .closure(closure):
let expected = c.split(whereSeparator: closure) let expected = c.split(whereSeparator: closure)
let actual = c.lazy.split(whereSeparator: closure) let actual = c.lazy.split(whereSeparator: closure)
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -726,7 +726,7 @@ final class SplitTests: XCTestCase {
// Provided max splits, omitting empty sequences // Provided max splits, omitting empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = c.split( let expected = c.split(
separator: element, separator: element,
maxSplits: maxSplits maxSplits: maxSplits
@@ -735,14 +735,14 @@ final class SplitTests: XCTestCase {
separator: element, separator: element,
maxSplits: maxSplits maxSplits: maxSplits
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue) omittingEmptySubsequences: .defaultValue)
) )
case .closure(let closure): case let .closure(closure):
let expected = c.split( let expected = c.split(
maxSplits: maxSplits, maxSplits: maxSplits,
whereSeparator: closure whereSeparator: closure
@@ -751,7 +751,7 @@ final class SplitTests: XCTestCase {
maxSplits: maxSplits, maxSplits: maxSplits,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -762,7 +762,7 @@ final class SplitTests: XCTestCase {
// Default max splits, including empty sequences // Default max splits, including empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = c.split( let expected = c.split(
separator: element, separator: element,
omittingEmptySubsequences: false omittingEmptySubsequences: false
@@ -771,14 +771,14 @@ final class SplitTests: XCTestCase {
separator: element, separator: element,
omittingEmptySubsequences: false omittingEmptySubsequences: false
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue, actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false))
) )
case .closure(let closure): case let .closure(closure):
let expected = c.split( let expected = c.split(
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
@@ -787,7 +787,7 @@ final class SplitTests: XCTestCase {
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
@@ -798,7 +798,7 @@ final class SplitTests: XCTestCase {
// Provided max splits, including empty sequences // Provided max splits, including empty sequences
switch separator { switch separator {
case .element(let element): case let .element(element):
let expected = c.split( let expected = c.split(
separator: element, separator: element,
maxSplits: maxSplits, maxSplits: maxSplits,
@@ -809,14 +809,14 @@ final class SplitTests: XCTestCase {
maxSplits: maxSplits, maxSplits: maxSplits,
omittingEmptySubsequences: false omittingEmptySubsequences: false
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits), actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false)) omittingEmptySubsequences: .provided(false))
) )
case .closure(let closure): case let .closure(closure):
let expected = c.split( let expected = c.split(
maxSplits: maxSplits, maxSplits: maxSplits,
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
@@ -827,7 +827,7 @@ final class SplitTests: XCTestCase {
omittingEmptySubsequences: false, omittingEmptySubsequences: false,
whereSeparator: closure whereSeparator: closure
) )
expectEqualSequences( XCTAssertEqualSequences(
expected, expected,
actual, actual,
failureMessage( failureMessage(
+48 -48
View File
@@ -9,45 +9,45 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class StridingTests: XCTestCase { final class StridingTests: XCTestCase {
func testStride() { func testStride() {
let a = 0...10 let a = 0...10
expectEqualSequences(a.striding(by: 1), (0...10)) XCTAssertEqualSequences(a.striding(by: 1), (0...10))
expectEqualSequences(a.striding(by: 2), [0, 2, 4, 6, 8, 10]) XCTAssertEqualSequences(a.striding(by: 2), [0, 2, 4, 6, 8, 10])
expectEqualSequences(a.striding(by: 3), [0, 3, 6, 9]) XCTAssertEqualSequences(a.striding(by: 3), [0, 3, 6, 9])
expectEqualSequences(a.striding(by: 4), [0, 4, 8]) XCTAssertEqualSequences(a.striding(by: 4), [0, 4, 8])
expectEqualSequences(a.striding(by: 5), [0, 5, 10]) XCTAssertEqualSequences(a.striding(by: 5), [0, 5, 10])
expectEqualSequences(a.striding(by: 10), [0, 10]) XCTAssertEqualSequences(a.striding(by: 10), [0, 10])
expectEqualSequences(a.striding(by: 11), [0]) XCTAssertEqualSequences(a.striding(by: 11), [0])
let s = (0...).prefix(11) let s = (0...).prefix(11)
expectEqualSequences(s.striding(by: 1), (0...10)) XCTAssertEqualSequences(s.striding(by: 1), (0...10))
expectEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10]) XCTAssertEqualSequences(s.striding(by: 2), [0, 2, 4, 6, 8, 10])
expectEqualSequences(s.striding(by: 3), [0, 3, 6, 9]) XCTAssertEqualSequences(s.striding(by: 3), [0, 3, 6, 9])
expectEqualSequences(s.striding(by: 4), [0, 4, 8]) XCTAssertEqualSequences(s.striding(by: 4), [0, 4, 8])
expectEqualSequences(s.striding(by: 5), [0, 5, 10]) XCTAssertEqualSequences(s.striding(by: 5), [0, 5, 10])
expectEqualSequences(s.striding(by: 10), [0, 10]) XCTAssertEqualSequences(s.striding(by: 10), [0, 10])
expectEqualSequences(s.striding(by: 11), [0]) XCTAssertEqualSequences(s.striding(by: 11), [0])
let empty = (0...).prefix(0) let empty = (0...).prefix(0)
expectEqualSequences(empty.striding(by: 2), []) XCTAssertEqualSequences(empty.striding(by: 2), [])
} }
func testStrideString() { func testStrideString() {
let s = "swift" let s = "swift"
expectEqualSequences(s.striding(by: 2), ["s", "i", "t"]) XCTAssertEqualSequences(s.striding(by: 2), ["s", "i", "t"])
} }
func testStrideReversed() { func testStrideReversed() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
expectEqualSequences(a.striding(by: 3).reversed(), [3, 0]) XCTAssertEqualSequences(a.striding(by: 3).reversed(), [3, 0])
expectEqualSequences(a.reversed().striding(by: 2), [5, 3, 1]) XCTAssertEqualSequences(a.reversed().striding(by: 2), [5, 3, 1])
} }
func testStrideIndexes() { func testStrideIndexes() {
let a = [0, 1, 2, 3, 4, 5].striding(by: 2) let a = [0, 1, 2, 3, 4, 5].striding(by: 2)
var i = a.startIndex var i = a.startIndex
@@ -60,20 +60,20 @@ final class StridingTests: XCTestCase {
XCTAssertEqual(a[i], 2) XCTAssertEqual(a[i], 2)
a.formIndex(before: &i) a.formIndex(before: &i)
XCTAssertEqual(a[i], 0) XCTAssertEqual(a[i], 0)
// a.formIndex(before: &i) // Precondition failed: Incrementing past start index // a.formIndex(before: &i) // Precondition failed: Incrementing past start index
// a.index(after: a.endIndex) // Precondition failed: Advancing past end index // a.index(after: a.endIndex) // Precondition failed: Advancing past end index
} }
func testStrideLast() { func testStrideLast() {
XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9 XCTAssertEqual((1...10).striding(by: 2).last, 9) // 1, 3, 5, 7, 9
XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10 XCTAssertEqual((1...10).striding(by: 3).last, 10) // 1, 4, 7, 10
XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9 XCTAssertEqual((1...10).striding(by: 4).last, 9) // 1, 5, 9
XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6 XCTAssertEqual((1...10).striding(by: 5).last, 6) // 1, 6
XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51 XCTAssertEqual((1...100).striding(by: 50).last, 51) // 1, 51
XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5 XCTAssertEqual((1...5).striding(by: 2).last, 5) // 1, 3, 5
XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty XCTAssertEqual([Int]().striding(by: 2).last, nil) // empty
} }
func testCount() { func testCount() {
let empty = [Int]().striding(by: 2) let empty = [Int]().striding(by: 2)
XCTAssertEqual(empty.count, 0) XCTAssertEqual(empty.count, 0)
@@ -86,15 +86,15 @@ final class StridingTests: XCTestCase {
XCTAssertEqual(a.striding(by: 10).count, [0, 10].count) XCTAssertEqual(a.striding(by: 10).count, [0, 10].count)
XCTAssertEqual(a.striding(by: 11).count, [0].count) XCTAssertEqual(a.striding(by: 11).count, [0].count)
} }
func testIndexTraversals() { func testIndexTraversals() {
do { do {
let empty: [Int] = [] let empty = [Int]()
let validator = IndexValidator<StridingCollection<[Int]>>() let validator = IndexValidator<StridingCollection<[Int]>>()
validator.validate(empty.striding(by: 1)) validator.validate(empty.striding(by: 1))
validator.validate(empty.striding(by: 2)) validator.validate(empty.striding(by: 2))
} }
do { do {
let range = 0...100 let range = 0...100
let validator = IndexValidator<StridingCollection<ClosedRange<Int>>>() let validator = IndexValidator<StridingCollection<ClosedRange<Int>>>()
@@ -102,7 +102,7 @@ final class StridingTests: XCTestCase {
validator.validate(range.striding(by: 11)) validator.validate(range.striding(by: 11))
validator.validate(range.striding(by: 101)) validator.validate(range.striding(by: 101))
} }
do { do {
let array = Array(0...100) let array = Array(0...100)
let validator = IndexValidator<StridingCollection<[Int]>>() let validator = IndexValidator<StridingCollection<[Int]>>()
@@ -110,7 +110,7 @@ final class StridingTests: XCTestCase {
validator.validate(array.striding(by: 11)) validator.validate(array.striding(by: 11))
validator.validate(array.striding(by: 101)) validator.validate(array.striding(by: 101))
} }
do { do {
let string = "swift rocks" let string = "swift rocks"
let validator = IndexValidator<StridingCollection<String>>() let validator = IndexValidator<StridingCollection<String>>()
@@ -119,7 +119,7 @@ final class StridingTests: XCTestCase {
validator.validate(string.striding(by: 10)) validator.validate(string.striding(by: 10))
} }
} }
func testOffsetBy() { func testOffsetBy() {
let a = (0...100).striding(by: 22) let a = (0...100).striding(by: 22)
let b = [0, 22, 44, 66, 88] let b = [0, 22, 44, 66, 88]
@@ -127,17 +127,17 @@ final class StridingTests: XCTestCase {
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i]) XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
} }
} }
func testOffsetByEndIndex() { func testOffsetByEndIndex() {
let a = 1...5 let a = 1...5
let b = a.striding(by: 3) // [1, 4] let b = a.striding(by: 3) // [1, 4]
let i = b.index(b.startIndex, offsetBy: 2) let i = b.index(b.startIndex, offsetBy: 2)
XCTAssertEqual(i, b.endIndex) XCTAssertEqual(i, b.endIndex)
} }
func testLazy() { func testLazy() {
requireLazySequence(AnySequence(0..<100).lazy.striding(by: 3)) XCTAssertLazySequence(AnySequence(0..<100).lazy.striding(by: 3))
requireLazySequence((0..<100).lazy.striding(by: 3)) XCTAssertLazySequence((0..<100).lazy.striding(by: 3))
requireLazyCollection((0..<100).lazy.striding(by: 3)) XCTAssertLazyCollection((0..<100).lazy.striding(by: 3))
} }
} }
+13 -13
View File
@@ -9,40 +9,40 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class SuffixTests: XCTestCase { final class SuffixTests: XCTestCase {
func testSuffix() { func testSuffix() {
let a = 0...10 let a = 0...10
expectEqualSequences(a.suffix(while: { $0 > 5 }), (6...10)) XCTAssertEqualSequences(a.suffix(while: { $0 > 5 }), (6...10))
expectEqualSequences(a.suffix(while: { $0 > 10 }), []) XCTAssertEqualSequences(a.suffix(while: { $0 > 10 }), [])
expectEqualSequences(a.suffix(while: { $0 > 9 }), [10]) XCTAssertEqualSequences(a.suffix(while: { $0 > 9 }), [10])
expectEqualSequences(a.suffix(while: { $0 > -1 }), (0...10)) XCTAssertEqualSequences(a.suffix(while: { $0 > -1 }), (0...10))
let empty: [Int] = [] let empty: [Int] = []
expectEqualSequences(empty.suffix(while: { $0 > 10 }), []) XCTAssertEqualSequences(empty.suffix(while: { $0 > 10 }), [])
} }
func testEndOfPrefix() { func testEndOfPrefix() {
let array = Array(0..<10) let array = Array(0..<10)
XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3) XCTAssertEqual(array.endOfPrefix(while: { $0 < 3 }), 3)
XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex) XCTAssertEqual(array.endOfPrefix(while: { _ in false }), array.startIndex)
XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex) XCTAssertEqual(array.endOfPrefix(while: { _ in true }), array.endIndex)
let empty: [Int] = [] let empty = [Int]()
XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0) XCTAssertEqual(empty.endOfPrefix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex) XCTAssertEqual(empty.endOfPrefix(while: { _ in false }), empty.startIndex)
XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex) XCTAssertEqual(empty.endOfPrefix(while: { _ in true }), empty.endIndex)
} }
func testStartOfSuffix() { func testStartOfSuffix() {
let array = Array(0..<10) let array = Array(0..<10)
XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3) XCTAssertEqual(array.startOfSuffix(while: { $0 >= 3 }), 3)
XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex) XCTAssertEqual(array.startOfSuffix(while: { _ in false }), array.endIndex)
XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex) XCTAssertEqual(array.startOfSuffix(while: { _ in true }), array.startIndex)
let empty: [Int] = [] let empty = [Int]()
XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0) XCTAssertEqual(empty.startOfSuffix(while: { $0 < 3 }), 0)
XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex) XCTAssertEqual(empty.startOfSuffix(while: { _ in false }), empty.endIndex)
XCTAssertEqual(empty.startOfSuffix(while: { _ in true }), empty.startIndex) XCTAssertEqual(empty.startOfSuffix(while: { _ in true }), empty.startIndex)
+59 -75
View File
@@ -32,16 +32,16 @@ extension Numeric {
struct SplitMix64: RandomNumberGenerator { struct SplitMix64: RandomNumberGenerator {
private var state: UInt64 private var state: UInt64
init(seed: UInt64) { init(seed: UInt64) {
self.state = seed self.state = seed
} }
mutating func next() -> UInt64 { mutating func next() -> UInt64 {
self.state &+= 0x9e37_79b9_7f4a_7c15 self.state &+= 0x9e3779b97f4a7c15
var z: UInt64 = self.state var z: UInt64 = self.state
z = (z ^ (z &>> 30)) &* 0xbf58_476d_1ce4_e5b9 z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9
z = (z ^ (z &>> 27)) &* 0x94d0_49bb_1331_11eb z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb
return z ^ (z &>> 31) return z ^ (z &>> 31)
} }
} }
@@ -54,7 +54,7 @@ struct AnyMutableCollection<Base> where Base: MutableCollection {
extension AnyMutableCollection: MutableCollection { extension AnyMutableCollection: MutableCollection {
typealias Index = Base.Index typealias Index = Base.Index
typealias Element = Base.Element typealias Element = Base.Element
var startIndex: Base.Index { base.startIndex } var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex } var endIndex: Base.Index { base.endIndex }
@@ -74,19 +74,18 @@ extension MutableCollection {
} }
} }
func expectEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2, _ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "", _ message: @autoclosure () -> String = "",
file: StaticString = (#file), line: UInt = #line file: StaticString = (#file), line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element { ) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try expectEqualSequences( try XCTAssertEqualSequences(expression1(), expression2(), by: ==,
expression1(), expression2(), by: ==,
message(), file: file, line: line) message(), file: file, line: line)
} }
// Two sequences contains exactly the same element but not necessarily in the same order. // Two sequences contains exactly the same element but not necessarily in the same order.
func expectUnorderedEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2, _ expression2: @autoclosure () throws -> S2,
file: StaticString = (#file), line: UInt = #line file: StaticString = (#file), line: UInt = #line
@@ -100,10 +99,9 @@ func expectUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
} }
s1.remove(at: idx) s1.remove(at: idx)
} }
XCTAssertTrue( XCTAssertTrue(
missing.isEmpty, missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
"first sequence missing '\(missing)' elements from second sequence",
file: file, line: line file: file, line: line
) )
@@ -113,7 +111,7 @@ func expectUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
) )
} }
func expectEqualSequences<S1: Sequence, S2: Sequence>( func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1, _ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2, _ expression2: @autoclosure () throws -> S2,
by areEquivalent: (S1.Element, S1.Element) -> Bool, by areEquivalent: (S1.Element, S1.Element) -> Bool,
@@ -123,9 +121,8 @@ func expectEqualSequences<S1: Sequence, S2: Sequence>(
func fail(_ reason: String) { func fail(_ reason: String) {
let message = message() let message = message()
XCTFail( XCTFail(message.isEmpty ? reason : "\(message) - \(reason)",
message.isEmpty ? reason : "\(message) - \(reason)", file: file, line: line)
file: file, line: line)
} }
var iter1 = try expression1().makeIterator() var iter1 = try expression1().makeIterator()
@@ -133,13 +130,11 @@ func expectEqualSequences<S1: Sequence, S2: Sequence>(
var idx = 0 var idx = 0
while true { while true {
switch (iter1.next(), iter2.next()) { switch (iter1.next(), iter2.next()) {
case (let e1?, let e2?) where areEquivalent(e1, e2): case let (e1?, e2?) where areEquivalent(e1, e2):
idx += 1 idx += 1
continue continue
case (let e1?, let e2?): case let (e1?, e2?):
fail( fail("element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)")
"element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)"
)
case (_?, nil): case (_?, nil):
fail("second sequence shorter than first") fail("second sequence shorter than first")
case (nil, _?): case (nil, _?):
@@ -150,11 +145,11 @@ func expectEqualSequences<S1: Sequence, S2: Sequence>(
} }
} }
func requireLazySequence<S: LazySequenceProtocol>(_: S) {} func XCTAssertLazySequence<S: LazySequenceProtocol>(_: S) {}
func requireLazyCollection<S: LazyCollectionProtocol>(_: S) {} func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
/// Asserts two collections are equal by using their indices to access elements. /// Asserts two collections are equal by using their indices to access elements.
func expectEqualCollections<C1: Collection, C2: Collection>( func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
_ expression1: @autoclosure () throws -> C1, _ expression1: @autoclosure () throws -> C1,
_ expression2: @autoclosure () throws -> C2, _ expression2: @autoclosure () throws -> C2,
_ message: @autoclosure () -> String = "", _ message: @autoclosure () -> String = "",
@@ -162,8 +157,7 @@ func expectEqualCollections<C1: Collection, C2: Collection>(
) rethrows where C1.Element: Equatable, C1.Element == C2.Element { ) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
let c1 = try expression1() let c1 = try expression1()
let c2 = try expression2() let c2 = try expression2()
XCTAssertEqual( XCTAssertEqual(c1.indices.count, c2.indices.count, message(), file: file, line: line)
c1.indices.count, c2.indices.count, message(), file: file, line: line)
for index in zip(c1.indices, c2.indices) { for index in zip(c1.indices, c2.indices) {
XCTAssertEqual(c1[index.0], c2[index.1], message(), file: file, line: line) XCTAssertEqual(c1[index.0], c2[index.1], message(), file: file, line: line)
} }
@@ -172,7 +166,7 @@ func expectEqualCollections<C1: Collection, C2: Collection>(
struct IndexValidator<C: Collection> { struct IndexValidator<C: Collection> {
let testRandomAccess = true let testRandomAccess = true
let indicesIncludingEnd: (C) -> [C.Index] let indicesIncludingEnd: (C) -> [C.Index]
/// Creates a new instance of an index validator that can verify that indices /// Creates a new instance of an index validator that can verify that indices
/// of a collection behave correctly and consistently. /// of a collection behave correctly and consistently.
/// ///
@@ -194,9 +188,7 @@ struct IndexValidator<C: Collection> {
/// using the contents of the collection directly. /// using the contents of the collection directly.
init( init(
testRandomAccess: Bool = true, testRandomAccess: Bool = true,
indicesIncludingEnd: @escaping (C) -> [C.Index] = { indicesIncludingEnd: @escaping (C) -> [C.Index] = { $0.indices + [$0.endIndex] }
$0.indices + [$0.endIndex]
}
) { ) {
self.indicesIncludingEnd = indicesIncludingEnd self.indicesIncludingEnd = indicesIncludingEnd
} }
@@ -210,7 +202,7 @@ extension IndexValidator {
let file: StaticString let file: StaticString
let line: UInt let line: UInt
} }
/// Verifies that all index traversal methods behave as expected. /// Verifies that all index traversal methods behave as expected.
/// ///
/// Verifies the correctness of the implementations of `startIndex`, /// Verifies the correctness of the implementations of `startIndex`,
@@ -219,6 +211,10 @@ extension IndexValidator {
/// `distance(from:to:)` by calling them with just about all possible input /// `distance(from:to:)` by calling them with just about all possible input
/// combinations. /// combinations.
/// ///
/// - Parameters:
/// - collection: The collection to be validated.
/// - expectedCount:
///
/// - Complexity: O(*n*^3) where *n* is the length of the collection if the /// - Complexity: O(*n*^3) where *n* is the length of the collection if the
/// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4). /// collection conforms to `RandomAccessCollection`, otherwise O(*n*^4).
func validate( func validate(
@@ -228,13 +224,13 @@ extension IndexValidator {
) { ) {
let indicesIncludingEnd = self.indicesIncludingEnd(collection) let indicesIncludingEnd = self.indicesIncludingEnd(collection)
let count = indicesIncludingEnd.count - 1 let count = indicesIncludingEnd.count - 1
let validator = Validator( let validator = Validator(
collection: collection, collection: collection,
count: count, count: count,
indicesIncludingEnd: indicesIncludingEnd, indicesIncludingEnd: indicesIncludingEnd,
file: file, line: line) file: file, line: line)
validator.validateForward( validator.validateForward(
testRandomAccess: testRandomAccess, testRandomAccess: testRandomAccess,
expectedCount: expectedCount) expectedCount: expectedCount)
@@ -248,13 +244,13 @@ extension IndexValidator where C: BidirectionalCollection {
) { ) {
let indicesIncludingEnd = self.indicesIncludingEnd(collection) let indicesIncludingEnd = self.indicesIncludingEnd(collection)
let count = indicesIncludingEnd.count - 1 let count = indicesIncludingEnd.count - 1
let validator = Validator( let validator = Validator(
collection: collection, collection: collection,
count: count, count: count,
indicesIncludingEnd: indicesIncludingEnd, indicesIncludingEnd: indicesIncludingEnd,
file: file, line: line) file: file, line: line)
validator.validateForward( validator.validateForward(
testRandomAccess: testRandomAccess, testRandomAccess: testRandomAccess,
expectedCount: expectedCount) expectedCount: expectedCount)
@@ -268,7 +264,7 @@ extension IndexValidator.Validator {
XCTAssertEqual( XCTAssertEqual(
expectedCount, count, "Count mismatch", file: file, line: line) expectedCount, count, "Count mismatch", file: file, line: line)
} }
XCTAssertEqual( XCTAssertEqual(
collection.count, count, collection.count, count,
"Count mismatch", "Count mismatch",
@@ -285,21 +281,21 @@ extension IndexValidator.Validator {
collection.endIndex, indicesIncludingEnd.last, collection.endIndex, indicesIncludingEnd.last,
"`endIndex` does not equal the last index", "`endIndex` does not equal the last index",
file: file, line: line) file: file, line: line)
validateIndexAfter() validateIndexAfter()
validateIndices() validateIndices()
validateIndexComparisons() validateIndexComparisons()
if testRandomAccess { if testRandomAccess {
validateDistanceFromTo() validateDistanceFromTo()
validateIndexOffsetBy() validateIndexOffsetBy()
validateIndexOffsetByLimitedBy() validateIndexOffsetByLimitedBy()
} }
} }
func validateIndexAfter() { func validateIndexAfter() {
var index = collection.startIndex var index = collection.startIndex
for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() { for (offset, expected) in indicesIncludingEnd.enumerated().dropFirst() {
collection.formIndex(after: &index) collection.formIndex(after: &index)
XCTAssertEqual( XCTAssertEqual(
@@ -311,7 +307,7 @@ extension IndexValidator.Validator {
file: file, line: line) file: file, line: line)
} }
} }
func validateIndices() { func validateIndices() {
XCTAssertEqual(collection.indices.count, count) XCTAssertEqual(collection.indices.count, count)
for (offset, index) in collection.indices.enumerated() { for (offset, index) in collection.indices.enumerated() {
@@ -321,7 +317,7 @@ extension IndexValidator.Validator {
file: file, line: line) file: file, line: line)
} }
} }
func validateIndexComparisons() { func validateIndexComparisons() {
for (offsetA, a) in indicesIncludingEnd.enumerated() { for (offsetA, a) in indicesIncludingEnd.enumerated() {
XCTAssertEqual( XCTAssertEqual(
@@ -332,7 +328,7 @@ extension IndexValidator.Validator {
a < a, a < a,
"Index at offset \(offsetA) is less than itself", "Index at offset \(offsetA) is less than itself",
file: file, line: line) file: file, line: line)
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() { for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
XCTAssertNotEqual( XCTAssertNotEqual(
a, b, a, b,
@@ -347,12 +343,10 @@ extension IndexValidator.Validator {
} }
} }
} }
func validateDistanceFromTo() { func validateDistanceFromTo() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst( for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
startOffset)
{
let distance = endOffset - startOffset let distance = endOffset - startOffset
XCTAssertEqual( XCTAssertEqual(
collection.distance(from: start, to: end), distance, collection.distance(from: start, to: end), distance,
@@ -364,12 +358,10 @@ extension IndexValidator.Validator {
} }
} }
} }
func validateIndexOffsetBy() { func validateIndexOffsetBy() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst( for (endOffset, end) in indicesIncludingEnd.enumerated().dropFirst(startOffset) {
startOffset)
{
let distance = endOffset - startOffset let distance = endOffset - startOffset
XCTAssertEqual( XCTAssertEqual(
collection.index(start, offsetBy: distance), end, collection.index(start, offsetBy: distance), end,
@@ -381,7 +373,7 @@ extension IndexValidator.Validator {
} }
} }
} }
func validateIndexOffsetByLimitedBy() { func validateIndexOffsetByLimitedBy() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (limitOffset, limit) in indicesIncludingEnd.enumerated() { for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
@@ -392,9 +384,8 @@ extension IndexValidator.Validator {
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) { func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
for targetOffset in range { for targetOffset in range {
let distance = targetOffset - startOffset let distance = targetOffset - startOffset
let end = collection.index( let end = collection.index(start, offsetBy: distance, limitedBy: limit)
start, offsetBy: distance, limitedBy: limit)
if pastLimit { if pastLimit {
XCTAssertNil( XCTAssertNil(
end, end,
@@ -415,7 +406,7 @@ extension IndexValidator.Validator {
} }
} }
} }
if limit >= start { if limit >= start {
// the limit has an effect // the limit has an effect
checkTargetRange(startOffset...limitOffset, pastLimit: false) checkTargetRange(startOffset...limitOffset, pastLimit: false)
@@ -432,20 +423,18 @@ extension IndexValidator.Validator {
extension IndexValidator.Validator where C: BidirectionalCollection { extension IndexValidator.Validator where C: BidirectionalCollection {
func validateBackward(testRandomAccess: Bool) { func validateBackward(testRandomAccess: Bool) {
validateIndexBefore() validateIndexBefore()
if testRandomAccess { if testRandomAccess {
validateDistanceFromTo() validateDistanceFromTo()
validateIndexOffsetBy() validateIndexOffsetBy()
validateIndexOffsetByLimitedBy() validateIndexOffsetByLimitedBy()
} }
} }
func validateIndexBefore() { func validateIndexBefore() {
var index = collection.endIndex var index = collection.endIndex
for (offset, expected) in indicesIncludingEnd.enumerated().dropLast() for (offset, expected) in indicesIncludingEnd.enumerated().dropLast().reversed() {
.reversed()
{
collection.formIndex(before: &index) collection.formIndex(before: &index)
XCTAssertEqual( XCTAssertEqual(
index, expected, index, expected,
@@ -456,12 +445,10 @@ extension IndexValidator.Validator where C: BidirectionalCollection {
file: file, line: line) file: file, line: line)
} }
} }
func validateDistanceFromTo() { func validateDistanceFromTo() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix( for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
startOffset)
{
let distance = endOffset - startOffset let distance = endOffset - startOffset
XCTAssertEqual( XCTAssertEqual(
collection.distance(from: start, to: end), distance, collection.distance(from: start, to: end), distance,
@@ -473,12 +460,10 @@ extension IndexValidator.Validator where C: BidirectionalCollection {
} }
} }
} }
func validateIndexOffsetBy() { func validateIndexOffsetBy() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (endOffset, end) in indicesIncludingEnd.enumerated().prefix( for (endOffset, end) in indicesIncludingEnd.enumerated().prefix(startOffset) {
startOffset)
{
let distance = endOffset - startOffset let distance = endOffset - startOffset
XCTAssertEqual( XCTAssertEqual(
collection.index(start, offsetBy: distance), end, collection.index(start, offsetBy: distance), end,
@@ -490,7 +475,7 @@ extension IndexValidator.Validator where C: BidirectionalCollection {
} }
} }
} }
func validateIndexOffsetByLimitedBy() { func validateIndexOffsetByLimitedBy() {
for (startOffset, start) in indicesIncludingEnd.enumerated() { for (startOffset, start) in indicesIncludingEnd.enumerated() {
for (limitOffset, limit) in indicesIncludingEnd.enumerated() { for (limitOffset, limit) in indicesIncludingEnd.enumerated() {
@@ -501,9 +486,8 @@ extension IndexValidator.Validator where C: BidirectionalCollection {
func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) { func checkTargetRange(_ range: ClosedRange<Int>, pastLimit: Bool) {
for targetOffset in range { for targetOffset in range {
let distance = targetOffset - startOffset let distance = targetOffset - startOffset
let end = collection.index( let end = collection.index(start, offsetBy: distance, limitedBy: limit)
start, offsetBy: distance, limitedBy: limit)
if pastLimit { if pastLimit {
XCTAssertNil( XCTAssertNil(
end, end,
@@ -524,7 +508,7 @@ extension IndexValidator.Validator where C: BidirectionalCollection {
} }
} }
} }
if limit <= start { if limit <= start {
// the limit has an effect // the limit has an effect
checkTargetRange(limitOffset...startOffset, pastLimit: false) checkTargetRange(limitOffset...startOffset, pastLimit: false)
+26 -30
View File
@@ -13,78 +13,74 @@ import Algorithms
import XCTest import XCTest
final class TrimTests: XCTestCase { final class TrimTests: XCTestCase {
func testEmpty() { func testEmpty() {
let resultsEmpty = ([] as [Int]).trimming { $0.isMultiple(of: 2) } let results_empty = ([] as [Int]).trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(resultsEmpty, []) XCTAssertEqual(results_empty, [])
} }
func testNoMatch() { func testNoMatch() {
// No match (nothing trimmed). // No match (nothing trimmed).
let resultsNoMatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
$0.isMultiple(of: 2) $0.isMultiple(of: 2)
} }
XCTAssertEqual(resultsNoMatch, [1, 3, 5, 7, 9, 11, 13, 15]) XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
} }
func testNoTailMatch() { func testNoTailMatch() {
// No tail match (only trim head). // No tail match (only trim head).
let resultsNoTailMatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 } let results_notailmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 < 10 }
XCTAssertEqual(resultsNoTailMatch, [11, 13, 15]) XCTAssertEqual(results_notailmatch, [11, 13, 15])
} }
func testNoHeadMatch() { func testNoHeadMatch() {
// No head match (only trim tail). // No head match (only trim tail).
let resultsNoHeadMatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 } let results_noheadmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0 > 10 }
XCTAssertEqual(resultsNoHeadMatch, [1, 3, 5, 7, 9]) XCTAssertEqual(results_noheadmatch, [1, 3, 5, 7, 9])
} }
func testBothEndsMatch() { func testBothEndsMatch() {
// Both ends match, some string of >1 elements do not (return that string). // Both ends match, some string of >1 elements do not (return that string).
let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) } let results = [2, 10, 11, 15, 20, 21, 100].trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(results, [11, 15, 20, 21]) XCTAssertEqual(results, [11, 15, 20, 21])
} }
func testEverythingMatches() { func testEverythingMatches() {
// Everything matches (trim everything). // Everything matches (trim everything).
let resultsAllMatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true } let results_allmatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { _ in true }
XCTAssertEqual(resultsAllMatch, []) XCTAssertEqual(results_allmatch, [])
} }
func testEverythingButOneMatches() { func testEverythingButOneMatches() {
// Both ends match, one element does not (trim all except that element). // Both ends match, one element does not (trim all except that element).
let resultsOne = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) } let results_one = [2, 10, 12, 15, 20, 100].trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(resultsOne, [15]) XCTAssertEqual(results_one, [15])
} }
func testTrimmingPrefix() { func testTrimmingPrefix() {
let results = [2, 10, 12, 15, 20, 100].trimmingPrefix { let results = [2, 10, 12, 15, 20, 100].trimmingPrefix { $0.isMultiple(of: 2) }
$0.isMultiple(of: 2)
}
XCTAssertEqual(results, [15, 20, 100]) XCTAssertEqual(results, [15, 20, 100])
} }
func testTrimmingSuffix() { func testTrimmingSuffix() {
let results = [2, 10, 12, 15, 20, 100].trimmingSuffix { let results = [2, 10, 12, 15, 20, 100].trimmingSuffix { $0.isMultiple(of: 2) }
$0.isMultiple(of: 2)
}
XCTAssertEqual(results, [2, 10, 12, 15]) XCTAssertEqual(results, [2, 10, 12, 15])
} }
// Self == Self.Subsequence // Self == Self.Subsequence
func testTrimNoAmbiguity() { func testTrimNoAmbiguity() {
var values = [2, 10, 12, 15, 20, 100] as ArraySlice var values = [2, 10, 12, 15, 20, 100] as ArraySlice
values.trim { $0.isMultiple(of: 2) } values.trim { $0.isMultiple(of: 2) }
XCTAssertEqual(values, [15]) XCTAssertEqual(values, [15])
} }
// Self == Self.Subsequence // Self == Self.Subsequence
func testTrimPrefixNoAmbiguity() { func testTrimPrefixNoAmbiguity() {
var values = [2, 10, 12, 15, 20, 100] as ArraySlice var values = [2, 10, 12, 15, 20, 100] as ArraySlice
values.trimPrefix { $0.isMultiple(of: 2) } values.trimPrefix { $0.isMultiple(of: 2) }
XCTAssertEqual(values, [15, 20, 100]) XCTAssertEqual(values, [15, 20, 100])
} }
// Self == Self.Subsequence // Self == Self.Subsequence
func testTrimSuffixNoAmbiguity() { func testTrimSuffixNoAmbiguity() {
var values = [2, 10, 12, 15, 20, 100] as ArraySlice var values = [2, 10, 12, 15, 20, 100] as ArraySlice
@@ -9,12 +9,12 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class UniquePermutationsTests: XCTestCase { final class UniquePermutationsTests: XCTestCase {
static let numbers = [1, 1, 1, 2, 3] static let numbers = [1, 1, 1, 2, 3]
static let numbersPermutations: [[[Int]]] = [ static let numbersPermutations: [[[Int]]] = [
// k = 0 // k = 0
[[]], [[]],
@@ -23,70 +23,64 @@ final class UniquePermutationsTests: XCTestCase {
// 2 // 2
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]], [[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
// 3 // 3
[ [[1, 1, 1], [1, 1, 2], [1, 1, 3],
[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2], [2, 1, 1], [2, 1, 3], [2, 3, 1],
[2, 1, 1], [2, 1, 3], [2, 3, 1], [3, 1, 1], [3, 1, 2], [3, 2, 1]],
[3, 1, 1], [3, 1, 2], [3, 2, 1],
],
// 4 // 4
[ [[1, 1, 1, 2], [1, 1, 1, 3],
[1, 1, 1, 2], [1, 1, 1, 3], [1, 1, 2, 1], [1, 1, 2, 3],
[1, 1, 2, 1], [1, 1, 2, 3], [1, 1, 3, 1], [1, 1, 3, 2],
[1, 1, 3, 1], [1, 1, 3, 2], [1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1],
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 1], [1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1],
[1, 3, 1, 1], [1, 3, 1, 2], [1, 3, 2, 1], [2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1],
[2, 1, 1, 1], [2, 1, 1, 3], [2, 1, 3, 1], [2, 3, 1, 1], [3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1]],
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1],
],
// 5 // 5
[ [[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
[1, 1, 1, 2, 3], [1, 1, 1, 3, 2], [1, 1, 2, 1, 3], [1, 1, 2, 3, 1],
[1, 1, 2, 1, 3], [1, 1, 2, 3, 1], [1, 1, 3, 1, 2], [1, 1, 3, 2, 1],
[1, 1, 3, 1, 2], [1, 1, 3, 2, 1], [1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1],
[1, 2, 1, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 1], [1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1],
[1, 3, 1, 1, 2], [1, 3, 1, 2, 1], [1, 3, 2, 1, 1], [2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1],
[2, 1, 1, 1, 3], [2, 1, 1, 3, 1], [2, 1, 3, 1, 1], [2, 3, 1, 1, 1], [3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1]]
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1],
],
] ]
} }
extension UniquePermutationsTests { extension UniquePermutationsTests {
func testEmpty() { func testEmpty() {
expectEqualSequences(([] as [Int]).uniquePermutations(), [[]]) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
expectEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]]) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
expectEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), []) XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
expectEqualSequences( XCTAssertEqualSequences(
([] as [Int]).uniquePermutations(ofCount: 1...3), []) ([] as [Int]).uniquePermutations(ofCount: 1...3), [])
} }
func testSingleCounts() { func testSingleCounts() {
for (k, expectation) in Self.numbersPermutations.enumerated() { for (k, expectation) in Self.numbersPermutations.enumerated() {
expectEqualSequences( XCTAssertEqualSequences(
expectation, expectation,
Self.numbers.uniquePermutations(ofCount: k)) Self.numbers.uniquePermutations(ofCount: k))
} }
expectEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[5], Self.numbersPermutations[5],
Self.numbers.uniquePermutations()) Self.numbers.uniquePermutations())
} }
func testRanges() { func testRanges() {
for lower in Self.numbersPermutations.indices { for lower in Self.numbersPermutations.indices {
// upper bounded // upper bounded
expectEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[...lower].joined(), Self.numbersPermutations[...lower].joined(),
Self.numbers.uniquePermutations(ofCount: ...lower)) Self.numbers.uniquePermutations(ofCount: ...lower))
// lower bounded // lower bounded
expectEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[lower...].joined(), Self.numbersPermutations[lower...].joined(),
Self.numbers.uniquePermutations(ofCount: lower...)) Self.numbers.uniquePermutations(ofCount: lower...))
for upper in lower..<Self.numbersPermutations.count { for upper in lower..<Self.numbersPermutations.count {
expectEqualSequences( XCTAssertEqualSequences(
Self.numbersPermutations[lower..<upper].joined(), Self.numbersPermutations[lower..<upper].joined(),
Self.numbers.uniquePermutations(ofCount: lower..<upper)) Self.numbers.uniquePermutations(ofCount: lower..<upper))
} }
@@ -97,11 +91,11 @@ extension UniquePermutationsTests {
extension UniquePermutationsTests { extension UniquePermutationsTests {
private final class IntBox: Hashable { private final class IntBox: Hashable {
var value: Int var value: Int
init(_ value: Int) { init(_ value: Int) {
self.value = value self.value = value
} }
static func == (lhs: IntBox, rhs: IntBox) -> Bool { static func == (lhs: IntBox, rhs: IntBox) -> Bool {
lhs.value == rhs.value lhs.value == rhs.value
} }
@@ -117,13 +111,12 @@ extension UniquePermutationsTests {
let numbers = Self.numbers.map(IntBox.init) let numbers = Self.numbers.map(IntBox.init)
for k in 0...numbers.count { for k in 0...numbers.count {
for p in numbers.uniquePermutations(ofCount: k) { for p in numbers.uniquePermutations(ofCount: k) {
XCTAssertTrue( XCTAssertTrue(p.filter { $0.value == 1 }.allSatisfy { $0 === numbers[0] })
p.filter { $0.value == 1 }.allSatisfy { $0 === numbers[0] })
} }
} }
} }
func testLaziness() { func testLaziness() {
requireLazySequence("ABCD".lazy.uniquePermutations()) XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
} }
} }
+17 -21
View File
@@ -9,8 +9,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import Algorithms
import XCTest import XCTest
import Algorithms
final class UniqueTests: XCTestCase { final class UniqueTests: XCTestCase {
func testUnique() { func testUnique() {
@@ -18,40 +18,36 @@ final class UniqueTests: XCTestCase {
let b = a.uniqued() let b = a.uniqued()
XCTAssertEqual(b.sorted(), Set(a).sorted()) XCTAssertEqual(b.sorted(), Set(a).sorted())
XCTAssertEqual(10, Array(b).count) XCTAssertEqual(10, Array(b).count)
let c: [Int] = [] let c: [Int] = []
expectEqualSequences(c.uniqued(), []) XCTAssertEqualSequences(c.uniqued(), [])
let d = Array(repeating: 1, count: 10) let d = Array(repeating: 1, count: 10)
expectEqualSequences(d.uniqued(), [1]) XCTAssertEqualSequences(d.uniqued(), [1])
} }
func testUniqueOn() { func testUniqueOn() {
let a = [ let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
"Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom",
]
let b = a.uniqued(on: { $0.first }) let b = a.uniqued(on: { $0.first })
XCTAssertEqual(["Albemarle", "Brandywine"], b) XCTAssertEqual(["Albemarle", "Brandywine"], b)
let c: [Int] = [] let c: [Int] = []
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), []) XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10) let d = Array(repeating: "Andromeda", count: 10)
expectEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"]) XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
} }
func testLazyUniqueOn() { func testLazyUniqueOn() {
let a = [ let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
"Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom",
]
let b = a.lazy.uniqued(on: { $0.first }) let b = a.lazy.uniqued(on: { $0.first })
expectEqualSequences(b, ["Albemarle", "Brandywine"]) XCTAssertEqualSequences(b, ["Albemarle", "Brandywine"])
requireLazySequence(b) XCTAssertLazySequence(b)
let c: [Int] = [] let c: [Int] = []
expectEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), []) XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10) let d = Array(repeating: "Andromeda", count: 10)
expectEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"]) XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
} }
} }
+32 -33
View File
@@ -10,7 +10,6 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
import XCTest import XCTest
@testable import Algorithms @testable import Algorithms
final class WindowsTests: XCTestCase { final class WindowsTests: XCTestCase {
@@ -19,73 +18,73 @@ final class WindowsTests: XCTestCase {
let w = s.windows(ofCount: 2) let w = s.windows(ofCount: 2)
var i = w.startIndex var i = w.startIndex
expectEqualSequences(w[i], "sw") XCTAssertEqualSequences(w[i], "sw")
w.formIndex(after: &i) w.formIndex(after: &i)
expectEqualSequences(w[i], "wi") XCTAssertEqualSequences(w[i], "wi")
w.formIndex(after: &i) w.formIndex(after: &i)
expectEqualSequences(w[i], "if") XCTAssertEqualSequences(w[i], "if")
w.formIndex(after: &i) w.formIndex(after: &i)
expectEqualSequences(w[i], "ft") XCTAssertEqualSequences(w[i], "ft")
// w.index(after: w.endIndex) // ← Precondition failed: windows index is out of range // w.index(after: w.endIndex) // ← Precondition failed: windows index is out of range
// w.index(before: w.startIndex) // ← Precondition failed: windows index is out of range // w.index(before: w.startIndex) // ← Precondition failed: windows index is out of range
// w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range // w.formIndex(after: &i); w[i] // ← Precondition failed: windows index is out of range
} }
func testWindowsOfRange() { func testWindowsOfRange() {
let a = 0...100 let a = 0...100
XCTAssertTrue(a.windows(ofCount: 200).isEmpty) XCTAssertTrue(a.windows(ofCount: 200).isEmpty)
let w = a.windows(ofCount: 10) let w = a.windows(ofCount: 10)
expectEqualSequences(w.first!, 0..<10) XCTAssertEqualSequences(w.first!, 0..<10)
expectEqualSequences(w.last!, 91..<101) XCTAssertEqualSequences(w.last!, 91..<101)
} }
func testWindowsOfInt() { func testWindowsOfInt() {
let a = [0, 1, 0, 1].windows(ofCount: 2) let a = [ 0, 1, 0, 1 ].windows(ofCount: 2)
XCTAssertEqual(a.count, 3) XCTAssertEqual(a.count, 3)
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1]) XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map { let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map {
$0.reduce(0, +) $0.reduce(0, +)
}.reduce(0, +) }.reduce(0, +)
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15) XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
} }
func testWindowsCount() { func testWindowsCount() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
XCTAssertEqual(a.windows(ofCount: 3).count, 4) XCTAssertEqual(a.windows(ofCount: 3).count, 4)
let a2 = [0, 1, 2, 3, 4] let a2 = [0, 1, 2, 3, 4]
XCTAssertEqual(a2.windows(ofCount: 6).count, 0) XCTAssertEqual(a2.windows(ofCount: 6).count, 0)
let a3: [Int] = [] let a3 = [Int]()
XCTAssertEqual(a3.windows(ofCount: 2).count, 0) XCTAssertEqual(a3.windows(ofCount: 2).count, 0)
} }
func testWindowsSecondAndLast() { func testWindowsSecondAndLast() {
let a = [0, 1, 2, 3, 4, 5] let a = [0, 1, 2, 3, 4, 5]
let w = a.windows(ofCount: 4) let w = a.windows(ofCount: 4)
let snd = w[w.index(after: w.startIndex)] let snd = w[w.index(after: w.startIndex)]
expectEqualSequences(snd, [1, 2, 3, 4]) XCTAssertEqualSequences(snd, [1, 2, 3, 4])
let w2 = a.windows(ofCount: 3) let w2 = a.windows(ofCount: 3)
expectEqualSequences(w2.last!, [3, 4, 5]) XCTAssertEqualSequences(w2.last!, [3, 4, 5])
} }
func testWindowsIndexAfterAndBefore() { func testWindowsIndexAfterAndBefore() {
let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2) let a = [0, 1, 2, 3, 4, 5].windows(ofCount: 2)
var i = a.startIndex var i = a.startIndex
a.formIndex(after: &i) a.formIndex(after: &i)
a.formIndex(after: &i) a.formIndex(after: &i)
a.formIndex(before: &i) a.formIndex(before: &i)
expectEqualSequences(a[i], [1, 2]) XCTAssertEqualSequences(a[i], [1, 2])
} }
func testWindowsIndexTraversals() { func testWindowsIndexTraversals() {
let validator = IndexValidator<WindowsOfCountCollection<String>>( let validator = IndexValidator<WindowsOfCountCollection<String>>(
indicesIncludingEnd: { windows in indicesIncludingEnd: { windows in
@@ -93,9 +92,9 @@ final class WindowsTests: XCTestCase {
let indices = windows.base.indices + [endIndex] let indices = windows.base.indices + [endIndex]
return zip(indices, indices.dropFirst(windows.windowSize)) return zip(indices, indices.dropFirst(windows.windowSize))
.map { .init(lowerBound: $0, upperBound: $1) } .map { .init(lowerBound: $0, upperBound: $1) }
+ [.init(lowerBound: endIndex, upperBound: endIndex)] + [.init(lowerBound: endIndex, upperBound: endIndex)]
}) })
validator.validate("".windows(ofCount: 1), expectedCount: 0) validator.validate("".windows(ofCount: 1), expectedCount: 0)
validator.validate("a".windows(ofCount: 1), expectedCount: 1) validator.validate("a".windows(ofCount: 1), expectedCount: 1)
validator.validate("ab".windows(ofCount: 1), expectedCount: 2) validator.validate("ab".windows(ofCount: 1), expectedCount: 2)
@@ -107,6 +106,6 @@ final class WindowsTests: XCTestCase {
} }
func testWindowsLazy() { func testWindowsLazy() {
requireLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2)) XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2))
} }
} }