Compare commits

..
Author SHA1 Message Date
Nate Cook e6011cc5d0 Disrespect existing line breaks 2021-04-15 15:28:23 -05:00
38 changed files with 1163 additions and 2600 deletions

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@
"lineLength" : 100,
"maximumBlankLines" : 1,
"prioritizeKeepingFunctionOutputTogether" : false,
"respectsExistingLineBreaks" : true,
"respectsExistingLineBreaks" : false,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLowerCamelCase" : true,
+5 -18
View File
@@ -13,23 +13,10 @@
import PackageDescription
let package = Package(
name: "swift-algorithms",
products: [
.library(
name: "Algorithms",
targets: ["Algorithms"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1")
],
name: "swift-algorithms", products: [.library(name: "Algorithms", targets: ["Algorithms"])],
dependencies: [.package(url: "https://github.com/apple/swift-numerics", from: "0.0.1")],
targets: [
.target(
name: "Algorithms",
dependencies: [
.product(name: "RealModule", package: "swift-numerics")
]),
.testTarget(
name: "SwiftAlgorithmsTests",
dependencies: ["Algorithms"]),
]
)
name: "Algorithms", dependencies: [.product(name: "RealModule", package: "swift-numerics")]),
.testTarget(name: "SwiftAlgorithmsTests", dependencies: ["Algorithms"]),
])
+63 -121
View File
@@ -10,18 +10,14 @@
//===----------------------------------------------------------------------===//
/// A concatenation of two sequences with the same element type.
public struct Chain2<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element {
public struct Chain2<Base1: Sequence, Base2: Sequence> where Base1.Element == Base2.Element {
/// The first sequence in this chain.
@usableFromInline
internal let base1: Base1
@usableFromInline internal let base1: Base1
/// The second sequence in this chain.
@usableFromInline
internal let base2: Base2
@usableFromInline internal let base2: Base2
@inlinable
internal init(base1: Base1, base2: Base2) {
@inlinable internal init(base1: Base1, base2: Base2) {
self.base1 = base1
self.base2 = base2
}
@@ -30,28 +26,21 @@ where Base1.Element == Base2.Element {
extension Chain2: Sequence {
/// The iterator for a `Chain2` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator1: Base1.Iterator
@usableFromInline internal var iterator1: Base1.Iterator
@usableFromInline
internal var iterator2: Base2.Iterator
@usableFromInline internal var iterator2: Base2.Iterator
@inlinable
internal init(_ concatenation: Chain2) {
@inlinable internal init(_ concatenation: Chain2) {
iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator()
}
@inlinable
public mutating func next() -> Base1.Element? {
@inlinable public mutating func next() -> Base1.Element? {
return iterator1.next() ?? iterator2.next()
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
}
@inlinable public func makeIterator() -> Iterator { Iterator(self) }
}
extension Chain2: Collection where Base1: Collection, Base2: Collection {
@@ -62,133 +51,99 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
// is not to be used as a value - iterating over indices should go straight
// from the penultimate index of the first collection to the start of the
// second.
@usableFromInline
internal enum Representation: Equatable {
@usableFromInline internal enum Representation: Equatable {
case first(Base1.Index)
case second(Base2.Index)
}
@usableFromInline
internal let position: Representation
@usableFromInline internal let position: Representation
/// Creates a new index into the first underlying collection.
@inlinable
internal init(first i: Base1.Index) {
position = .first(i)
}
@inlinable internal init(first i: Base1.Index) { position = .first(i) }
/// Creates a new index into the second underlying collection.
@inlinable
internal init(second i: Base2.Index) {
position = .second(i)
}
@inlinable internal init(second i: Base2.Index) { position = .second(i) }
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.position, rhs.position) {
case (.first, .second):
return true
case (.second, .first):
return false
case let (.first(l), .first(r)):
return l < r
case let (.second(l), .second(r)):
return l < r
case (.first, .second): return true
case (.second, .first): return false
case let (.first(l), .first(r)): return l < r
case let (.second(l), .second(r)): return l < r
}
}
}
/// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`.
@inlinable
internal func normalizeIndex(_ i: Base1.Index) -> Index {
@inlinable internal func normalizeIndex(_ i: Base1.Index) -> Index {
i == base1.endIndex ? Index(second: base2.startIndex) : Index(first: i)
}
@inlinable
public var startIndex: Index {
@inlinable public var startIndex: Index {
// if `base1` is empty, this will return `base2.startIndex` - if `base2` is
// also empty, this will correctly equal `base2.endIndex`
normalizeIndex(base1.startIndex)
}
@inlinable
public var endIndex: Index {
return Index(second: base2.endIndex)
}
@inlinable public var endIndex: Index { return Index(second: base2.endIndex) }
@inlinable
public subscript(i: Index) -> Base1.Element {
@inlinable public subscript(i: Index) -> Base1.Element {
switch i.position {
case let .first(i):
return base1[i]
case let .second(i):
return base2[i]
case let .first(i): return base1[i]
case let .second(i): return base2[i]
}
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
switch i.position {
case let .first(i):
assert(i != base1.endIndex)
return normalizeIndex(base1.index(after: i))
case let .second(i):
return Index(second: base2.index(after: i))
case let .second(i): return Index(second: base2.index(after: i))
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
{
if distance >= 0 {
return limit >= i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
} else {
return limit <= i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance >= 0)
assert(limit >= i)
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(first:))
return base1.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(first:))
case let (.first(i), .second(limit)):
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
@@ -197,8 +152,8 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
} else {
// the offset overflows the bounds of `base1` by `n - d`
let d = base1.distance(from: i, to: base1.endIndex)
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
.map(Index.init(second:))
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit).map(
Index.init(second:))
}
case (.second, .first):
@@ -206,22 +161,19 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
fatalError()
case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(second:))
return base2.index(i, offsetBy: distance, limitedBy: limit).map(Index.init(second:))
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance >= 0)
assert(limit <= i)
switch (i.position, limit.position) {
case let (.first(i), .first(limit)):
return base1.index(i, offsetBy: -distance, limitedBy: limit)
.map(Index.init(first:))
return base1.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(first:))
case (.first, .second):
// impossible because `limit <= i`
@@ -234,24 +186,20 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
} else {
// the offset overflows the bounds of `base2` by `n - d`
let d = base2.distance(from: base2.startIndex, to: i)
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit)
.map(Index.init(first:))
return base1.index(base1.endIndex, offsetBy: -(distance - d), limitedBy: limit).map(
Index.init(first:))
}
case let (.second(i), .second(limit)):
// `limit` is relevant, so `base1` cannot be reached
return base2.index(i, offsetBy: -distance, limitedBy: limit)
.map(Index.init(second:))
return base2.index(i, offsetBy: -distance, limitedBy: limit).map(Index.init(second:))
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
switch (start.position, end.position) {
case let (.first(i), .first(j)):
return base1.distance(from: i, to: j)
case let (.second(i), .second(j)):
return base2.distance(from: i, to: j)
case let (.first(i), .first(j)): return base1.distance(from: i, to: j)
case let (.second(i), .second(j)): return base2.distance(from: i, to: j)
case let (.first(i), .second(j)):
return base1.distance(from: i, to: base1.endIndex)
+ base2.distance(from: base2.startIndex, to: j)
@@ -264,16 +212,13 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
extension Chain2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
@inlinable public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex")
switch i.position {
case let .first(i):
return Index(first: base1.index(before: i))
case let .first(i): return Index(first: base1.index(before: i))
case let .second(i):
return i == base2.startIndex
? Index(first: base1.index(before: base1.endIndex))
: Index(second: base2.index(before: i))
? Index(first: base1.index(before: base1.endIndex)) : Index(second: base2.index(before: i))
}
}
}
@@ -311,20 +256,17 @@ where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
/// then over the elements of `s2`.
///
/// - Complexity: O(1)
@inlinable
public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
@inlinable public func chain<S1, S2>(_ s1: S1, _ s2: S2) -> Chain2<S1, S2> {
Chain2(base1: s1, base2: s2)
}
// MARK: - Deprecations
@available(*, deprecated, renamed: "Chain2")
public typealias Chain = Chain2
@available(*, deprecated, renamed: "Chain2") public typealias Chain = Chain2
extension Sequence {
@available(*, deprecated, message: "Use the chain(_:_:) function, instead.")
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S>
where Element == S.Element {
public func chained<S: Sequence>(with other: S) -> Chain2<Self, S> where Element == S.Element {
Chain2(base1: self, base2: other)
}
}
+96 -214
View File
@@ -13,25 +13,19 @@
/// predicate or projection.
public struct Chunked<Base: Collection, Subject> {
/// The collection that this instance provides a view onto.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
/// The projection function.
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline internal let projection: (Base.Element) -> Subject
/// The predicate.
@usableFromInline
internal let belongInSameGroup: (Subject, Subject) -> Bool
@usableFromInline internal let belongInSameGroup: (Subject, Subject) -> Bool
/// The upper bound of the first chunk.
@usableFromInline
internal var firstUpperBound: Base.Index
@usableFromInline internal var firstUpperBound: Base.Index
@inlinable
internal init(
base: Base,
projection: @escaping (Base.Element) -> Subject,
@inlinable internal init(
base: Base, projection: @escaping (Base.Element) -> Subject,
belongInSameGroup: @escaping (Subject, Subject) -> Bool
) {
self.base = base
@@ -39,9 +33,7 @@ public struct Chunked<Base: Collection, Subject> {
self.belongInSameGroup = belongInSameGroup
self.firstUpperBound = base.startIndex
if !base.isEmpty {
firstUpperBound = endOfChunk(startingAt: base.startIndex)
}
if !base.isEmpty { firstUpperBound = endOfChunk(startingAt: base.startIndex) }
}
}
@@ -49,23 +41,17 @@ extension Chunked: LazyCollectionProtocol {
/// A position in a chunked collection.
public struct Index: Comparable {
/// The range corresponding to the chunk at this position.
@usableFromInline
internal var baseRange: Range<Base.Index>
@usableFromInline internal var baseRange: Range<Base.Index>
@inlinable
internal init(_ baseRange: Range<Base.Index>) {
self.baseRange = baseRange
}
@inlinable internal init(_ baseRange: Range<Base.Index>) { self.baseRange = baseRange }
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
// Since each index represents the range of a disparate chunk, no two
// unique indices will have the same lower bound.
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
// Only use the lower bound to test for ordering, as above.
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
}
@@ -73,25 +59,18 @@ extension Chunked: LazyCollectionProtocol {
/// Returns the index in the base collection of the end of the chunk starting
/// at the given index.
@inlinable
internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
@inlinable internal func endOfChunk(startingAt start: Base.Index) -> Base.Index {
let subject = projection(base[start])
return base[base.index(after: start)...]
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
return base[base.index(after: start)...].endOfPrefix(while: {
belongInSameGroup(subject, projection($0))
})
}
@inlinable
public var startIndex: Index {
Index(base.startIndex..<firstUpperBound)
}
@inlinable public var startIndex: Index { Index(base.startIndex..<firstUpperBound) }
@inlinable
public var endIndex: Index {
Index(base.endIndex..<base.endIndex)
}
@inlinable public var endIndex: Index { Index(base.endIndex..<base.endIndex) }
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
let upperBound = i.baseRange.upperBound
guard upperBound != base.endIndex else { return endIndex }
@@ -99,8 +78,7 @@ extension Chunked: LazyCollectionProtocol {
return Index(upperBound..<end)
}
@inlinable
public subscript(position: Index) -> Base.SubSequence {
@inlinable public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex")
return base[position.baseRange]
}
@@ -108,30 +86,29 @@ extension Chunked: LazyCollectionProtocol {
extension Chunked.Index: Hashable where Base.Index: Hashable {}
extension Chunked: BidirectionalCollection
where Base: BidirectionalCollection {
extension Chunked: BidirectionalCollection where Base: BidirectionalCollection {
/// Returns the index in the base collection of the start of the chunk ending
/// at the given index.
@inlinable
internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
@inlinable internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
let indexBeforeEnd = base.index(before: end)
// Get the projected value of the last element in the range ending at `end`.
let subject = projection(base[indexBeforeEnd])
return base[..<indexBeforeEnd]
.startOfSuffix(while: { belongInSameGroup(projection($0), subject) })
return base[..<indexBeforeEnd].startOfSuffix(while: {
belongInSameGroup(projection($0), subject)
})
}
@inlinable
public func index(before i: Index) -> Index {
@inlinable public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't advance before startIndex")
let start = startOfChunk(endingAt: i.baseRange.lowerBound)
return Index(start..<i.baseRange.lowerBound)
}
}
@available(*, deprecated, renamed: "Chunked")
public typealias LazyChunked<Base: Collection, Subject> = Chunked<Base, Subject>
@available(*, deprecated, renamed: "Chunked") public typealias LazyChunked<
Base: Collection, Subject
> = Chunked<Base, Subject>
//===----------------------------------------------------------------------===//
// lazy.chunked(by:)
@@ -142,29 +119,17 @@ extension LazyCollectionProtocol {
/// the given predicate.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunked(
by belongInSameGroup: @escaping (Element, Element) -> Bool
) -> Chunked<Elements, Element> {
Chunked(
base: elements,
projection: { $0 },
belongInSameGroup: belongInSameGroup)
}
@inlinable public func chunked(by belongInSameGroup: @escaping (Element, Element) -> Bool)
-> Chunked<Elements, Element>
{ Chunked(base: elements, projection: { $0 }, belongInSameGroup: belongInSameGroup) }
/// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunked<Subject: Equatable>(
on projection: @escaping (Element) -> Subject
) -> Chunked<Elements, Subject> {
Chunked(
base: elements,
projection: projection,
belongInSameGroup: ==)
}
@inlinable public func chunked<Subject: Equatable>(on projection: @escaping (Element) -> Subject)
-> Chunked<Elements, Subject>
{ Chunked(base: elements, projection: projection, belongInSameGroup: ==) }
}
//===----------------------------------------------------------------------===//
@@ -177,8 +142,7 @@ extension Collection {
/// predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
internal func chunked<Subject>(
@inlinable internal func chunked<Subject>(
on projection: (Element) throws -> Subject,
by belongInSameGroup: (Subject, Subject) throws -> Bool
) rethrows -> [SubSequence] {
@@ -197,9 +161,7 @@ extension Collection {
}
}
if start != endIndex {
result.append(self[start..<endIndex])
}
if start != endIndex { result.append(self[start..<endIndex]) }
return result
}
@@ -208,23 +170,17 @@ extension Collection {
/// the given predicate.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
public func chunked(
by belongInSameGroup: (Element, Element) throws -> Bool
) rethrows -> [SubSequence] {
try chunked(on: { $0 }, by: belongInSameGroup)
}
@inlinable public func chunked(by belongInSameGroup: (Element, Element) throws -> Bool) rethrows
-> [SubSequence]
{ try chunked(on: { $0 }, by: belongInSameGroup) }
/// Returns a collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
@inlinable
public func chunked<Subject: Equatable>(
on projection: (Element) throws -> Subject
) rethrows -> [SubSequence] {
try chunked(on: projection, by: ==)
}
@inlinable public func chunked<Subject: Equatable>(on projection: (Element) throws -> Subject)
rethrows -> [SubSequence]
{ try chunked(on: projection, by: ==) }
}
//===----------------------------------------------------------------------===//
@@ -244,185 +200,128 @@ public struct ChunkedByCount<Base: Collection> {
public typealias Element = Base.SubSequence
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let chunkCount: Int
@usableFromInline internal let chunkCount: Int
@usableFromInline
internal var startUpperBound: Base.Index
@usableFromInline internal var startUpperBound: Base.Index
/// Creates a view instance that presents the elements of `base`
/// in `SubSequence` chunks of the given count.
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
internal init(_base: Base, _chunkCount: Int) {
@inlinable internal init(_base: Base, _chunkCount: Int) {
self.base = _base
self.chunkCount = _chunkCount
// Compute the start index upfront in order to make
// start index a O(1) lookup.
self.startUpperBound =
_base.index(
_base.startIndex, offsetBy: _chunkCount,
limitedBy: _base.endIndex
) ?? _base.endIndex
_base.index(_base.startIndex, offsetBy: _chunkCount, limitedBy: _base.endIndex)
?? _base.endIndex
}
}
extension ChunkedByCount: Collection {
public struct Index {
@usableFromInline
internal let baseRange: Range<Base.Index>
@usableFromInline internal let baseRange: Range<Base.Index>
@inlinable
internal init(_baseRange: Range<Base.Index>) {
self.baseRange = _baseRange
}
@inlinable internal init(_baseRange: Range<Base.Index>) { self.baseRange = _baseRange }
}
/// - Complexity: O(1)
@inlinable
public var startIndex: Index {
Index(_baseRange: base.startIndex..<startUpperBound)
}
@inlinable
public var endIndex: Index {
Index(_baseRange: base.endIndex..<base.endIndex)
}
@inlinable public var startIndex: Index { Index(_baseRange: base.startIndex..<startUpperBound) }
@inlinable public var endIndex: Index { Index(_baseRange: base.endIndex..<base.endIndex) }
/// - Complexity: O(1)
@inlinable
public subscript(i: Index) -> Element {
@inlinable public subscript(i: Index) -> Element {
precondition(i < endIndex, "Index out of range")
return base[i.baseRange]
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i < endIndex, "Advancing past end index")
let baseIdx =
base.index(
i.baseRange.upperBound, offsetBy: chunkCount,
limitedBy: base.endIndex
) ?? base.endIndex
base.index(i.baseRange.upperBound, offsetBy: chunkCount, limitedBy: base.endIndex)
?? base.endIndex
return Index(_baseRange: i.baseRange.upperBound..<baseIdx)
}
}
extension ChunkedByCount.Index: Comparable {
@inlinable
public static func == (
lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index
) -> Bool {
@inlinable public static func == (lhs: ChunkedByCount.Index, rhs: ChunkedByCount.Index) -> Bool {
lhs.baseRange.lowerBound == rhs.baseRange.lowerBound
}
@inlinable
public static func < (
lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index
) -> Bool {
@inlinable public static func < (lhs: ChunkedByCount.Index, rhs: ChunkedByCount.Index) -> Bool {
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
}
}
extension ChunkedByCount:
BidirectionalCollection, RandomAccessCollection
extension ChunkedByCount: BidirectionalCollection, RandomAccessCollection
where Base: RandomAccessCollection {
@inlinable
public func index(before i: Index) -> Index {
@inlinable public func index(before i: Index) -> Index {
precondition(i > startIndex, "Advancing past start index")
var offset = chunkCount
if i.baseRange.lowerBound == base.endIndex {
let remainder = base.count % chunkCount
if remainder != 0 {
offset = remainder
}
if remainder != 0 { offset = remainder }
}
let baseIdx =
base.index(
i.baseRange.lowerBound, offsetBy: -offset,
limitedBy: base.startIndex
) ?? base.startIndex
base.index(i.baseRange.lowerBound, offsetBy: -offset, limitedBy: base.startIndex)
?? base.startIndex
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
}
}
extension ChunkedByCount {
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
let distance =
base.distance(
from: start.baseRange.lowerBound,
to: end.baseRange.lowerBound)
let (quotient, remainder) =
distance.quotientAndRemainder(dividingBy: chunkCount)
@inlinable public func distance(from start: Index, to end: Index) -> Int {
let distance = base.distance(from: start.baseRange.lowerBound, to: end.baseRange.lowerBound)
let (quotient, remainder) = distance.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum()
}
@inlinable
public var count: Int {
let (quotient, remainder) =
base.count.quotientAndRemainder(dividingBy: chunkCount)
@inlinable public var count: Int {
let (quotient, remainder) = base.count.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum()
}
@inlinable
public func index(
_ i: Index, offsetBy offset: Int, limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy offset: Int, limitedBy limit: Index) -> Index? {
guard offset != 0 else { return i }
guard limit != i else { return nil }
if offset > 0 {
return limit > i
? offsetForward(i, offsetBy: offset, limit: limit)
: offsetForward(i, offsetBy: offset)
? offsetForward(i, offsetBy: offset, limit: limit) : offsetForward(i, offsetBy: offset)
} else {
return limit < i
? offsetBackward(i, offsetBy: offset, limit: limit)
: offsetBackward(i, offsetBy: offset)
? offsetBackward(i, offsetBy: offset, limit: limit) : offsetBackward(i, offsetBy: offset)
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
let idx =
distance > 0
? offsetForward(i, offsetBy: distance)
: offsetBackward(i, offsetBy: distance)
guard let index = idx else {
fatalError("Out of bounds")
}
distance > 0 ? offsetForward(i, offsetBy: distance) : offsetBackward(i, offsetBy: distance)
guard let index = idx else { fatalError("Out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ i: Index, offsetBy distance: Int, limit: Index? = nil
) -> Index? {
@inlinable internal func offsetForward(_ i: Index, offsetBy distance: Int, limit: Index? = nil)
-> Index?
{
assert(distance > 0)
return makeOffsetIndex(
from: i, baseBound: base.endIndex,
distance: distance, baseDistance: distance * chunkCount,
limit: limit, by: >
)
from: i, baseBound: base.endIndex, distance: distance, baseDistance: distance * chunkCount,
limit: limit, by: >)
}
// Convenience to compute offset backward base distance.
@inlinable
internal func computeOffsetBackwardBaseDistance(
_ i: Index, _ distance: Int
) -> Int {
@inlinable internal func computeOffsetBackwardBaseDistance(_ i: Index, _ distance: Int) -> Int {
if i == endIndex {
let remainder = base.count % chunkCount
// We have to take it into account when calculating offsets.
@@ -436,30 +335,22 @@ extension ChunkedByCount {
return distance * chunkCount
}
@inlinable
internal func offsetBackward(
_ i: Index, offsetBy distance: Int, limit: Index? = nil
) -> Index? {
@inlinable internal func offsetBackward(_ i: Index, offsetBy distance: Int, limit: Index? = nil)
-> Index?
{
assert(distance < 0)
let baseDistance =
computeOffsetBackwardBaseDistance(i, distance)
let baseDistance = computeOffsetBackwardBaseDistance(i, distance)
return makeOffsetIndex(
from: i, baseBound: base.startIndex,
distance: distance, baseDistance: baseDistance,
limit: limit, by: <
)
from: i, baseBound: base.startIndex, distance: distance, baseDistance: baseDistance,
limit: limit, by: <)
}
// Helper to compute index(offsetBy:) index.
@inlinable
internal func makeOffsetIndex(
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int,
limit: Index?, by limitFn: (Base.Index, Base.Index) -> Bool
@inlinable internal func makeOffsetIndex(
from i: Index, baseBound: Base.Index, distance: Int, baseDistance: Int, limit: Index?,
by limitFn: (Base.Index, Base.Index) -> Bool
) -> Index? {
let baseIdx = base.index(
i.baseRange.lowerBound, offsetBy: baseDistance,
limitedBy: baseBound
)
let baseIdx = base.index(i.baseRange.lowerBound, offsetBy: baseDistance, limitedBy: baseBound)
if let limit = limit {
if baseIdx == nil {
@@ -472,9 +363,7 @@ extension ChunkedByCount {
// non-random access collection base) to compute the base
// distance taking remainder into account.
if baseDistance > 0 && limit == endIndex {
if self.distance(from: i, to: limit) < distance {
return nil
}
if self.distance(from: i, to: limit) < distance { return nil }
} else {
return nil
}
@@ -482,16 +371,12 @@ extension ChunkedByCount {
// Checks for the limit.
let baseStartIdx = baseIdx ?? baseBound
if limitFn(baseStartIdx, limit.baseRange.lowerBound) {
return nil
}
if limitFn(baseStartIdx, limit.baseRange.lowerBound) { return nil }
}
let baseStartIdx = baseIdx ?? baseBound
let baseEndIdx =
base.index(
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
) ?? base.endIndex
base.index(baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex) ?? base.endIndex
return Index(_baseRange: baseStartIdx..<baseEndIdx)
}
@@ -514,8 +399,7 @@ extension Collection {
/// // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
///
/// - Complexity: O(*n*), because the start index is pre-computed.
@inlinable
public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
@inlinable public func chunks(ofCount count: Int) -> ChunkedByCount<Self> {
precondition(count > 0, "Cannot chunk with count <= 0!")
return ChunkedByCount(_base: self, _chunkCount: count)
}
@@ -524,7 +408,5 @@ extension Collection {
extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
// Lazy conditional conformance.
extension ChunkedByCount: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension ChunkedByCount: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension ChunkedByCount: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension ChunkedByCount: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
+21 -56
View File
@@ -12,55 +12,40 @@
/// A collection wrapper that generates combinations of a base collection.
public struct Combinations<Base: Collection> {
/// The collection to iterate over for combinations.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let baseCount: Int
@usableFromInline internal let baseCount: Int
/// The range of accepted sizes of combinations.
/// - Note: This may be `nil` if the attempted range entirely exceeds the
/// upper bounds of the size of the `base` collection.
@usableFromInline
internal let kRange: Range<Int>?
@usableFromInline internal let kRange: Range<Int>?
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - k: The expected size of each combination.
@inlinable
internal init(_ base: Base, k: Int) {
self.init(base, kRange: k...k)
}
@inlinable internal init(_ base: Base, k: Int) { self.init(base, kRange: k...k) }
/// Initializes a `Combinations` for all combinations of `base` of sizes
/// within a given range.
/// - Parameters:
/// - base: The collection to iterate over for combinations.
/// - kRange: The range of accepted sizes of combinations.
@inlinable
internal init<R: RangeExpression>(
_ base: Base, kRange: R
) where R.Bound == Int {
@inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R) where R.Bound == Int {
let range = kRange.relative(to: 0 ..< .max)
self.base = base
let baseCount = base.count
self.baseCount = baseCount
let upperBound = baseCount + 1
self.kRange =
range.lowerBound < upperBound
? range.clamped(to: 0..<upperBound)
: nil
self.kRange = range.lowerBound < upperBound ? range.clamped(to: 0..<upperBound) : nil
}
/// The total number of combinations.
@inlinable
public var count: Int {
@inlinable public var count: Int {
guard let k = self.kRange else { return 0 }
let n = baseCount
if k == 0..<(n + 1) {
return 1 << n
}
if k == 0..<(n + 1) { return 1 << n }
func binomial(n: Int, k: Int) -> Int {
switch k {
@@ -71,36 +56,27 @@ public struct Combinations<Base: Collection> {
}
}
return k.map {
binomial(n: n, k: $0)
}.reduce(0, +)
return k.map { binomial(n: n, k: $0) }.reduce(0, +)
}
}
extension Combinations: Sequence {
/// The iterator for a `Combinations` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
/// The current range of accepted sizes of combinations.
/// - Note: The range is contracted until empty while iterating over
/// combinations of different sizes. When the range is empty, iteration is
/// finished.
@usableFromInline
internal var kRange: Range<Int>
@usableFromInline internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty)
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@inlinable internal var isFinished: Bool { return kRange.isEmpty }
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline internal var indexes: [Base.Index]
@inlinable
internal init(_ combinations: Combinations) {
@inlinable internal init(_ combinations: Combinations) {
self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
@@ -124,8 +100,7 @@ extension Combinations: Sequence {
/// [2, 3, 4] *
/// // Can't advance without needing to go past `base.endIndex`,
/// // so the iteration is finished.
@inlinable
internal mutating func advance() {
@inlinable internal mutating func advance() {
/// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished.
func advanceKRange() {
@@ -161,24 +136,19 @@ extension Combinations: Sequence {
base.formIndex(after: &indexes[j])
for k in indexes.indices[(j + 1)...] {
indexes[k] = base.index(after: indexes[k - 1])
if indexes[k] == base.endIndex {
break
}
if indexes[k] == base.endIndex { break }
}
}
}
@inlinable
public mutating func next() -> [Base.Element]? {
@inlinable public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil }
defer { advance() }
return indexes.map { i in base[i] }
}
}
public func makeIterator() -> Iterator {
Iterator(self)
}
public func makeIterator() -> Iterator { Iterator(self) }
}
extension Combinations: LazySequenceProtocol where Base: LazySequenceProtocol {}
@@ -249,12 +219,8 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection.
@inlinable
public func combinations<R: RangeExpression>(
ofCount kRange: R
) -> Combinations<Self> where R.Bound == Int {
return Combinations(self, kRange: kRange)
}
@inlinable public func combinations<R: RangeExpression>(ofCount kRange: R) -> Combinations<Self>
where R.Bound == Int { return Combinations(self, kRange: kRange) }
/// Returns a collection of combinations of this collection's elements, with
/// each combination having the specified number of elements.
@@ -285,8 +251,7 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Combinations`
/// accesses the `count` of the base collection.
@inlinable
public func combinations(ofCount k: Int) -> Combinations<Self> {
@inlinable public func combinations(ofCount k: Int) -> Combinations<Self> {
precondition(k >= 0, "Can't have combinations with a negative number of elements.")
return Combinations(self, k: k)
}
+31 -74
View File
@@ -10,28 +10,18 @@
//===----------------------------------------------------------------------===//
/// A `Sequence` that iterates over every non-nil element from the original `Sequence`.
public struct CompactedSequence<Base: Sequence, Element>: Sequence
where Base.Element == Element? {
public struct CompactedSequence<Base: Sequence, Element>: Sequence where Base.Element == Element? {
@usableFromInline
let base: Base
@usableFromInline let base: Base
@inlinable
init(base: Base) {
self.base = base
}
@inlinable init(base: Base) { self.base = base }
public struct Iterator: IteratorProtocol {
@usableFromInline
var base: Base.Iterator
@usableFromInline var base: Base.Iterator
@inlinable
init(base: Base.Iterator) {
self.base = base
}
@inlinable init(base: Base.Iterator) { self.base = base }
@inlinable
public mutating func next() -> Element? {
@inlinable public mutating func next() -> Element? {
while let wrapped = base.next() {
guard let some = wrapped else { continue }
return some
@@ -40,10 +30,7 @@ where Base.Element == Element? {
}
}
@inlinable
public func makeIterator() -> Iterator {
return Iterator(base: base.makeIterator())
}
@inlinable public func makeIterator() -> Iterator { return Iterator(base: base.makeIterator()) }
}
extension Sequence {
@@ -64,86 +51,62 @@ extension Sequence {
/// `Sequence`.
///
/// Complexity: O(1)
@inlinable
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == Unwrapped? {
CompactedSequence(base: self)
}
@inlinable public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == Unwrapped? { CompactedSequence(base: self) }
}
/// A `Collection` that iterates over every non-nil element from the original `Collection`.
public struct CompactedCollection<Base: Collection, Element>: Collection
where Base.Element == Element? {
@usableFromInline
let base: Base
@usableFromInline let base: Base
@inlinable
init(base: Base) {
@inlinable init(base: Base) {
self.base = base
let idx = base.firstIndex(where: { $0 != nil }) ?? base.endIndex
self.startIndex = Index(base: idx)
}
public struct Index {
@usableFromInline
let base: Base.Index
@usableFromInline let base: Base.Index
@inlinable
init(base: Base.Index) {
self.base = base
}
@inlinable init(base: Base.Index) { self.base = base }
}
public var startIndex: Index
@inlinable
public var endIndex: Index { Index(base: base.endIndex) }
@inlinable public var endIndex: Index { Index(base: base.endIndex) }
@inlinable
public subscript(position: Index) -> Element {
base[position.base]!
}
@inlinable public subscript(position: Index) -> Element { base[position.base]! }
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i != endIndex, "Index out of bounds")
let baseIdx = base.index(after: i.base)
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil })
else { return endIndex }
guard let idx = base[baseIdx...].firstIndex(where: { $0 != nil }) else { return endIndex }
return Index(base: idx)
}
}
extension CompactedCollection: BidirectionalCollection
where Base: BidirectionalCollection {
extension CompactedCollection: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
@inlinable public func index(before i: Index) -> Index {
precondition(i != startIndex, "Index out of bounds")
guard
let idx =
base[startIndex.base..<i.base]
.lastIndex(where: { $0 != nil })
else { fatalError("Index out of bounds") }
guard let idx = base[startIndex.base..<i.base].lastIndex(where: { $0 != nil }) else {
fatalError("Index out of bounds")
}
return Index(base: idx)
}
}
extension CompactedCollection.Index: Comparable {
@inlinable
public static func < (
lhs: CompactedCollection.Index,
rhs: CompactedCollection.Index
) -> Bool {
lhs.base < rhs.base
}
@inlinable public static func < (lhs: CompactedCollection.Index, rhs: CompactedCollection.Index)
-> Bool
{ lhs.base < rhs.base }
}
extension CompactedCollection.Index: Hashable
where Base.Index: Hashable {}
extension CompactedCollection.Index: Hashable where Base.Index: Hashable {}
extension Collection {
/// Returns a new `Collection` that iterates over every non-nil element
@@ -164,21 +127,15 @@ extension Collection {
///
/// Complexity: O(*n*) where *n* is the number of elements in the
/// original `Collection`.
@inlinable
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped? {
CompactedCollection(base: self)
}
@inlinable public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped? { CompactedCollection(base: self) }
}
//===----------------------------------------------------------------------===//
// Protocol Conformances
//===----------------------------------------------------------------------===//
extension CompactedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension CompactedSequence: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension CompactedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension CompactedCollection: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension CompactedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
+30 -81
View File
@@ -12,47 +12,34 @@
/// A collection wrapper that repeats the elements of a base collection.
public struct Cycle<Base: Collection> {
/// The collection to repeat.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@inlinable
internal init(base: Base) {
self.base = base
}
@inlinable internal init(base: Base) { self.base = base }
}
extension Cycle: Sequence {
/// The iterator for a `Cycle` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal var current: Base.Index
@usableFromInline internal var current: Base.Index
@inlinable
internal init(base: Base) {
@inlinable internal init(base: Base) {
self.base = base
self.current = base.startIndex
}
@inlinable
public mutating func next() -> Base.Element? {
@inlinable public mutating func next() -> Base.Element? {
guard !base.isEmpty else { return nil }
if current == base.endIndex {
current = base.startIndex
}
if current == base.endIndex { current = base.startIndex }
defer { base.formIndex(after: &current) }
return base[current]
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base: base)
}
@inlinable public func makeIterator() -> Iterator { Iterator(base: base) }
}
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
@@ -61,13 +48,9 @@ extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
/// finite number of times.
public struct FiniteCycle<Base: Collection> {
/// A Product2 instance for iterating the Base collection.
@usableFromInline
internal let product: Product2<Range<Int>, Base>
@usableFromInline internal let product: Product2<Range<Int>, Base>
@inlinable
internal init(base: Base, times: Int) {
self.product = Product2(0..<times, base)
}
@inlinable internal init(base: Base, times: Int) { self.product = Product2(0..<times, base) }
}
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
@@ -79,91 +62,61 @@ extension FiniteCycle: Collection {
public struct Index: Comparable {
/// The index corresponding to the Product2 index at this position.
@usableFromInline
internal let productIndex: Product2<Range<Int>, Base>.Index
@usableFromInline internal let productIndex: Product2<Range<Int>, Base>.Index
@inlinable
internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
@inlinable internal init(_ productIndex: Product2<Range<Int>, Base>.Index) {
self.productIndex = productIndex
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex == rhs.productIndex
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.productIndex < rhs.productIndex
}
}
@inlinable
public var startIndex: Index {
Index(product.startIndex)
}
@inlinable public var startIndex: Index { Index(product.startIndex) }
@inlinable
public var endIndex: Index {
Index(product.endIndex)
}
@inlinable public var endIndex: Index { Index(product.endIndex) }
@inlinable
public subscript(_ index: Index) -> Element {
product[index.productIndex].1
}
@inlinable public subscript(_ index: Index) -> Element { product[index.productIndex].1 }
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
let productIndex = product.index(after: i.productIndex)
return Index(productIndex)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
product.distance(from: start.productIndex, to: end.productIndex)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
let productIndex = product.index(i.productIndex, offsetBy: distance)
return Index(productIndex)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
{
guard
let productIndex = product.index(
i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex)
else {
return nil
}
i.productIndex, offsetBy: distance, limitedBy: limit.productIndex)
else { return nil }
return Index(productIndex)
}
@inlinable
public var count: Int {
product.count
}
@inlinable public var count: Int { product.count }
}
extension FiniteCycle: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
extension FiniteCycle: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable public func index(before i: Index) -> Index {
let productIndex = product.index(before: i.productIndex)
return Index(productIndex)
}
}
extension FiniteCycle: RandomAccessCollection
where Base: RandomAccessCollection {}
extension FiniteCycle: RandomAccessCollection where Base: RandomAccessCollection {}
//===----------------------------------------------------------------------===//
// cycled()
@@ -195,10 +148,7 @@ extension Collection {
/// forever.
///
/// - Complexity: O(1)
@inlinable
public func cycled() -> Cycle<Self> {
Cycle(base: self)
}
@inlinable public func cycled() -> Cycle<Self> { Cycle(base: self) }
/// Returns a sequence that repeats the elements of this collection the
/// specified number of times.
@@ -217,8 +167,7 @@ extension Collection {
/// times.
///
/// - Complexity: O(1)
@inlinable
public func cycled(times: Int) -> FiniteCycle<Self> {
@inlinable public func cycled(times: Int) -> FiniteCycle<Self> {
FiniteCycle(base: self, times: times)
}
}
+2 -8
View File
@@ -30,14 +30,8 @@ extension Sequence {
///
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
/// the sequence that result in `nil` when applying the transformation.
public func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
public func firstNonNil<Result>(_ transform: (Element) throws -> Result?) rethrows -> Result? {
for value in self { if let value = try transform(value) { return value } }
return nil
}
}
+13 -38
View File
@@ -16,59 +16,37 @@ public struct Indexed<Base: Collection> {
public typealias Element = (index: Base.Index, element: Base.Element)
/// The base collection.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@inlinable
internal init(base: Base) {
self.base = base
}
@inlinable internal init(base: Base) { self.base = base }
}
extension Indexed: Collection {
@inlinable
public var startIndex: Base.Index {
base.startIndex
}
@inlinable public var startIndex: Base.Index { base.startIndex }
@inlinable
public var endIndex: Base.Index {
base.endIndex
}
@inlinable public var endIndex: Base.Index { base.endIndex }
@inlinable
public subscript(position: Base.Index) -> Element {
@inlinable public subscript(position: Base.Index) -> Element {
(index: position, element: base[position])
}
@inlinable
public func index(after i: Base.Index) -> Base.Index {
base.index(after: i)
}
@inlinable public func index(after i: Base.Index) -> Base.Index { base.index(after: i) }
@inlinable
public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
@inlinable public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index {
base.index(i, offsetBy: distance)
}
@inlinable
public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base
.Index?
{
base.index(i, offsetBy: distance, limitedBy: limit)
}
@inlinable public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index)
-> Base.Index?
{ base.index(i, offsetBy: distance, limitedBy: limit) }
@inlinable
public func distance(from start: Base.Index, to end: Base.Index) -> Int {
@inlinable public func distance(from start: Base.Index, to end: Base.Index) -> Int {
base.distance(from: start, to: end)
}
}
extension Indexed: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable
public func index(before i: Base.Index) -> Base.Index {
base.index(before: i)
}
@inlinable public func index(before i: Base.Index) -> Base.Index { base.index(before: i) }
}
extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {}
@@ -95,8 +73,5 @@ extension Collection {
/// }
///
/// Returns: A collection of paired indices and elements of this collection.
@inlinable
public func indexed() -> Indexed<Self> {
Indexed(base: self)
}
@inlinable public func indexed() -> Indexed<Self> { Indexed(base: self) }
}
+36 -76
View File
@@ -12,14 +12,11 @@
/// A sequence that presents the elements of a base sequence of elements
/// with a separator between each of those elements.
public struct Intersperse<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let separator: Base.Element
@usableFromInline internal let separator: Base.Element
@inlinable
internal init(base: Base, separator: Base.Element) {
@inlinable internal init(base: Base, separator: Base.Element) {
self.base = base
self.separator = separator
}
@@ -28,30 +25,24 @@ public struct Intersperse<Base: Sequence> {
extension Intersperse: Sequence {
/// The iterator for an `Intersperse` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline internal var iterator: Base.Iterator
@usableFromInline
internal let separator: Base.Element
@usableFromInline internal let separator: Base.Element
@usableFromInline
internal var state = State.start
@usableFromInline internal var state = State.start
@inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) {
@inlinable internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator
self.separator = separator
}
@usableFromInline
enum State {
@usableFromInline enum State {
case start
case element(Base.Element)
case separator
}
@inlinable
public mutating func next() -> Base.Element? {
@inlinable public mutating func next() -> Base.Element? {
// After the start, the state flips between element and separator. Before
// returning a separator, a check is made for the next element as a
// separator is only returned between two elements. The next element is
@@ -71,8 +62,7 @@ extension Intersperse: Sequence {
}
}
@inlinable
public func makeIterator() -> Intersperse<Base>.Iterator {
@inlinable public func makeIterator() -> Intersperse<Base>.Iterator {
Iterator(iterator: base.makeIterator(), separator: separator)
}
}
@@ -80,77 +70,57 @@ extension Intersperse: Sequence {
extension Intersperse: Collection where Base: Collection {
/// A position in an `Intersperse` collection.
public struct Index: Comparable {
@usableFromInline
enum Representation: Equatable {
@usableFromInline enum Representation: Equatable {
case element(Base.Index)
case separator(next: Base.Index)
}
@usableFromInline
internal let representation: Representation
@usableFromInline internal let representation: Representation
@inlinable
init(representation: Representation) {
self.representation = representation
}
@inlinable init(representation: Representation) { self.representation = representation }
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs.representation, rhs.representation) {
case let (.element(li), .element(ri)),
let (.separator(next: li), .separator(next: ri)),
case let (.element(li), .element(ri)), let (.separator(next: li), .separator(next: ri)),
let (.element(li), .separator(next: ri)):
return li < ri
case let (.separator(next: li), .element(ri)):
return li <= ri
case let (.separator(next: li), .element(ri)): return li <= ri
}
}
@inlinable
static func element(_ index: Base.Index) -> Self {
@inlinable static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index))
}
@inlinable
static func separator(next: Base.Index) -> Self {
@inlinable static func separator(next: Base.Index) -> Self {
Self(representation: .separator(next: next))
}
}
@inlinable
public var startIndex: Index {
@inlinable public var startIndex: Index {
base.startIndex == base.endIndex ? endIndex : .element(base.startIndex)
}
@inlinable
public var endIndex: Index {
.separator(next: base.endIndex)
}
@inlinable public var endIndex: Index { .separator(next: base.endIndex) }
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
switch i.representation {
case let .element(index):
return .separator(next: base.index(after: index))
case let .separator(next):
return .element(next)
case let .element(index): return .separator(next: base.index(after: index))
case let .separator(next): return .element(next)
}
}
@inlinable
public subscript(position: Index) -> Element {
@inlinable public subscript(position: Index) -> Element {
switch position.representation {
case .element(let index): return base[index]
case .separator: return separator
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
switch (i.representation, distance.isMultiple(of: 2)) {
case (let .element(index), true):
return .element(base.index(index, offsetBy: distance / 2))
case (let .element(index), true): return .element(base.index(index, offsetBy: distance / 2))
case (let .element(index), false):
return .separator(next: base.index(index, offsetBy: (distance + 1) / 2))
case (let .separator(next: index), true):
@@ -161,42 +131,33 @@ extension Intersperse: Collection where Base: Collection {
}
// TODO: Implement index(_:offsetBy:limitedBy:)
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case let (.element(element), .separator(next: separator)):
return 2 * base.distance(from: element, to: separator) - 1
case let (.separator(next: separator), .element(element)):
return 2 * base.distance(from: separator, to: element) + 1
case let (.element(start), .element(end)),
let (.separator(start), .separator(end)):
case let (.element(start), .element(end)), let (.separator(start), .separator(end)):
return 2 * base.distance(from: start, to: end)
}
}
}
extension Intersperse: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
extension Intersperse: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex")
switch i.representation {
case let .element(index):
return .separator(next: index)
case let .separator(next):
return .element(base.index(before: next))
case let .element(index): return .separator(next: index)
case let .separator(next): return .element(base.index(before: next))
}
}
}
extension Intersperse: RandomAccessCollection
where Base: RandomAccessCollection {}
extension Intersperse: RandomAccessCollection where Base: RandomAccessCollection {}
extension Intersperse: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension Intersperse: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension Intersperse: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension Intersperse: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
extension Sequence {
@@ -228,8 +189,7 @@ extension Sequence {
/// - Returns: The interspersed sequence of elements.
///
/// - Complexity: O(1)
@inlinable
public func interspersed(with separator: Element) -> Intersperse<Self> {
@inlinable public func interspersed(with separator: Element) -> Intersperse<Self> {
Intersperse(base: self, separator: separator)
}
}
+67 -165
View File
@@ -22,23 +22,16 @@
///
/// where `x` conforms to `LazySequenceProtocol`.
public struct LazySplitSequence<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
@usableFromInline internal let omittingEmptySubsequences: Bool
@inlinable
internal init(
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
@inlinable internal init(
base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
@@ -52,31 +45,22 @@ extension LazySplitSequence {
public struct Iterator {
public typealias Element = [Base.Element]
@usableFromInline
internal var base: Base.Iterator
@usableFromInline internal var base: Base.Iterator
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
@usableFromInline internal let omittingEmptySubsequences: Bool
/// The number of splits performed.
@usableFromInline
internal var splitCount = 0
@usableFromInline internal var splitCount = 0
/// The number of subsequences returned.
@usableFromInline
internal var sequenceLength = 0
@usableFromInline internal var sequenceLength = 0
@inlinable
internal init(
base: Base.Iterator,
whereSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
@inlinable internal init(
base: Base.Iterator, whereSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
@@ -88,8 +72,7 @@ extension LazySplitSequence {
}
extension LazySplitSequence.Iterator: IteratorProtocol {
@inlinable
public mutating func next() -> Element? {
@inlinable public mutating func next() -> Element? {
var currentElement = base.next()
var subsequence: Element = []
@@ -117,8 +100,7 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
// than the number of separators), or the only subsequence left to return is
// empty and we're omitting those.
if currentElement == nil
&& (sequenceLength == splitCount + 1
|| omittingEmptySubsequences && subsequence.isEmpty)
&& (sequenceLength == splitCount + 1 || omittingEmptySubsequences && subsequence.isEmpty)
{
return nil
} else {
@@ -129,14 +111,10 @@ extension LazySplitSequence.Iterator: IteratorProtocol {
}
extension LazySplitSequence: LazySequenceProtocol {
@inlinable
public func makeIterator() -> Iterator {
@inlinable public func makeIterator() -> Iterator {
return Iterator(
base: base.makeIterator(),
whereSeparator: self.isSeparator,
maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences
)
base: base.makeIterator(), whereSeparator: self.isSeparator, maxSplits: self.maxSplits,
omittingEmptySubsequences: self.omittingEmptySubsequences)
}
}
@@ -225,20 +203,15 @@ extension LazySequenceProtocol {
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@inlinable public func split(
maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences)
}
}
@@ -315,20 +288,14 @@ extension LazySequenceProtocol where Element: Equatable {
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
@inlinable public func split(
separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
) -> LazySplitSequence<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitSequence(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences)
}
}
@@ -345,26 +312,18 @@ extension LazySequenceProtocol where Element: Equatable {
///
/// where `x` conforms to `LazyCollectionProtocol`.
public struct LazySplitCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let isSeparator: (Base.Element) -> Bool
@usableFromInline internal let isSeparator: (Base.Element) -> Bool
@usableFromInline
internal let maxSplits: Int
@usableFromInline internal let maxSplits: Int
@usableFromInline
internal let omittingEmptySubsequences: Bool
@usableFromInline internal let omittingEmptySubsequences: Bool
@usableFromInline
internal var _startIndex: Index
@usableFromInline internal var _startIndex: Index
@inlinable
internal init(
base: Base,
isSeparator: @escaping (Base.Element) -> Bool,
maxSplits: Int,
@inlinable internal init(
base: Base, isSeparator: @escaping (Base.Element) -> Bool, maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = base
@@ -376,10 +335,7 @@ public struct LazySplitCollection<Base: Collection> {
// 1. `base` is empty and we're _not_ omitting empty subsequences, in which
// case the following index describes the sole element of this collection;
self._startIndex = Index(
baseRange: base.startIndex..<base.startIndex,
sequenceLength: 1,
splitCount: 0
)
baseRange: base.startIndex..<base.startIndex, sequenceLength: 1, splitCount: 0)
if base.isEmpty {
if omittingEmptySubsequences {
// 2. `base` is empty and we _are_ omitting empty subsequences, so this
@@ -390,10 +346,7 @@ public struct LazySplitCollection<Base: Collection> {
// 3. `base` isn't empty, so we must iterate it to determine the start
// index.
_startIndex = indexForSubsequence(
atOrAfter: base.startIndex,
sequenceLength: 0,
splitCount: 0
)
atOrAfter: base.startIndex, sequenceLength: 0, splitCount: 0)
}
}
}
@@ -402,50 +355,37 @@ extension LazySplitCollection: LazyCollectionProtocol {
/// Position of a subsequence in a split collection.
public struct Index: Comparable {
/// The range corresponding to the subsequence at this position.
@usableFromInline
internal let baseRange: Range<Base.Index>
@usableFromInline internal let baseRange: Range<Base.Index>
/// The number of subsequences up to and including this position in the
/// collection.
@usableFromInline
internal let sequenceLength: Int
@usableFromInline internal let sequenceLength: Int
/// The number splits performed up to and including this position in the
/// collection.
@usableFromInline
internal let splitCount: Int
@usableFromInline internal let splitCount: Int
@inlinable
internal init(
baseRange: Range<Base.Index>,
sequenceLength: Int,
splitCount: Int
) {
@inlinable internal init(baseRange: Range<Base.Index>, sequenceLength: Int, splitCount: Int) {
self.baseRange = baseRange
self.sequenceLength = sequenceLength
self.splitCount = splitCount
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
// `sequenceLength` is equivalent to the index's 1-based position in the
// collection of indices.
lhs.sequenceLength == rhs.sequenceLength
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.sequenceLength < rhs.sequenceLength
}
}
/// Returns the index of the subsequence starting at or after the given base
/// collection index.
@inlinable
internal func indexForSubsequence(
atOrAfter lowerBound: Base.Index,
sequenceLength: Int,
splitCount: Int
@inlinable internal func indexForSubsequence(
atOrAfter lowerBound: Base.Index, sequenceLength: Int, splitCount: Int
) -> Index {
var start = lowerBound
// If we don't have any more splits to do (which we'll determine shortly),
@@ -455,16 +395,12 @@ extension LazySplitCollection: LazyCollectionProtocol {
if splitCount < maxSplits {
// The non-inclusive end of this subsequence is marked by the next
// separator, or the end of the base collection.
end =
base[start...].firstIndex(where: isSeparator)
?? base.endIndex
end = base[start...].firstIndex(where: isSeparator) ?? base.endIndex
if base[start..<end].isEmpty {
if omittingEmptySubsequences {
// Find the next subsequence of non-separators.
start =
base[end...].firstIndex(where: { !isSeparator($0) })
?? base.endIndex
start = base[end...].firstIndex(where: { !isSeparator($0) }) ?? base.endIndex
if start == base.endIndex {
// No non-separators left in the base collection. We're done.
return endIndex
@@ -483,28 +419,16 @@ extension LazySplitCollection: LazyCollectionProtocol {
}
return Index(
baseRange: start..<end,
sequenceLength: sequenceLength + 1,
splitCount: updatedSplitCount
)
baseRange: start..<end, sequenceLength: sequenceLength + 1, splitCount: updatedSplitCount)
}
@inlinable
public var startIndex: Index {
_startIndex
@inlinable public var startIndex: Index { _startIndex }
@inlinable public var endIndex: Index {
Index(baseRange: base.endIndex..<base.endIndex, sequenceLength: Int.max, splitCount: Int.max)
}
@inlinable
public var endIndex: Index {
Index(
baseRange: base.endIndex..<base.endIndex,
sequenceLength: Int.max,
splitCount: Int.max
)
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
var subsequenceStart = i.baseRange.upperBound
@@ -516,41 +440,31 @@ extension LazySplitCollection: LazyCollectionProtocol {
}
guard subsequenceStart != base.endIndex else {
if !omittingEmptySubsequences
&& i.sequenceLength < i.splitCount + 1
{
if !omittingEmptySubsequences && i.sequenceLength < i.splitCount + 1 {
// The base collection ended with a separator, so we need to emit one
// more empty subsequence. This one differs from `endIndex` in its
// `sequenceLength` (except in an extreme edge case!), which is the
// sole property tested for equality and comparison.
return Index(
baseRange: base.endIndex..<base.endIndex,
sequenceLength: i.sequenceLength + 1,
splitCount: i.splitCount
)
baseRange: base.endIndex..<base.endIndex, sequenceLength: i.sequenceLength + 1,
splitCount: i.splitCount)
} else {
return endIndex
}
}
return indexForSubsequence(
atOrAfter: subsequenceStart,
sequenceLength: i.sequenceLength,
splitCount: i.splitCount
)
atOrAfter: subsequenceStart, sequenceLength: i.sequenceLength, splitCount: i.splitCount)
}
@inlinable
public subscript(position: Index) -> Base.SubSequence {
@inlinable public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex")
return base[position.baseRange]
}
}
extension LazySplitCollection.Index: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(sequenceLength)
}
public func hash(into hasher: inout Hasher) { hasher.combine(sequenceLength) }
}
extension LazyCollectionProtocol {
@@ -636,25 +550,19 @@ extension LazyCollectionProtocol {
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@inlinable public func split(
maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: @escaping (Element) -> Bool
) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
base: elements,
isSeparator: isSeparator,
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
base: elements, isSeparator: isSeparator, maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences)
}
}
extension LazyCollectionProtocol
where Element: Equatable {
extension LazyCollectionProtocol where Element: Equatable {
/// Lazily returns the longest possible subsequences of the collection, in
/// order, around elements equal to the given element.
///
@@ -732,19 +640,13 @@ where Element: Equatable {
/// elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
@inlinable public func split(
separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true
) -> LazySplitCollection<Elements> {
precondition(maxSplits >= 0, "Must take zero or more splits")
return LazySplitCollection(
base: elements,
isSeparator: { $0 == separator },
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences
)
base: elements, isSeparator: { $0 == separator }, maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences)
}
}
+28 -70
View File
@@ -11,25 +11,20 @@
extension Sequence {
/// Implementation for min(count:areInIncreasingOrder:)
@inlinable
internal func _minImplementation(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable internal func _minImplementation(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
result.reserveCapacity(count)
while result.count < count, let e = iterator.next() {
result.append(e)
}
while result.count < count, let e = iterator.next() { result.append(e) }
try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() {
// To be part of `result`, `e` must be strictly less than `result.last`.
guard try areInIncreasingOrder(e, result.last!) else { continue }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
let insertionIndex = try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex != result.endIndex)
result.removeLast()
@@ -40,25 +35,20 @@ extension Sequence {
}
/// Implementation for max(count:areInIncreasingOrder:)
@inlinable
internal func _maxImplementation(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable internal func _maxImplementation(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
result.reserveCapacity(count)
while result.count < count, let e = iterator.next() {
result.append(e)
}
while result.count < count, let e = iterator.next() { result.append(e) }
try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() {
// To be part of `result`, `e` must be greater/equal to `result.first`.
guard try !areInIncreasingOrder(e, result.first!) else { continue }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
let insertionIndex = try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex > 0)
// Inserting `e` and then removing the first element (or vice versa)
@@ -102,22 +92,17 @@ extension Sequence {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func min(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable public func min(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(
count >= 0,
"""
Cannot find a minimum with a negative count of elements!
"""
)
""")
// Do nothing if we're prefixing nothing.
guard count > 0 else {
return []
}
guard count > 0 else { return [] }
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
@@ -149,22 +134,17 @@ extension Sequence {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func max(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable public func max(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(
count >= 0,
"""
Cannot find a maximum with a negative count of elements!
"""
)
""")
// Do nothing if we're suffixing nothing.
guard count > 0 else {
return []
}
guard count > 0 else { return [] }
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
}
@@ -192,10 +172,7 @@ extension Sequence where Element: Comparable {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
@inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
/// Returns the largest elements of this sequence.
///
@@ -218,10 +195,7 @@ extension Sequence where Element: Comparable {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
@inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
}
extension Collection {
@@ -252,22 +226,17 @@ extension Collection {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func min(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable public func min(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(
count >= 0,
"""
Cannot find a minimum with a negative count of elements!
"""
)
""")
// Do nothing if we're prefixing nothing.
guard count > 0 else {
return []
}
guard count > 0 else { return [] }
// Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count)
@@ -308,22 +277,17 @@ extension Collection {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func max(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
@inlinable public func max(
count: Int, sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(
count >= 0,
"""
Cannot find a maximum with a negative count of elements!
"""
)
""")
// Do nothing if we're suffixing nothing.
guard count > 0 else {
return []
}
guard count > 0 else { return [] }
// Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count)
@@ -360,10 +324,7 @@ extension Collection where Element: Comparable {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
@inlinable public func min(count: Int) -> [Element] { return min(count: count, sortedBy: <) }
/// Returns the largest elements of this collection.
///
@@ -386,8 +347,5 @@ extension Collection where Element: Comparable {
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
@inlinable public func max(count: Int) -> [Element] { return max(count: count, sortedBy: <) }
}
+20 -38
View File
@@ -21,29 +21,21 @@ extension MutableCollection {
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
@inlinable
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
@inlinable internal mutating func stablePartition(
count n: Int, subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
if n == 0 { return subrange.lowerBound }
if n == 1 {
return try belongsInSecondPartition(self[subrange.lowerBound])
? subrange.lowerBound
: subrange.upperBound
? subrange.lowerBound : subrange.upperBound
}
let h = n / 2
let i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition(
count: h,
subrange: subrange.lowerBound..<i,
by: belongsInSecondPartition)
count: h, subrange: subrange.lowerBound..<i, by: belongsInSecondPartition)
let k = try stablePartition(
count: n - h,
subrange: i..<subrange.upperBound,
by: belongsInSecondPartition)
count: n - h, subrange: i..<subrange.upperBound, by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i)
}
@@ -58,14 +50,11 @@ extension MutableCollection {
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
@inlinable public mutating func stablePartition(
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
subrange: subrange,
count: distance(from: subrange.lowerBound, to: subrange.upperBound), subrange: subrange,
by: belongsInSecondPartition)
}
@@ -78,13 +67,10 @@ extension MutableCollection {
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
@inlinable public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
try stablePartition(subrange: startIndex..<endIndex, by: belongsInSecondPartition)
}
}
@@ -97,15 +83,14 @@ extension MutableCollection {
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
@inlinable public mutating func partition(
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
// This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) else {
return subrange.upperBound
}
var j = index(after: i)
while j != subrange.upperBound {
@@ -125,10 +110,8 @@ extension MutableCollection where Self: BidirectionalCollection {
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
@inlinable public mutating func partition(
subrange: Range<Index>, by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var lo = subrange.lowerBound
var hi = subrange.upperBound
@@ -184,10 +167,9 @@ extension Collection {
///
/// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
@inlinable
public func partitioningIndex(
where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
@inlinable public func partitioningIndex(where belongsInSecondPartition: (Element) throws -> Bool)
rethrows -> Index
{
var n = count
var l = startIndex
+50 -117
View File
@@ -13,8 +13,7 @@
// nextPermutation()
//===----------------------------------------------------------------------===//
extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable {
extension MutableCollection where Self: BidirectionalCollection, Element: Comparable {
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
@@ -27,8 +26,7 @@ where Self: BidirectionalCollection, Element: Comparable {
/// is in ascending order according to `areInIncreasingOrder`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
@inlinable internal mutating func nextPermutation(upperBound: Index? = nil) -> Bool {
// Ensure we have > 1 element in the collection.
guard !isEmpty else { return false }
var i = index(before: endIndex)
@@ -77,31 +75,23 @@ where Self: BidirectionalCollection, Element: Comparable {
/// A sequence of all the permutations of a collection's elements.
public struct Permutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let baseCount: Int
@usableFromInline internal let baseCount: Int
/// The range of accepted sizes of permutations.
/// - Note: This may be empty if the attempted range entirely exceeds the
/// bounds of the size of the `base` collection.
@usableFromInline
internal let kRange: Range<Int>
@usableFromInline internal let kRange: Range<Int>
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
/// - Parameters:
/// - base: The collection to iterate over for permutations
/// - k: The expected size of each permutation, or `nil` (default) to
/// iterate over all permutations of the same size as the base collection.
@inlinable
internal init(_ base: Base, k: Int? = nil) {
@inlinable internal init(_ base: Base, k: Int? = nil) {
let kRange: ClosedRange<Int>?
if let countToChoose = k {
kRange = countToChoose...countToChoose
} else {
kRange = nil
}
if let countToChoose = k { kRange = countToChoose...countToChoose } else { kRange = nil }
self.init(base, kRange: kRange)
}
@@ -111,55 +101,41 @@ public struct Permutations<Base: Collection> {
/// - base: The collection to iterate over for permutations.
/// - kRange: The range of accepted sizes of permutations, or `nil` to
/// iterate over all permutations of the same size as the base collection.
@inlinable
internal init<R: RangeExpression>(
_ base: Base, kRange: R?
) where R.Bound == Int {
@inlinable internal init<R: RangeExpression>(_ base: Base, kRange: R?) where R.Bound == Int {
self.base = base
let baseCount = base.count
self.baseCount = baseCount
let upperBound = baseCount + 1
self.kRange =
kRange?.relative(to: 0 ..< .max)
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound
kRange?.relative(to: 0 ..< .max).clamped(to: 0..<upperBound) ?? baseCount..<upperBound
}
/// The total number of permutations.
@inlinable
public var count: Int {
return kRange.map {
stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *)
}.reduce(0, +)
@inlinable public var count: Int {
return kRange.map { stride(from: baseCount, to: baseCount - $0, by: -1).reduce(1, *) }.reduce(
0, +)
}
}
extension Permutations: Sequence {
/// The iterator for a `Permutations` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let baseCount: Int
@usableFromInline internal let baseCount: Int
/// The current range of accepted sizes of permutations.
/// - Note: The range is contracted until empty while iterating over
/// permutations of different sizes. When the range is empty, iteration is
/// finished.
@usableFromInline
internal var kRange: Range<Int>
@usableFromInline internal var kRange: Range<Int>
/// Whether or not iteration is finished (`kRange` is empty)
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@inlinable internal var isFinished: Bool { return kRange.isEmpty }
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline internal var indexes: [Base.Index]
@inlinable
internal init(_ permutations: Permutations) {
@inlinable internal init(_ permutations: Permutations) {
self.base = permutations.base
self.baseCount = permutations.baseCount
self.kRange = permutations.kRange
@@ -177,8 +153,7 @@ extension Permutations: Sequence {
/// is in ascending order.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal mutating func nextState() -> Bool {
@inlinable internal mutating func nextState() -> Bool {
let countToChoose = self.kRange.lowerBound
let edge = countToChoose - 1
@@ -191,12 +166,8 @@ extension Permutations: Sequence {
// Find last increasing pair below `edge`.
// TODO: This could be indexes[..<edge].adjacentPairs().lastIndex(where: ...)
var lastAscent = edge - 1
while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] {
lastAscent -= 1
}
if lastAscent < 0 {
return false
}
while lastAscent >= 0 && indexes[lastAscent] >= indexes[lastAscent + 1] { lastAscent -= 1 }
if lastAscent < 0 { return false }
// Find rightmost index less than that at `lastAscent`.
if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) {
@@ -208,8 +179,7 @@ extension Permutations: Sequence {
return true
}
@inlinable
public mutating func next() -> [Base.Element]? {
@inlinable public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil }
/// Advances `kRange` by incrementing its `lowerBound` until the range is
@@ -221,9 +191,7 @@ extension Permutations: Sequence {
let countToChoose = self.kRange.lowerBound
if countToChoose == 0 {
defer {
advanceKRange()
}
defer { advanceKRange() }
return []
}
@@ -233,9 +201,7 @@ extension Permutations: Sequence {
// call to `nextPermutation` on `indexes`.
defer {
let hasMorePermutations = indexes.nextPermutation()
if !hasMorePermutations {
advanceKRange()
}
if !hasMorePermutations { advanceKRange() }
}
return indexes.map { base[$0] }
} else {
@@ -243,19 +209,14 @@ extension Permutations: Sequence {
// advance the state.
defer {
let hasMorePermutations = nextState()
if !hasMorePermutations {
advanceKRange()
}
if !hasMorePermutations { advanceKRange() }
}
return indexes.prefix(countToChoose).map { base[$0] }
}
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
}
@inlinable public func makeIterator() -> Iterator { Iterator(self) }
}
extension Permutations: LazySequenceProtocol where Base: LazySequenceProtocol {}
@@ -321,12 +282,8 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
@inlinable
public func permutations<R: RangeExpression>(
ofCount kRange: R
) -> Permutations<Self> where R.Bound == Int {
return Permutations(self, kRange: kRange)
}
@inlinable public func permutations<R: RangeExpression>(ofCount kRange: R) -> Permutations<Self>
where R.Bound == Int { return Permutations(self, kRange: kRange) }
/// Returns a collection of the permutations of this collection of the
/// specified length.
@@ -377,11 +334,8 @@ extension Collection {
/// - Complexity: O(1) for random-access base collections. O(*n*) where *n*
/// is the number of elements in the base collection, since `Permutations`
/// accesses the `count` of the base collection.
@inlinable
public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
precondition(
k ?? 0 >= 0,
"Can't have permutations with a negative number of elements.")
@inlinable public func permutations(ofCount k: Int? = nil) -> Permutations<Self> {
precondition(k ?? 0 >= 0, "Can't have permutations with a negative number of elements.")
return Permutations(self, k: k)
}
}
@@ -397,75 +351,59 @@ extension Collection {
/// `uniquePermutations` methods on your collection.
public struct UniquePermutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline internal var indexes: [Base.Index]
@usableFromInline
internal let kRange: Range<Int>
@usableFromInline internal let kRange: Range<Int>
}
extension UniquePermutations where Base.Element: Hashable {
@inlinable
internal static func _indexes(_ base: Base) -> [Base.Index] {
@inlinable internal static func _indexes(_ base: Base) -> [Base.Index] {
let firstIndexesAndCountsByElement = Dictionary(
base.indices.lazy.map { (base[$0], ($0, 1)) },
uniquingKeysWith: { indexAndCount, _ in (indexAndCount.0, indexAndCount.1 + 1) })
return firstIndexesAndCountsByElement
.values.sorted(by: { $0.0 < $1.0 })
.flatMap { index, count in repeatElement(index, count: count) }
return firstIndexesAndCountsByElement.values.sorted(by: { $0.0 < $1.0 }).flatMap {
index, count in repeatElement(index, count: count)
}
}
@inlinable
internal init(_ elements: Base) {
@inlinable internal init(_ elements: Base) {
self.indexes = Self._indexes(elements)
self.base = elements
self.kRange = self.indexes.count..<(self.indexes.count + 1)
}
@inlinable
internal init<R: RangeExpression>(_ base: Base, _ range: R)
where R.Bound == Int {
@inlinable internal init<R: RangeExpression>(_ base: Base, _ range: R) where R.Bound == Int {
self.indexes = Self._indexes(base)
self.base = base
let upperBound = self.indexes.count + 1
self.kRange = range.relative(to: 0 ..< .max)
.clamped(to: 0..<upperBound)
self.kRange = range.relative(to: 0 ..< .max).clamped(to: 0..<upperBound)
}
}
extension UniquePermutations: Sequence {
/// The iterator for a `UniquePermutations` instance.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline internal var indexes: [Base.Index]
@usableFromInline
internal var lengths: Range<Int>
@usableFromInline internal var lengths: Range<Int>
@usableFromInline
internal var initial = true
@usableFromInline internal var initial = true
@inlinable
internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
@inlinable internal init(_ elements: Base, indexes: [Base.Index], lengths: Range<Int>) {
self.base = elements
self.indexes = indexes
self.lengths = lengths
}
@inlinable
public mutating func next() -> [Base.Element]? {
@inlinable public mutating func next() -> [Base.Element]? {
// In the end case, `lengths` is an empty range.
if lengths.isEmpty {
return nil
}
if lengths.isEmpty { return nil }
// The first iteration must produce the original sorted array, before any
// permutations. We skip the permutation the first time so that we can
@@ -479,17 +417,14 @@ extension UniquePermutations: Sequence {
if !indexes.nextPermutation(upperBound: lengths.lowerBound) {
lengths.removeFirst()
if lengths.isEmpty {
return nil
}
if lengths.isEmpty { return nil }
}
return indexes[..<lengths.lowerBound].map { base[$0] }
}
}
@inlinable
public func makeIterator() -> Iterator {
@inlinable public func makeIterator() -> Iterator {
Iterator(base, indexes: indexes, lengths: kRange)
}
}
@@ -573,7 +508,5 @@ extension Collection where Element: Hashable {
/// - Complexity: O(*n*), where *n* is the number of elements in this
/// collection.
public func uniquePermutations<R: RangeExpression>(ofCount kRange: R) -> UniquePermutations<Self>
where R.Bound == Int {
UniquePermutations(self, kRange)
}
where R.Bound == Int { UniquePermutations(self, kRange) }
}
+81 -138
View File
@@ -12,15 +12,12 @@
/// A sequence that represents the product of two sequences' elements.
public struct Product2<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
@usableFromInline
internal let base1: Base1
@usableFromInline internal let base1: Base1
/// The inner sequence in the product.
@usableFromInline
internal let base2: Base2
@usableFromInline internal let base2: Base2
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
@inlinable internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
}
@@ -31,28 +28,19 @@ extension Product2: Sequence {
/// The iterator for a `Product2` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var i1: Base1.Iterator
@usableFromInline
internal var i2: Base2.Iterator
@usableFromInline
internal var element1: Base1.Element?
@usableFromInline
internal let base2: Base2
@usableFromInline internal var i1: Base1.Iterator
@usableFromInline internal var i2: Base2.Iterator
@usableFromInline internal var element1: Base1.Element?
@usableFromInline internal let base2: Base2
@inlinable
internal init(_ c: Product2) {
@inlinable internal init(_ c: Product2) {
self.base2 = c.base2
self.i1 = c.base1.makeIterator()
self.i2 = c.base2.makeIterator()
self.element1 = nil
}
@inlinable
public mutating func next() -> (
Base1.Element,
Base2.Element
)? {
@inlinable public mutating func next() -> (Base1.Element, Base2.Element)? {
// This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has
// already returned nil.
@@ -64,100 +52,70 @@ extension Product2: Sequence {
// Get the next element from the second sequence, if not
// at end.
if let element2 = i2.next() {
return (element1!, element2)
}
if let element2 = i2.next() { return (element1!, element2) }
// We've reached the end of the second sequence, so:
// 1) Get the next element of the first sequence, if exists
// 2) Restart iteration of the second sequence
// 3) Get the first element of the second sequence, if exists
element1 = i1.next()
guard let element1 = element1
else { return nil }
guard let element1 = element1 else { return nil }
i2 = base2.makeIterator()
if let element2 = i2.next() {
return (element1, element2)
} else {
return nil
}
if let element2 = i2.next() { return (element1, element2) } else { return nil }
}
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
public func makeIterator() -> Iterator { return Iterator(self) }
}
extension Product2: Collection where Base1: Collection {
/// The index type for a `Product2` collection.
public struct Index: Comparable {
@usableFromInline
internal var i1: Base1.Index
@usableFromInline
internal var i2: Base2.Index
@usableFromInline internal var i1: Base1.Index
@usableFromInline internal var i2: Base2.Index
@inlinable
internal init(i1: Base1.Index, i2: Base2.Index) {
@inlinable internal init(i1: Base1.Index, i2: Base2.Index) {
self.i1 = i1
self.i2 = i2
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
}
}
@inlinable
public var count: Int {
base1.count * base2.count
@inlinable public var count: Int { base1.count * base2.count }
@inlinable public var startIndex: Index {
Index(i1: base2.isEmpty ? base1.endIndex : base1.startIndex, i2: base2.startIndex)
}
@inlinable
public var startIndex: Index {
Index(
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
i2: base2.startIndex)
}
@inlinable
public var endIndex: Index {
@inlinable public var endIndex: Index {
// `base2.startIndex` simplifies index calculations.
Index(i1: base1.endIndex, i2: base2.startIndex)
}
@inlinable
public subscript(position: Index) -> (
Base1.Element,
Base2.Element
) {
@inlinable public subscript(position: Index) -> (Base1.Element, Base2.Element) {
(base1[position.i1], base2[position.i2])
}
/// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary.
@inlinable
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
@inlinable internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
i2 == base2.endIndex
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
: Index(i1: i1, i2: i2)
? Index(i1: base1.index(after: i1), i2: base2.startIndex) : Index(i1: i1, i2: i2)
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
return normalizeIndex(i.i1, base2.index(after: i.i2))
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
guard start.i1 <= end.i1
else { return -distance(from: end, to: start) }
guard start.i1 != end.i1
else { return base2.distance(from: start.i2, to: end.i2) }
@inlinable public func distance(from start: Index, to end: Index) -> Int {
guard start.i1 <= end.i1 else { return -distance(from: end, to: start) }
guard start.i1 != end.i1 else { return base2.distance(from: start.i2, to: end.i2) }
// The number of full cycles through `base2` between `start` and `end`,
// excluding the cycles that `start` and `end` are on.
@@ -178,9 +136,7 @@ extension Product2: Collection where Base1: Collection {
let center = base2[start.i2..<end.i2].count
let right = base2[end.i2...].count
return center + right
+ fullBase2Cycles * (left + center + right)
+ left + center
return center + right + fullBase2Cycles * (left + center + right) + left + center
} else {
// start.i2
// v
@@ -200,56 +156,44 @@ extension Product2: Collection where Base1: Collection {
guard fullBase2Cycles > 0 else { return right + left }
let center = base2[end.i2..<start.i2].count
return right
+ fullBase2Cycles * (left + center + right)
+ left
return right + fullBase2Cycles * (left + center + right) + left
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
{
if distance >= 0 {
return limit >= i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
} else {
return limit <= i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance >= 0)
assert(limit >= i)
@@ -260,8 +204,9 @@ extension Product2: Collection where Base1: Collection {
// v v
// i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) }
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2).map { i2 in
Index(i1: i.i1, i2: i2)
}
}
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
@@ -289,8 +234,9 @@ extension Product2: Collection where Base1: Collection {
// ^
// limit.i2
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: nextI1, i2: i2) }
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2).map { i2 in
Index(i1: nextI1, i2: i2)
}
}
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
@@ -312,21 +258,22 @@ extension Product2: Collection where Base1: Collection {
let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
else { return nil }
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1) else {
return nil
}
// The distance from `base2.startIndex` to the target.
let base2Distance = remaining % base2Count
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) }
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit).map { i2 in
Index(i1: i1, i2: i2)
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance >= 0)
assert(limit <= i)
@@ -337,8 +284,9 @@ extension Product2: Collection where Base1: Collection {
// v v
// i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) }
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2).map { i2 in
Index(i1: i.i1, i2: i2)
}
}
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
@@ -366,8 +314,9 @@ extension Product2: Collection where Base1: Collection {
// ^
// i.i2
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: previousI1, i2: i2) }
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2).map { i2 in
Index(i1: previousI1, i2: i2)
}
}
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
@@ -413,26 +362,23 @@ extension Product2: Collection where Base1: Collection {
}
}
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
else { return nil }
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1) else {
return nil
}
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) }
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit).map { i2 in
Index(i1: i1, i2: i2)
}
}
}
extension Product2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(
i != startIndex,
"Can't move before startIndex")
@inlinable public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex")
if i.i2 == base2.startIndex {
return Index(
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
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))
}
@@ -481,9 +427,6 @@ extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Has
/// - s2: The second sequence to iterate over.
///
/// - Complexity: O(1)
@inlinable
public func product<Base1: Sequence, Base2: Collection>(
_ s1: Base1, _ s2: Base2
) -> Product2<Base1, Base2> {
return Product2(s1, s2)
}
@inlinable public func product<Base1: Sequence, Base2: Collection>(_ s1: Base1, _ s2: Base2)
-> Product2<Base1, Base2>
{ return Product2(s1, s2) }
+18 -32
View File
@@ -27,8 +27,7 @@ extension Collection {
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func randomStableSample<G: RandomNumberGenerator>(
@inlinable public func randomStableSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
@@ -67,8 +66,7 @@ extension Collection {
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func randomStableSample(count k: Int) -> [Element] {
@inlinable public func randomStableSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomStableSample(count: k, using: &g)
}
@@ -82,17 +80,13 @@ extension Collection {
// Algorithms of Time Complexity O(n(1 + log(N/n)))":
// https://dl.acm.org/doi/pdf/10.1145/198429.198435
@usableFromInline
internal func nextW<G: RandomNumberGenerator>(
k: Int, using rng: inout G
) -> Double {
Double.root(.random(in: 0..<1, using: &rng), k)
}
@usableFromInline internal func nextW<G: RandomNumberGenerator>(k: Int, using rng: inout G)
-> Double
{ Double.root(.random(in: 0..<1, using: &rng), k) }
@usableFromInline
internal func nextOffset<G: RandomNumberGenerator>(
w: Double, using rng: inout G
) -> Int {
@usableFromInline internal func nextOffset<G: RandomNumberGenerator>(w: Double, using rng: inout G)
-> Int
{
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
return offset < Double(Int.max) ? Int(offset) : Int.max
}
@@ -110,10 +104,9 @@ extension Collection {
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
@inlinable
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
@inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
-> [Element]
{
guard k > 0 else { return [] }
var w = 1.0
@@ -162,8 +155,7 @@ extension Collection {
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
@inlinable
public func randomSample(count k: Int) -> [Element] {
@inlinable public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
@@ -180,10 +172,9 @@ extension Sequence {
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
@inlinable public func randomSample<G: RandomNumberGenerator>(count k: Int, using rng: inout G)
-> [Element]
{
guard k > 0 else { return [] }
var w = 1.0
@@ -192,9 +183,7 @@ extension Sequence {
// Fill the reservoir with the first `k` elements.
var iterator = makeIterator()
while result.count < k, let el = iterator.next() {
result.append(el)
}
while result.count < k, let el = iterator.next() { result.append(el) }
while true {
// Calculate the next value of w.
@@ -204,9 +193,7 @@ extension Sequence {
var offset = nextOffset(w: w, using: &rng)
// Skip over `offset` elements to find the selected element.
while offset > 0, let _ = iterator.next() {
offset -= 1
}
while offset > 0, let _ = iterator.next() { offset -= 1 }
guard let nextElement = iterator.next() else { break }
// Swap selected element with a randomly chosen one in the reservoir.
@@ -231,8 +218,7 @@ extension Sequence {
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomSample(count k: Int) -> [Element] {
@inlinable public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
+108 -226
View File
@@ -34,14 +34,10 @@ extension LazySequenceProtocol {
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
@inlinable public func reductions<Result>(
_ initial: Result, _ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
return reductions(into: initial) { result, element in
result = transform(result, element)
}
return reductions(into: initial) { result, element in result = transform(result, element) }
}
/// Returns a sequence containing the accumulated results of combining the
@@ -65,10 +61,8 @@ extension LazySequenceProtocol {
/// elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
@inlinable public func reductions<Result>(
into initial: Result, _ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
ExclusiveReductions(base: self, initial: initial, transform: transform)
}
@@ -110,10 +104,8 @@ extension Sequence {
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
@inlinable public func reductions<Result>(
_ initial: Result, _ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
return try reductions(into: initial) { result, element in
result = try transform(result, element)
@@ -154,10 +146,8 @@ extension Sequence {
/// - Returns: An array of the initial value followed by the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
@inlinable public func reductions<Result>(
into initial: Result, _ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
var output = [Result]()
@@ -177,20 +167,14 @@ extension Sequence {
/// A sequence of applying a transform to the element of a sequence and the
/// previously transformed result.
public struct ExclusiveReductions<Result, Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let initial: Result
@usableFromInline internal let initial: Result
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@usableFromInline internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
base: Base,
initial: Result,
transform: @escaping (inout Result, Base.Element) -> Void
@inlinable internal init(
base: Base, initial: Result, transform: @escaping (inout Result, Base.Element) -> Void
) {
self.base = base
self.initial = initial
@@ -200,19 +184,14 @@ public struct ExclusiveReductions<Result, Base: Sequence> {
extension ExclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline internal var iterator: Base.Iterator
@usableFromInline
internal var current: Result?
@usableFromInline internal var current: Result?
@usableFromInline
internal let transform: (inout Result, Base.Element) -> Void
@usableFromInline internal let transform: (inout Result, Base.Element) -> Void
@inlinable
internal init(
iterator: Base.Iterator,
current: Result? = nil,
@inlinable internal init(
iterator: Base.Iterator, current: Result? = nil,
transform: @escaping (inout Result, Base.Element) -> Void
) {
self.iterator = iterator
@@ -220,11 +199,9 @@ extension ExclusiveReductions: Sequence {
self.transform = transform
}
@inlinable
public mutating func next() -> Result? {
@inlinable public mutating func next() -> Result? {
guard let result = current else { return nil }
current = iterator.next().map { element in
var result = result
current = iterator.next().map { element in var result = result
transform(&result, element)
return result
}
@@ -232,41 +209,29 @@ extension ExclusiveReductions: Sequence {
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(
iterator: base.makeIterator(),
current: initial,
transform: transform)
@inlinable public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), current: initial, transform: transform)
}
}
extension ExclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
@usableFromInline internal let representation: ReductionsIndexRepresentation<Base.Index, Result>
@inlinable
internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Result>
) {
@inlinable internal init(_ representation: ReductionsIndexRepresentation<Base.Index, Result>) {
self.representation = representation
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
@inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
}
}
@inlinable
public var startIndex: Index { Index(.start) }
@inlinable public var startIndex: Index { Index(.start) }
@inlinable
public var endIndex: Index { Index(.end) }
@inlinable public var endIndex: Index { Index(.end) }
@inlinable
public subscript(position: Index) -> Result {
@inlinable public subscript(position: Index) -> Result {
switch position.representation {
case .start: return initial
case .base(_, let result): return result
@@ -274,8 +239,7 @@ extension ExclusiveReductions: Collection where Base: Collection {
}
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
func index(base index: Base.Index, previous: Result) -> Index {
guard index != base.endIndex else { return endIndex }
var previous = previous
@@ -283,45 +247,30 @@ extension ExclusiveReductions: Collection where Base: Collection {
return Index(.base(index: index, result: previous))
}
switch i.representation {
case .start:
return index(base: base.startIndex, previous: initial)
case let .base(i, result):
return index(base: base.index(after: i), previous: result)
case .end:
fatalError("Cannot get index after end index.")
case .start: return index(base: base.startIndex, previous: initial)
case let .base(i, result): return index(base: base.index(after: i), previous: result)
case .end: fatalError("Cannot get index after end index.")
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index) + 1
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex) + 1
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex) - 1
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex) - 1
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
case (.start, .start): return 0
case let (.start, .base(index, _)): return base.distance(from: base.startIndex, to: index) + 1
case (.start, .end): return base.distance(from: base.startIndex, to: base.endIndex) + 1
case let (.base(index, _), .start): return base.distance(from: index, to: base.startIndex) - 1
case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end)
case let (.base(index, _), .end): return base.distance(from: index, to: base.endIndex)
case (.end, .start): return base.distance(from: base.endIndex, to: base.startIndex) - 1
case let (.end, .base(index, _)): return base.distance(from: base.endIndex, to: index)
case (.end, .end): return 0
}
}
}
extension ExclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension ExclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
// MARK: - Inclusive Reductions
@@ -346,12 +295,9 @@ extension LazySequenceProtocol {
/// - Returns: A sequence of the reduced elements.
///
/// - Complexity: O(1)
@inlinable
public func reductions(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
InclusiveReductions(base: self, transform: transform)
}
@inlinable public func reductions(_ transform: @escaping (Element, Element) -> Element)
-> InclusiveReductions<Self>
{ InclusiveReductions(base: self, transform: transform) }
}
extension Sequence {
@@ -391,10 +337,9 @@ extension Sequence {
/// - Returns: An array of the reduced elements.
///
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
@inlinable
public func reductions(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
@inlinable public func reductions(_ transform: (Element, Element) throws -> Element) rethrows
-> [Element]
{
var iterator = makeIterator()
guard let initial = iterator.next() else { return [] }
return try IteratorSequence(iterator).reductions(initial, transform)
@@ -402,16 +347,12 @@ extension Sequence {
}
public struct InclusiveReductions<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
base: Base,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
@inlinable internal init(
base: Base, transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.base = base
self.transform = transform
@@ -420,19 +361,14 @@ public struct InclusiveReductions<Base: Sequence> {
extension InclusiveReductions: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline internal var iterator: Base.Iterator
@usableFromInline
internal var element: Base.Element?
@usableFromInline internal var element: Base.Element?
@usableFromInline
internal let transform: (Base.Element, Base.Element) -> Base.Element
@usableFromInline internal let transform: (Base.Element, Base.Element) -> Base.Element
@inlinable
internal init(
iterator: Base.Iterator,
element: Base.Element? = nil,
@inlinable internal init(
iterator: Base.Iterator, element: Base.Element? = nil,
transform: @escaping (Base.Element, Base.Element) -> Base.Element
) {
self.iterator = iterator
@@ -440,8 +376,7 @@ extension InclusiveReductions: Sequence {
self.transform = transform
}
@inlinable
public mutating func next() -> Base.Element? {
@inlinable public mutating func next() -> Base.Element? {
guard let previous = element else {
element = iterator.next()
return element
@@ -452,43 +387,33 @@ extension InclusiveReductions: Sequence {
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(
iterator: base.makeIterator(),
transform: transform)
@inlinable public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), transform: transform)
}
}
extension InclusiveReductions: Collection where Base: Collection {
public struct Index: Comparable {
@usableFromInline
internal let representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
@usableFromInline internal let representation:
ReductionsIndexRepresentation<Base.Index, Base.Element>
@inlinable
internal init(
@inlinable internal init(
_ representation: ReductionsIndexRepresentation<Base.Index, Base.Element>
) {
self.representation = representation
}
) { self.representation = representation }
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
@inlinable public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.representation < rhs.representation
}
}
@inlinable
public var startIndex: Index {
@inlinable public var startIndex: Index {
guard base.startIndex != base.endIndex else { return endIndex }
return Index(.start)
}
@inlinable
public var endIndex: Index { Index(.end) }
@inlinable public var endIndex: Index { Index(.end) }
@inlinable
public subscript(position: Index) -> Base.Element {
@inlinable public subscript(position: Index) -> Base.Element {
switch position.representation {
case .start: return base[base.startIndex]
case .base(_, let result): return result
@@ -496,66 +421,48 @@ extension InclusiveReductions: Collection where Base: Collection {
}
}
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
func index(after i: Base.Index, previous: Base.Element) -> Index {
let index = base.index(after: i)
guard index != base.endIndex else { return endIndex }
return Index(.base(index: index, result: transform(previous, base[index])))
}
switch i.representation {
case .start:
return index(after: base.startIndex, previous: base[base.startIndex])
case let .base(i, element):
return index(after: i, previous: element)
case .end:
fatalError("Cannot get index after end index.")
case .start: return index(after: base.startIndex, previous: base[base.startIndex])
case let .base(i, element): return index(after: i, previous: element)
case .end: fatalError("Cannot get index after end index.")
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
switch (start.representation, end.representation) {
case (.start, .start):
return 0
case let (.start, .base(index, _)):
return base.distance(from: base.startIndex, to: index)
case (.start, .end):
return base.distance(from: base.startIndex, to: base.endIndex)
case let (.base(index, _), .start):
return base.distance(from: index, to: base.startIndex)
case let (.base(start, _), .base(end, _)):
return base.distance(from: start, to: end)
case let (.base(index, _), .end):
return base.distance(from: index, to: base.endIndex)
case (.end, .start):
return base.distance(from: base.endIndex, to: base.startIndex)
case let (.end, .base(index, _)):
return base.distance(from: base.endIndex, to: index)
case (.end, .end):
return 0
case (.start, .start): return 0
case let (.start, .base(index, _)): return base.distance(from: base.startIndex, to: index)
case (.start, .end): return base.distance(from: base.startIndex, to: base.endIndex)
case let (.base(index, _), .start): return base.distance(from: index, to: base.startIndex)
case let (.base(start, _), .base(end, _)): return base.distance(from: start, to: end)
case let (.base(index, _), .end): return base.distance(from: index, to: base.endIndex)
case (.end, .start): return base.distance(from: base.endIndex, to: base.startIndex)
case let (.end, .base(index, _)): return base.distance(from: base.endIndex, to: index)
case (.end, .end): return 0
}
}
}
extension InclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
extension InclusiveReductions: LazySequenceProtocol where Base: LazySequenceProtocol {}
extension InclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
extension InclusiveReductions: LazyCollectionProtocol where Base: LazyCollectionProtocol {}
// MARK: - ReductionsIndexRepresentation
@usableFromInline
enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
@usableFromInline enum ReductionsIndexRepresentation<BaseIndex: Comparable, Result> {
case start
case base(index: BaseIndex, result: Result)
case end
}
extension ReductionsIndexRepresentation: Equatable {
@inlinable
static func == (lhs: Self, rhs: Self) -> Bool {
@inlinable static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.start, .start): return true
case (.end, .end): return true
@@ -566,8 +473,7 @@ extension ReductionsIndexRepresentation: Equatable {
}
extension ReductionsIndexRepresentation: Comparable {
@inlinable
static func < (lhs: Self, rhs: Self) -> Bool {
@inlinable static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (_, .start): return false
case (.start, _): return true
@@ -582,64 +488,40 @@ extension ReductionsIndexRepresentation: Comparable {
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: @escaping (Result, Element) -> Result
) -> ExclusiveReductions<Result, Self> {
reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable
public func scan<Result>(_ initial: Result, _ transform: @escaping (Result, Element) -> Result)
-> ExclusiveReductions<Result, Self>
{ reductions(initial, transform) }
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
@available(*, deprecated, message: "Use reductions(into:_:) instead.") @inlinable
public func scan<Result>(
into initial: Result,
_ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> {
reductions(into: initial, transform)
}
into initial: Result, _ transform: @escaping (inout Result, Element) -> Void
) -> ExclusiveReductions<Result, Self> { reductions(into: initial, transform) }
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:_:) instead.")
@inlinable
public func scan<Result>(
_ initial: Result,
_ transform: (Result, Element) throws -> Result
) rethrows -> [Result] {
try reductions(initial, transform)
}
@available(*, deprecated, message: "Use reductions(_:_:) instead.") @inlinable
public func scan<Result>(_ initial: Result, _ transform: (Result, Element) throws -> Result)
rethrows -> [Result]
{ try reductions(initial, transform) }
@available(*, deprecated, message: "Use reductions(into:_:) instead.")
@inlinable
@available(*, deprecated, message: "Use reductions(into:_:) instead.") @inlinable
public func scan<Result>(
into initial: Result,
_ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] {
try reductions(into: initial, transform)
}
into initial: Result, _ transform: (inout Result, Element) throws -> Void
) rethrows -> [Result] { try reductions(into: initial, transform) }
}
extension LazySequenceProtocol {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
@available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
_ transform: @escaping (Element, Element) -> Element
) -> InclusiveReductions<Self> {
reductions(transform)
}
) -> InclusiveReductions<Self> { reductions(transform) }
}
extension Sequence {
@available(*, deprecated, message: "Use reductions(_:) instead.")
@inlinable
public func scan(
@available(*, deprecated, message: "Use reductions(_:) instead.") @inlinable public func scan(
_ transform: (Element, Element) throws -> Element
) rethrows -> [Element] {
try reductions(transform)
}
) rethrows -> [Element] { try reductions(transform) }
}
+13 -34
View File
@@ -29,9 +29,7 @@ extension MutableCollection where Self: BidirectionalCollection {
///
/// - Postcondition: For returned indices `(lower, upper)`:
/// `lower == limit || upper == limit`
@inlinable
@discardableResult
internal mutating func _reverse(
@inlinable @discardableResult internal mutating func _reverse(
subrange: Range<Index>, until limit: Index
) -> (Index, Index) {
var lower = subrange.lowerBound
@@ -56,8 +54,7 @@ extension MutableCollection where Self: BidirectionalCollection {
/// - Parameter subrange: The subrange of this collection to reverse.
///
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable
public mutating func reverse(subrange: Range<Index>) {
@inlinable public mutating func reverse(subrange: Range<Index>) {
if subrange.isEmpty { return }
var lower = subrange.lowerBound
var upper = subrange.upperBound
@@ -94,8 +91,7 @@ extension MutableCollection {
/// - distance(from: lhs.lowerBound, to: p) == distance(from:
/// rhs.lowerBound, to: q)
/// - p == lhs.upperBound || q == rhs.upperBound
@inlinable
internal mutating func _swapNonemptySubrangePrefixes(
@inlinable internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ rhs: Range<Index>
) -> (Index, Index) {
assert(!lhs.isEmpty)
@@ -132,11 +128,8 @@ extension MutableCollection {
/// `subrange` pre-rotation.
///
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
toStartAt newStart: Index
@inlinable @discardableResult public mutating func rotate(
subrange: Range<Index>, toStartAt newStart: Index
) -> Index {
var m = newStart
var s = subrange.lowerBound
@@ -213,9 +206,7 @@ extension MutableCollection {
/// - Returns: The new index of the element that was first pre-rotation.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func rotate(toStartAt newStart: Index) -> Index {
@inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
}
}
@@ -242,11 +233,8 @@ extension MutableCollection where Self: BidirectionalCollection {
/// `subrange` pre-rotation.
///
/// - Complexity: O(*n*), where *n* is the length of `subrange`.
@inlinable
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
toStartAt newStart: Index
@inlinable @discardableResult public mutating func rotate(
subrange: Range<Index>, toStartAt newStart: Index
) -> Index {
reverse(subrange: subrange.lowerBound..<newStart)
reverse(subrange: newStart..<subrange.upperBound)
@@ -273,9 +261,7 @@ extension MutableCollection where Self: BidirectionalCollection {
/// - Returns: The new index of the element that was first pre-rotation.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func rotate(toStartAt newStart: Index) -> Index {
@inlinable @discardableResult public mutating func rotate(toStartAt newStart: Index) -> Index {
rotate(subrange: startIndex..<endIndex, toStartAt: newStart)
}
}
@@ -283,18 +269,11 @@ extension MutableCollection where Self: BidirectionalCollection {
// Deprecations
extension MutableCollection {
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)")
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index
) -> Index {
@available(*, deprecated, renamed: "rotate(subrange:toStartAt:)") @discardableResult
public mutating func rotate(subrange: Range<Index>, at newStart: Index) -> Index {
rotate(subrange: subrange, toStartAt: newStart)
}
@available(*, deprecated, renamed: "rotate(toStartAt:)")
@discardableResult
public mutating func rotate(at newStart: Index) -> Index {
rotate(toStartAt: newStart)
}
@available(*, deprecated, renamed: "rotate(toStartAt:)") @discardableResult
public mutating func rotate(at newStart: Index) -> Index { rotate(toStartAt: newStart) }
}
+41 -114
View File
@@ -26,8 +26,7 @@ extension Sequence {
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a sequence for stepping through the
/// elements by the specified amount.
@inlinable
public func striding(by step: Int) -> StrideSequence<Self> {
@inlinable public func striding(by step: Int) -> StrideSequence<Self> {
StrideSequence(base: self, stride: step)
}
}
@@ -46,8 +45,7 @@ extension Collection {
/// - Parameter step: The amount to step with each iteration.
/// - Returns: Returns a collection for stepping through the
/// elements by the specified amount.
@inlinable
public func striding(by step: Int) -> StrideCollection<Self> {
@inlinable public func striding(by step: Int) -> StrideCollection<Self> {
StrideCollection(base: self, stride: step)
}
}
@@ -55,14 +53,11 @@ extension Collection {
/// A wrapper that strides over a base sequence.
public struct StrideSequence<Base: Sequence>: Sequence {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let stride: Int
@usableFromInline internal let stride: Int
@inlinable
internal init(base: Base, stride: Int) {
@inlinable internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
self.base = base
self.stride = stride
@@ -73,57 +68,43 @@ extension StrideSequence {
/// An iterator over a `Stride` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline internal var iterator: Base.Iterator
@usableFromInline
internal let stride: Int
@usableFromInline internal let stride: Int
@usableFromInline
internal var striding: Bool = false
@usableFromInline internal var striding: Bool = false
@inlinable
internal init(iterator: Base.Iterator, stride: Int) {
@inlinable internal init(iterator: Base.Iterator, stride: Int) {
self.iterator = iterator
self.stride = stride
}
@inlinable
public mutating func next() -> Base.Element? {
@inlinable public mutating func next() -> Base.Element? {
guard striding else {
striding = true
return iterator.next()
}
for _ in 0..<stride - 1 {
guard iterator.next() != nil else { break }
}
for _ in 0..<stride - 1 { guard iterator.next() != nil else { break } }
return iterator.next()
}
}
@inlinable
public func makeIterator() -> Iterator {
@inlinable public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), stride: stride)
}
}
extension StrideSequence {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
@inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
}
/// A wrapper that strides over a base collection.
public struct StrideCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let stride: Int
@usableFromInline internal let stride: Int
@inlinable
internal init(base: Base, stride: Int) {
@inlinable internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
self.base = base
self.stride = stride
@@ -131,57 +112,32 @@ public struct StrideCollection<Base: Collection> {
}
extension StrideCollection {
@inlinable
public func striding(by step: Int) -> Self {
Self(base: base, stride: stride * step)
}
@inlinable public func striding(by step: Int) -> Self { Self(base: base, stride: stride * step) }
}
extension StrideCollection: Collection {
/// A position in a `Stride` collection.
public struct Index: Comparable {
@usableFromInline
internal let base: Base.Index
@usableFromInline internal let base: Base.Index
@usableFromInline
internal init(_ base: Base.Index) {
self.base = base
}
@usableFromInline internal init(_ base: Base.Index) { self.base = base }
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool { lhs.base < rhs.base }
}
@inlinable
public var startIndex: Index {
Index(base.startIndex)
}
@inlinable public var startIndex: Index { Index(base.startIndex) }
@inlinable
public var endIndex: Index {
Index(base.endIndex)
}
@inlinable public var endIndex: Index { Index(base.endIndex) }
@inlinable
public subscript(i: Index) -> Base.Element {
base[i.base]
}
@inlinable public subscript(i: Index) -> Base.Element { base[i.base] }
@inlinable
public func index(after i: Index) -> Index {
@inlinable public func index(after i: Index) -> Index {
precondition(i.base < base.endIndex, "Advancing past end index")
return index(i, offsetBy: 1)
}
@inlinable
public func index(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? {
guard n != 0 else { return i }
guard limit != i else { return nil }
@@ -190,66 +146,39 @@ extension StrideCollection: Collection {
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
}
@inlinable
internal func offsetForward(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetForward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
-> Index?
{
if limit < i {
if let idx = base.index(
i.base,
offsetBy: n * stride,
limitedBy: base.endIndex
) {
if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: base.endIndex) {
return Index(idx)
} else {
assert(distance(from: i, to: endIndex) == n, "Advancing past end index")
return endIndex
}
} else if let idx = base.index(
i.base,
offsetBy: n * stride,
limitedBy: limit.base
) {
} else if let idx = base.index(i.base, offsetBy: n * stride, limitedBy: limit.base) {
return Index(idx)
} else {
return distance(from: i, to: limit) == n
? endIndex
: nil
return distance(from: i, to: limit) == n ? endIndex : nil
}
}
@inlinable
internal func offsetBackward(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetBackward(_ i: Index, offsetBy n: Int, limitedBy limit: Index)
-> Index?
{
let distance =
i == endIndex
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
: n * -stride
return base.index(
i.base,
offsetBy: distance,
limitedBy: limit.base
).map(Index.init)
i == endIndex ? -((base.count - 1) % stride + 1) + (n - 1) * -stride : n * -stride
return base.index(i.base, offsetBy: distance, limitedBy: limit.base).map(Index.init)
}
@inlinable
public var count: Int {
base.isEmpty ? 0 : (base.count - 1) / stride + 1
}
@inlinable public var count: Int { base.isEmpty ? 0 : (base.count - 1) / stride + 1 }
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable public func distance(from start: Index, to end: Index) -> Int {
let distance = base.distance(from: start.base, to: end.base)
return distance / stride + (distance % stride).signum()
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
precondition(distance >= 0 || i.base > base.startIndex, "Incrementing past start index")
let limit = distance > 0 ? endIndex : startIndex
@@ -259,11 +188,9 @@ extension StrideCollection: Collection {
}
}
extension StrideCollection: BidirectionalCollection
where Base: RandomAccessCollection {
extension StrideCollection: BidirectionalCollection where Base: RandomAccessCollection {
@inlinable
public func index(before i: Index) -> Index {
@inlinable public func index(before i: Index) -> Index {
precondition(i.base > base.startIndex, "Incrementing past start index")
return index(i, offsetBy: -1)
}
+8 -18
View File
@@ -23,10 +23,7 @@ extension BidirectionalCollection {
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func suffix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
@inlinable public func suffix(while predicate: (Element) throws -> Bool) rethrows -> SubSequence {
try self[startOfSuffix(while: predicate)...]
}
}
@@ -45,14 +42,10 @@ extension Collection {
/// be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func endOfPrefix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
@inlinable internal func endOfPrefix(while predicate: (Element) throws -> Bool) rethrows -> Index
{
var index = startIndex
while try index != endIndex && predicate(self[index]) {
formIndex(after: &index)
}
while try index != endIndex && predicate(self[index]) { formIndex(after: &index) }
return index
}
}
@@ -71,17 +64,14 @@ extension BidirectionalCollection {
/// be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
internal func startOfSuffix(
while predicate: (Element) throws -> Bool
) rethrows -> Index {
@inlinable internal func startOfSuffix(while predicate: (Element) throws -> Bool) rethrows
-> Index
{
var index = endIndex
while index != startIndex {
let after = index
formIndex(before: &index)
if try !predicate(self[index]) {
return after
}
if try !predicate(self[index]) { return after }
}
return index
}
+2 -4
View File
@@ -25,10 +25,8 @@ extension BidirectionalCollection {
///
/// - Complexity: O(*n*), where *n* is the length of this collection.
///
@inlinable
public func trimming(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
@inlinable public func trimming(while predicate: (Element) throws -> Bool) rethrows -> SubSequence
{
let start = try endOfPrefix(while: predicate)
let end = try self[start...].startOfSuffix(while: predicate)
return self[start..<end]
+19 -38
View File
@@ -12,15 +12,12 @@
/// A sequence wrapper that leaves out duplicate elements of a base sequence.
public struct Uniqued<Base: Sequence, Subject: Hashable> {
/// The base collection.
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
/// The projection function.
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline internal let projection: (Base.Element) -> Subject
@usableFromInline
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
@usableFromInline internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
self.base = base
self.projection = projection
}
@@ -29,37 +26,28 @@ public struct Uniqued<Base: Sequence, Subject: Hashable> {
extension Uniqued: Sequence {
/// The iterator for a `Uniqued` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var base: Base.Iterator
@usableFromInline internal var base: Base.Iterator
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline internal let projection: (Base.Element) -> Subject
@usableFromInline
internal var seen: Set<Subject> = []
@usableFromInline internal var seen: Set<Subject> = []
@usableFromInline
internal init(
base: Base.Iterator,
projection: @escaping (Base.Element) -> Subject
@usableFromInline internal init(
base: Base.Iterator, projection: @escaping (Base.Element) -> Subject
) {
self.base = base
self.projection = projection
}
@inlinable
public mutating func next() -> Base.Element? {
@inlinable public mutating func next() -> Base.Element? {
while let element = base.next() {
if seen.insert(projection(element)).inserted {
return element
}
if seen.insert(projection(element)).inserted { return element }
}
return nil
}
}
@inlinable
public func makeIterator() -> Iterator {
@inlinable public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator(), projection: projection)
}
}
@@ -82,8 +70,7 @@ extension Sequence where Element: Hashable {
/// - Returns: A sequence with only the unique elements of this sequence.
/// .
/// - Complexity: O(1).
@inlinable
public func uniqued() -> Uniqued<Self, Element> {
@inlinable public func uniqued() -> Uniqued<Self, Element> {
Uniqued(base: self, projection: { $0 })
}
}
@@ -110,16 +97,13 @@ extension Sequence {
/// determined by the result of `projection` for each element.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func uniqued<Subject: Hashable>(
on projection: (Element) throws -> Subject
) rethrows -> [Element] {
@inlinable public func uniqued<Subject: Hashable>(on projection: (Element) throws -> Subject)
rethrows -> [Element]
{
var seen: Set<Subject> = []
var result: [Element] = []
for element in self {
if seen.insert(try projection(element)).inserted {
result.append(element)
}
if seen.insert(try projection(element)).inserted { result.append(element) }
}
return result
}
@@ -135,10 +119,7 @@ extension LazySequenceProtocol {
/// of each unique element.
///
/// - Complexity: O(1).
@inlinable
public func uniqued<Subject: Hashable>(
on projection: @escaping (Element) -> Subject
) -> Uniqued<Self, Subject> {
Uniqued(base: self, projection: projection)
}
@inlinable public func uniqued<Subject: Hashable>(on projection: @escaping (Element) -> Subject)
-> Uniqued<Self, Subject>
{ Uniqued(base: self, projection: projection) }
}
+52 -107
View File
@@ -38,8 +38,7 @@ extension Collection {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
/// Access to successive windows is O(1).
@inlinable
public func windows(ofCount count: Int) -> Windows<Self> {
@inlinable public func windows(ofCount count: Int) -> Windows<Self> {
Windows(base: self, size: count)
}
}
@@ -47,53 +46,42 @@ extension Collection {
/// A collection wrapper that presents a sliding window over the elements of
/// a collection.
public struct Windows<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline internal let base: Base
@usableFromInline
internal let size: Int
@usableFromInline internal let size: Int
@usableFromInline
internal var firstUpperBound: Base.Index?
@usableFromInline internal var firstUpperBound: Base.Index?
@inlinable
internal init(base: Base, size: Int) {
@inlinable internal init(base: Base, size: Int) {
precondition(size > 0, "Windows size must be greater than zero")
self.base = base
self.size = size
self.firstUpperBound =
base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
self.firstUpperBound = base.index(base.startIndex, offsetBy: size, limitedBy: base.endIndex)
}
}
extension Windows: Collection {
/// A position in a `Windows` collection.
public struct Index: Comparable {
@usableFromInline
internal var lowerBound: Base.Index
@usableFromInline internal var lowerBound: Base.Index
@usableFromInline
internal var upperBound: Base.Index
@usableFromInline internal var upperBound: Base.Index
@inlinable
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
@inlinable internal init(lowerBound: Base.Index, upperBound: Base.Index) {
self.lowerBound = lowerBound
self.upperBound = upperBound
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound == rhs.lowerBound
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
@inlinable public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound
}
}
@inlinable
public var startIndex: Index {
@inlinable public var startIndex: Index {
if let upperBound = firstUpperBound {
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else {
@@ -101,76 +89,60 @@ extension Windows: Collection {
}
}
@inlinable
public var endIndex: Index {
@inlinable public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
}
@inlinable
public subscript(index: Index) -> Base.SubSequence {
precondition(
index.lowerBound != index.upperBound,
"Windows index is out of range")
@inlinable public subscript(index: Index) -> Base.SubSequence {
precondition(index.lowerBound != index.upperBound, "Windows index is out of range")
return base[index.lowerBound..<index.upperBound]
}
@inlinable
public func index(after index: Index) -> Index {
@inlinable public func index(after index: Index) -> Index {
precondition(index < endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex }
return Index(
lowerBound: base.index(after: index.lowerBound),
upperBound: base.index(after: index.upperBound)
)
upperBound: base.index(after: index.upperBound))
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
@inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
return distance > 0 ? offsetForward(i, by: distance) : offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
@inlinable public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index?
{
guard distance != 0 else { return i }
guard limit != i else { return nil }
if distance > 0 {
return limit > i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
? offsetForward(i, by: distance, limitedBy: limit) : offsetForward(i, by: distance)
} else {
return limit < i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
? offsetBackward(i, by: -distance, limitedBy: limit) : offsetBackward(i, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
@inlinable internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex) else {
fatalError("Index is out of bounds")
}
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetForward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance > 0)
assert(limit > i)
@@ -196,22 +168,16 @@ extension Windows: Collection {
guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - size,
limitedBy: limit.lowerBound),
i.upperBound, offsetBy: distance - size, limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: size - 1,
limitedBy: limit.upperBound)
lowerBound, offsetBy: size - 1, limitedBy: limit.upperBound)
else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index(
lowerBound: lowerBound,
upperBound: base.index(after: indexBeforeUpperBound))
return Index(lowerBound: lowerBound, upperBound: base.index(after: indexBeforeUpperBound))
} else {
// input: [x|x x x x x x|x x x x x]
// |> > > >| |> > >|>|
@@ -219,15 +185,12 @@ extension Windows: Collection {
guard
let indexBeforeUpperBound = base.index(
i.upperBound,
offsetBy: distance - 1,
limitedBy: limit.upperBound)
i.upperBound, offsetBy: distance - 1, limitedBy: limit.upperBound)
else { return nil }
// If `indexBeforeUpperBound` equals the limit, the upper bound itself
// exceeds it.
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
else { return nil }
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
@@ -239,10 +202,9 @@ extension Windows: Collection {
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
@inlinable internal func offsetBackward(_ i: Index, by distance: Int, limitedBy limit: Index)
-> Index?
{
assert(distance > 0)
assert(limit < i)
@@ -258,14 +220,10 @@ extension Windows: Collection {
guard
let upperBound = base.index(
base.endIndex,
offsetBy: -(distance - 1),
limitedBy: limit.upperBound)
base.endIndex, offsetBy: -(distance - 1), limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
} else if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
// bound of the output is less than or equal to the lower bound of the
@@ -277,34 +235,25 @@ extension Windows: Collection {
guard limit.upperBound <= i.lowerBound,
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - size),
limitedBy: limit.upperBound)
i.lowerBound, offsetBy: -(distance - size), limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
return Index(lowerBound: base.index(upperBound, offsetBy: -size), upperBound: upperBound)
} else {
// 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]
guard
let lowerBound = base.index(
i.lowerBound,
offsetBy: -distance,
limitedBy: limit.lowerBound)
let lowerBound = base.index(i.lowerBound, offsetBy: -distance, limitedBy: limit.lowerBound)
else { return nil }
return Index(
lowerBound: lowerBound,
upperBound: base.index(i.lowerBound, offsetBy: -distance))
lowerBound: lowerBound, upperBound: base.index(i.lowerBound, offsetBy: -distance))
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
@inlinable 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 0 }
guard end < endIndex else {
@@ -333,19 +282,15 @@ extension Windows: Collection {
}
extension Windows: BidirectionalCollection where Base: BidirectionalCollection {
@inlinable
public func index(before index: Index) -> Index {
@inlinable public func index(before index: Index) -> Index {
precondition(index > startIndex, "Incrementing past start index")
if index == endIndex {
return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -size),
upperBound: index.upperBound
)
lowerBound: base.index(index.lowerBound, offsetBy: -size), upperBound: index.upperBound)
} else {
return Index(
lowerBound: base.index(before: index.lowerBound),
upperBound: base.index(before: index.upperBound)
)
upperBound: base.index(before: index.upperBound))
}
}
}
+2 -6
View File
@@ -38,13 +38,9 @@ final class ChainTests: XCTestCase {
func testChainIndexTraversals() {
validateIndexTraversals(
chain("abcd", "XYZ"),
chain("abcd", ""),
chain("", "XYZ"),
chain("", ""),
chain("abcd", "XYZ"), chain("abcd", ""), chain("", "XYZ"), chain("", ""),
indices: { chain in
chain.base1.indices.map { .init(first: $0) }
+ chain.base2.indices.map { .init(second: $0) }
chain.base1.indices.map { .init(first: $0) } + chain.base2.indices.map { .init(second: $0) }
+ [.init(second: chain.base2.endIndex)]
})
}
+14 -33
View File
@@ -14,24 +14,16 @@ import XCTest
final class ChunkedTests: XCTestCase {
let fruits = [
"Apple", "Apricot", "Avocado", "Banana",
"Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
"Currant", "Cherry", "Cherimoya", "Clementine",
"Date", "Damson", "Dragonfruit", "Durian",
"Eggplant", "Elderberry", "Feijoa",
"Grape", "Grapefruit", "Guava",
"Apple", "Apricot", "Avocado", "Banana", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry",
"Currant", "Cherry", "Cherimoya", "Clementine", "Date", "Damson", "Dragonfruit", "Durian",
"Eggplant", "Elderberry", "Feijoa", "Grape", "Grapefruit", "Guava",
]
func validateFruitChunks<C: BidirectionalCollection>(_ fruitChunks: C)
where C.Element == ArraySlice<String> {
let expectedChunks: [ArraySlice<String>] = [
fruits[0..<3],
fruits[3..<8],
fruits[8..<12],
fruits[12..<16],
fruits[16..<18],
fruits[18..<19],
fruits[19..<22],
fruits[0..<3], fruits[3..<8], fruits[8..<12], fruits[12..<16], fruits[16..<18],
fruits[18..<19], fruits[19..<22],
]
XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==)
@@ -85,22 +77,15 @@ final class ChunkedTests: XCTestCase {
let collection1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
XCTAssertEqualSequences(
collection1.chunks(ofCount: 1),
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
collection1.chunks(ofCount: 1), [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 3),
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 5),
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 11),
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
collection1.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])
XCTAssertEqualSequences(collection1.chunks(ofCount: 5), [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
XCTAssertEqualSequences(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]
XCTAssertEqualSequences(
collection2.chunks(ofCount: 3),
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
collection2.chunks(ofCount: 3), [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]])
}
func testChunksOfCountBidirectional() {
@@ -110,19 +95,15 @@ final class ChunkedTests: XCTestCase {
collection1.chunks(ofCount: 1).reversed(),
[[10], [9], [8], [7], [6], [5], [4], [3], [2], [1]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 3).reversed(),
[[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
collection1.chunks(ofCount: 3).reversed(), [[10], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 5).reversed(),
[[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
collection1.chunks(ofCount: 5).reversed(), [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]])
XCTAssertEqualSequences(
collection1.chunks(ofCount: 11).reversed(),
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
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]
XCTAssertEqualSequences(
collection2.chunks(ofCount: 3).reversed(),
[[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
collection2.chunks(ofCount: 3).reversed(), [[10, 11], [7, 8, 9], [4, 5, 6], [1, 2, 3]])
}
func testChunksOfCountCount() {
@@ -14,32 +14,23 @@ import XCTest
final class CompactedTests: XCTestCase {
let tests: [[Int?]] =
[nil, nil, nil, 0, 1, 2]
.uniquePermutations(ofCount: 0...)
.map(Array.init)
let tests: [[Int?]] = [nil, nil, nil, 0, 1, 2].uniquePermutations(ofCount: 0...).map(Array.init)
func testCompactedCompacted() {
for collection in self.tests {
let seq = AnySequence(collection)
XCTAssertEqualSequences(
seq.compactMap({ $0 }), seq.compacted())
XCTAssertEqualSequences(
collection.compactMap({ $0 }), collection.compacted())
XCTAssertEqualSequences(seq.compactMap({ $0 }), seq.compacted())
XCTAssertEqualSequences(collection.compactMap({ $0 }), collection.compacted())
}
}
func testCompactedBidirectionalCollection() {
for array in self.tests {
XCTAssertEqualSequences(
array.compactMap({ $0 }).reversed(),
array.compacted().reversed())
XCTAssertEqualSequences(array.compactMap({ $0 }).reversed(), array.compacted().reversed())
}
}
func testCollectionTraversals() {
for array in self.tests {
validateIndexTraversals(array.compacted())
}
for array in self.tests { validateIndexTraversals(array.compacted()) }
}
}
+5 -15
View File
@@ -16,9 +16,7 @@ final class CycleTests: XCTestCase {
func testCycle() {
let cycle = (1...4).cycled()
XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
cycle.prefix(20)
)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], cycle.prefix(20))
}
func testCycleClosedRangePrefix() {
@@ -31,15 +29,11 @@ final class CycleTests: XCTestCase {
XCTAssert(empty.isEmpty)
}
func testCycleLazy() {
XCTAssertLazySequence((1...4).lazy.cycled())
}
func testCycleLazy() { XCTAssertLazySequence((1...4).lazy.cycled()) }
func testRepeated() {
let repeats = (1...4).cycled(times: 3)
XCTAssertEqualSequences(
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
repeats)
XCTAssertEqualSequences([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], repeats)
}
func testRepeatedClosedRange() {
@@ -57,9 +51,7 @@ final class CycleTests: XCTestCase {
XCTAssert(empty2.isEmpty)
}
func testRepeatedLazy() {
XCTAssertLazySequence((1...4).lazy.cycled(times: 3))
}
func testRepeatedLazy() { XCTAssertLazySequence((1...4).lazy.cycled(times: 3)) }
func testRepeatedIndexMethods() {
let cycle = (1..<5).cycled(times: 2)
@@ -73,9 +65,7 @@ final class CycleTests: XCTestCase {
nextIndex = cycle.index(nextIndex, offsetBy: 2, limitedBy: cycle.endIndex)!
XCTAssertEqual(cycle.distance(from: startIndex, to: nextIndex), 8)
let outOfBounds = cycle.index(
nextIndex, offsetBy: 1,
limitedBy: cycle.endIndex)
let outOfBounds = cycle.index(nextIndex, offsetBy: 1, limitedBy: cycle.endIndex)
XCTAssertNil(outOfBounds)
let previousIndex = cycle.index(before: nextIndex)
@@ -28,7 +28,5 @@ final class IndexedTests: XCTestCase {
XCTAssertEqual("I", s[indexOfI])
}
func testIndexedLazy() {
XCTAssertLazyCollection("ABCD".lazy.indexed())
}
func testIndexedLazy() { XCTAssertLazyCollection("ABCD".lazy.indexed()) }
}
+217 -432
View File
@@ -17,13 +17,7 @@ import XCTest
//===----------------------------------------------------------------------===//
final class LazySplitTests: XCTestCase {
func testEmpty() {
Validator(
subject: [],
separator: .element(0),
maxSplits: 1
).validate()
}
func testEmpty() { Validator(subject: [], separator: .element(0), maxSplits: 1).validate() }
// The following test names indicate the sequence being split, using the
// notation
@@ -41,54 +35,35 @@ final class LazySplitTests: XCTestCase {
// Length 1
//===--------------------------------------------------------------------===//
func testE() {
Validator(subject: [1], separator: .element(0), maxSplits: 0).validate()
}
func testE() { Validator(subject: [1], separator: .element(0), maxSplits: 0).validate() }
func testS() {
Validator(subject: [0], separator: .element(0), maxSplits: 0).validate()
}
func testS() { Validator(subject: [0], separator: .element(0), maxSplits: 0).validate() }
//===--------------------------------------------------------------------===//
// Length 2
//===--------------------------------------------------------------------===//
func testEE() {
Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate()
}
func testEE() { Validator(subject: [1, 1], separator: .element(0), maxSplits: 0).validate() }
func testSS() {
Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate()
}
func testSS() { Validator(subject: [0, 0], separator: .element(0), maxSplits: 1).validate() }
func testES() {
Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate()
}
func testES() { Validator(subject: [1, 0], separator: .element(0), maxSplits: 0).validate() }
func testSE() {
Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate()
}
func testSE() { Validator(subject: [0, 1], separator: .element(0), maxSplits: 0).validate() }
//===--------------------------------------------------------------------===//
// Length 3
//===--------------------------------------------------------------------===//
func testEEE() {
Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0)
.validate()
}
func testEEE() { Validator(subject: [1, 1, 1], separator: .element(0), maxSplits: 0).validate() }
func testSSS() {
Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1)
.validate()
}
func testSSS() { Validator(subject: [0, 0, 0], separator: .element(0), maxSplits: 1).validate() }
func testAllEES() {
let permutations = [[1, 1, 0], [1, 0, 1], [0, 1, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
}
}
@@ -96,8 +71,7 @@ final class LazySplitTests: XCTestCase {
let permutations = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
@@ -106,18 +80,14 @@ final class LazySplitTests: XCTestCase {
//===--------------------------------------------------------------------===//
func testEEEE() {
Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0)
.validate()
Validator(subject: [1, 1, 1, 1], separator: .element(0), maxSplits: 0).validate()
}
func testAllEEES() {
let permutations = [
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1],
]
let permutations = [[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 0)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 0).validate()
}
}
@@ -128,48 +98,41 @@ final class LazySplitTests: XCTestCase {
// All separators.
func testSSSS() {
Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: [0, 0, 0, 0], separator: .element(0), maxSplits: 1).validate()
}
// Equal numbers of elements and separators.
func testAllEESS() {
let permutations = [
[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1],
[0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
// More separators than elements.
func testAllEESSS() {
let permutations = [
[1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1],
[0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0],
[0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
[1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1], [0, 1, 1, 0, 0],
[0, 1, 0, 1, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
// More elements than separators.
func testAllEEESS() {
let permutations = [
[1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0],
[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1],
[0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
[1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 1], [1, 0, 1, 1, 0], [1, 0, 1, 0, 1],
[1, 0, 0, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
@@ -178,35 +141,28 @@ final class LazySplitTests: XCTestCase {
//===--------------------------------------------------------------------===//
func testAllESSS() {
let permutations = [
[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],
]
let permutations = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
func testAllEEEESSS() {
let permutations = [
[1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1], [1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0, 1],
[1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0],
[0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0, 1, 0], [1, 1, 1, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1, 0],
[1, 1, 0, 0, 1, 0, 1], [1, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 1, 1],
[1, 0, 0, 1, 1, 1, 0], [1, 0, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1],
[0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
@@ -219,143 +175,105 @@ final class LazySplitTests: XCTestCase {
// Equal numbers of separators and elements.
func testAllEEEESSSS() {
let permutations = [
[1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 1, 0, 0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, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 0, 1],
[0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
// More separators than elements.
func testAllEEESSSS() {
let permutations = [
[1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0],
[1, 1, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1],
[0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0],
[0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0],
[0, 0, 1, 1, 0, 0, 1], [0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1], [0, 1, 0, 1, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
// More elements than separators.
func testAllEEEEESSSS() {
let permutations = [
[1, 1, 1, 1, 1, 0, 0, 0, 0], [1,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 1, 0, 1, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1, 1], [0, 1, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 0, 1, 1, 1, 0, 1],
[0, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 0, 1, 1],
[0, 0, 0, 1, 1, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
@@ -367,53 +285,38 @@ final class LazySplitTests: XCTestCase {
// More separators than elements.
func testAllEEESSSSSS() {
let permutations = [
[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1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 1, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1],
]
for permutation in permutations {
Validator(subject: permutation, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: permutation, separator: .element(0), maxSplits: 1).validate()
}
}
@@ -424,11 +327,7 @@ final class LazySplitTests: XCTestCase {
// The motivating example from
// https://github.com/apple/swift-algorithms/issues/59.
func testSplitFilenameComponents() {
Validator(
subject: "archive.tar.gz",
separator: .element("."),
maxSplits: 1
).validate()
Validator(subject: "archive.tar.gz", separator: .element("."), maxSplits: 1).validate()
}
// Examples from documentation.
@@ -436,15 +335,12 @@ final class LazySplitTests: XCTestCase {
// Closure version.
let numbers = stride(from: 1, through: 16, by: 1)
Validator(
subject: Array(numbers),
separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }),
maxSplits: 1
subject: Array(numbers), separator: .closure({ $0 % 3 == 0 || $0 % 5 == 0 }), maxSplits: 1
).validate()
// Equatable element version.
let numbers2 = [1, 2, 0, 3, 4, 0, 0, 5]
Validator(subject: numbers2, separator: .element(0), maxSplits: 1)
.validate()
Validator(subject: numbers2, separator: .element(0), maxSplits: 1).validate()
}
func testCollectionDocExample() {
@@ -456,22 +352,17 @@ final class LazySplitTests: XCTestCase {
// above. Preserved to ensure we're not losing any test coverage.
func testVintagePatterns() {
let pattern1 = [1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern1, separator: .element(42), maxSplits: 2)
.validate()
Validator(subject: pattern1, separator: .element(42), maxSplits: 0)
.validate()
Validator(subject: pattern1, separator: .element(42), maxSplits: 2).validate()
Validator(subject: pattern1, separator: .element(42), maxSplits: 0).validate()
let pattern2 = [42, 1, 2, 42, 3, 4, 42, 5, 6, 42, 7]
Validator(subject: pattern2, separator: .element(42), maxSplits: 2)
.validate()
Validator(subject: pattern2, separator: .element(42), maxSplits: 2).validate()
let pattern3 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7]
Validator(subject: pattern3, separator: .element(42), maxSplits: 2)
.validate()
Validator(subject: pattern3, separator: .element(42), maxSplits: 2).validate()
let pattern4 = [1, 2, 42, 3, 4, 42, 42, 5, 6, 42, 7, 42, 42, 42]
Validator(subject: pattern4, separator: .element(42), maxSplits: 1)
.validate()
Validator(subject: pattern4, separator: .element(42), maxSplits: 1).validate()
}
//===--------------------------------------------------------------------===//
@@ -507,8 +398,7 @@ final class LazySplitTests: XCTestCase {
/// determine the element--on which to split.
/// - maxSplits: The value to pass for `maxSplits` during validation. The
/// default value is also validated.
fileprivate struct Validator<C: Collection>
where C.Element: Equatable, C.SubSequence: Equatable {
fileprivate struct Validator<C: Collection> where C.Element: Equatable, C.SubSequence: Equatable {
enum Separator {
case element(C.Element)
case closure((C.Element) -> Bool)
@@ -529,10 +419,8 @@ final class LazySplitTests: XCTestCase {
var description: String {
switch self {
case .provided(let value):
return "maxSplits: \(value)"
case .defaultValue:
return "maxSplits: default"
case .provided(let value): return "maxSplits: \(value)"
case .defaultValue: return "maxSplits: default"
}
}
}
@@ -543,159 +431,108 @@ final class LazySplitTests: XCTestCase {
var description: String {
switch self {
case .provided(let value):
return "omittingEmptySubsequences: \(value)"
case .defaultValue:
return "omittingEmptySubsequences: default"
case .provided(let value): return "omittingEmptySubsequences: \(value)"
case .defaultValue: return "omittingEmptySubsequences: default"
}
}
}
private func failureMessage<L: LazySequenceProtocol, S: Sequence>(
actual: L,
expected: S,
maxSplits: MaxSplits,
actual: L, expected: S, maxSplits: MaxSplits,
omittingEmptySubsequences: OmittingEmptySubsequences
) -> String {
"for \(Array(subject).debugDescription), \(maxSplits), \(omittingEmptySubsequences): \(Array(actual).debugDescription) != \(Array(expected).debugDescription)"
}
private func _validateAsSequence<T: Sequence>(_ s: T)
where T.Element == C.Element {
private func _validateAsSequence<T: Sequence>(_ s: T) where T.Element == C.Element {
// Default max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = s.split(separator: element).map { Array($0) }
let actual = s.lazy.split(separator: element)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
case let .closure(closure):
let expected = s.split(whereSeparator: closure).map { Array($0) }
let actual = s.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
}
// Provided max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
maxSplits: maxSplits
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
maxSplits: maxSplits
)
let expected = s.split(separator: element, maxSplits: maxSplits).map { Array($0) }
let actual = s.lazy.split(separator: element, maxSplits: maxSplits)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
case let .closure(closure):
let expected = s.split(
maxSplits: maxSplits,
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
let expected = s.split(maxSplits: maxSplits, whereSeparator: closure).map { Array($0) }
let actual = s.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
}
// Default max splits, including empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
omittingEmptySubsequences: false
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
let expected = s.split(separator: element, omittingEmptySubsequences: false).map {
Array($0)
}
let actual = s.lazy.split(separator: element, omittingEmptySubsequences: false)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
case let .closure(closure):
let expected = s.split(
omittingEmptySubsequences: false,
whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
let expected = s.split(omittingEmptySubsequences: false, whereSeparator: closure).map {
Array($0)
}
let actual = s.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
}
// Provided max splits, including empty sequences
switch separator {
case let .element(element):
let expected = s.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false
).map { Array($0) }
let actual = s.lazy.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
case let .closure(closure):
let expected = s.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure
).map { Array($0) }
let actual = s.lazy.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
}
}
@@ -706,134 +543,82 @@ final class LazySplitTests: XCTestCase {
let expected = c.split(separator: element)
let actual = c.lazy.split(separator: element)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
case let .closure(closure):
let expected = c.split(whereSeparator: closure)
let actual = c.lazy.split(whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
}
// Provided max splits, omitting empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
maxSplits: maxSplits
)
let actual = c.lazy.split(
separator: element,
maxSplits: maxSplits
)
let expected = c.split(separator: element, maxSplits: maxSplits)
let actual = c.lazy.split(separator: element, maxSplits: maxSplits)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
case let .closure(closure):
let expected = c.split(
maxSplits: maxSplits,
whereSeparator: closure
)
let actual = c.lazy.split(
maxSplits: maxSplits,
whereSeparator: closure
)
let expected = c.split(maxSplits: maxSplits, whereSeparator: closure)
let actual = c.lazy.split(maxSplits: maxSplits, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .defaultValue)
)
omittingEmptySubsequences: .defaultValue))
}
// Default max splits, including empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
omittingEmptySubsequences: false
)
let actual = c.lazy.split(
separator: element,
omittingEmptySubsequences: false
)
let expected = c.split(separator: element, omittingEmptySubsequences: false)
let actual = c.lazy.split(separator: element, omittingEmptySubsequences: false)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
case let .closure(closure):
let expected = c.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
let actual = c.lazy.split(
omittingEmptySubsequences: false,
whereSeparator: closure
)
let expected = c.split(omittingEmptySubsequences: false, whereSeparator: closure)
let actual = c.lazy.split(omittingEmptySubsequences: false, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .defaultValue,
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
}
// Provided max splits, including empty sequences
switch separator {
case let .element(element):
let expected = c.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
let actual = c.lazy.split(
separator: element,
maxSplits: maxSplits,
omittingEmptySubsequences: false
)
separator: element, maxSplits: maxSplits, omittingEmptySubsequences: false)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
case let .closure(closure):
let expected = c.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
let actual = c.lazy.split(
maxSplits: maxSplits,
omittingEmptySubsequences: false,
whereSeparator: closure
)
maxSplits: maxSplits, omittingEmptySubsequences: false, whereSeparator: closure)
XCTAssertEqualSequences(
expected,
actual,
expected, actual,
failureMessage(
actual: actual, expected: expected, maxSplits: .provided(maxSplits),
omittingEmptySubsequences: .provided(false))
)
omittingEmptySubsequences: .provided(false)))
}
}
}
+17 -45
View File
@@ -20,9 +20,8 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqualSequences(min, 0..<5)
// Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100)
.enumerated()
.max(count: 5, sortedBy: { $0.element < $1.element })
let maxZeroes = Array(repeating: 0, count: 100).enumerated().max(
count: 5, sortedBy: { $0.element < $1.element })
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
}
@@ -33,9 +32,8 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqualSequences(max, 10..<15)
// Stability with all equal values
let maxZeroes = Array(repeating: 0, count: 100)
.enumerated()
.max(count: 5, sortedBy: { $0.element < $1.element })
let maxZeroes = Array(repeating: 0, count: 100).enumerated().max(
count: 5, sortedBy: { $0.element < $1.element })
XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100)
}
@@ -84,21 +82,13 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound])
XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5))
XCTAssertEqualSequences(
input.min(count: 5, sortedBy: >),
range.suffix(5).reversed())
XCTAssertEqualSequences(input.min(count: 5, sortedBy: >), range.suffix(5).reversed())
XCTAssertEqualSequences(
input.min(count: 500, sortedBy: <),
range.prefix(500))
XCTAssertEqualSequences(
input.min(count: 500, sortedBy: >),
range.suffix(500).reversed())
XCTAssertEqualSequences(input.min(count: 500, sortedBy: <), range.prefix(500))
XCTAssertEqualSequences(input.min(count: 500, sortedBy: >), range.suffix(500).reversed())
XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range)
XCTAssertEqualSequences(
input.min(count: 1000, sortedBy: >),
range.reversed())
XCTAssertEqualSequences(input.min(count: 1000, sortedBy: >), range.reversed())
}
func testMaxCountWithHugeInput() {
@@ -112,21 +102,13 @@ final class SortedPrefixTests: XCTestCase {
XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound])
XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5))
XCTAssertEqualSequences(
input.max(count: 5, sortedBy: >),
range.prefix(5).reversed())
XCTAssertEqualSequences(input.max(count: 5, sortedBy: >), range.prefix(5).reversed())
XCTAssertEqualSequences(
input.max(count: 500, sortedBy: <),
range.suffix(500))
XCTAssertEqualSequences(
input.max(count: 500, sortedBy: >),
range.prefix(500).reversed())
XCTAssertEqualSequences(input.max(count: 500, sortedBy: <), range.suffix(500))
XCTAssertEqualSequences(input.max(count: 500, sortedBy: >), range.prefix(500).reversed())
XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range)
XCTAssertEqualSequences(
input.max(count: 1000, sortedBy: >),
range.reversed())
XCTAssertEqualSequences(input.max(count: 1000, sortedBy: >), range.reversed())
}
func testStability() {
@@ -159,28 +141,18 @@ final class SortedPrefixTests: XCTestCase {
assertStability([1, 1, 1, 0, 0, 0], withCount: 5)
}
func assertStability(
_ actual: [Int],
withCount count: Int
) {
func stableOrder(
a: (offset: Int, element: Int),
b: (offset: Int, element: Int)
) -> Bool {
a.element == b.element
? a.offset < b.offset
: a.element < b.element
func assertStability(_ actual: [Int], withCount count: Int) {
func stableOrder(a: (offset: Int, element: Int), b: (offset: Int, element: Int)) -> Bool {
a.element == b.element ? a.offset < b.offset : a.element < b.element
}
do {
let sorted = actual.enumerated()
.min(count: count) { $0.element < $1.element }
let sorted = actual.enumerated().min(count: count) { $0.element < $1.element }
XCTAssert(sorted.isSorted(by: stableOrder))
}
do {
let sorted = actual.enumerated()
.max(count: count) { $0.element < $1.element }
let sorted = actual.enumerated().max(count: count) { $0.element < $1.element }
XCTAssert(sorted.isSorted(by: stableOrder))
}
}
@@ -29,11 +29,9 @@ final class PermutationsTests: XCTestCase {
}
func ts<R: RangeExpression>(count: R) where R.Bound == Int {
let p = count.relative(to: 0 ..< .max)
.clamped(to: 0..<c.count + 1)
.flatMap {
c.permutations(ofCount: $0)
}
let p = count.relative(to: 0 ..< .max).clamped(to: 0..<c.count + 1).flatMap {
c.permutations(ofCount: $0)
}
let p2 = c.permutations(ofCount: count)
@@ -102,9 +100,7 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers)
}
func testPermutationsLazy() {
XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2))
}
func testPermutationsLazy() { XCTAssertLazySequence("ABCD".lazy.permutations(ofCount: 2)) }
func testDocumentationExample1() {
// From Guides/Permutations.md
@@ -112,14 +108,7 @@ final class PermutationsTests: XCTestCase {
let permutations = numbers.permutations()
XCTAssertEqualSequences(
permutations,
[
[10, 20, 30],
[10, 30, 20],
[20, 10, 30],
[20, 30, 10],
[30, 10, 20],
[30, 20, 10],
])
[[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]])
}
func testDocumentationExample2() {
@@ -127,15 +116,7 @@ final class PermutationsTests: XCTestCase {
let numbers = [10, 20, 30]
let permutations = numbers.permutations(ofCount: 2)
XCTAssertEqualSequences(
permutations,
[
[10, 20],
[10, 30],
[20, 10],
[20, 30],
[30, 10],
[30, 20],
])
permutations, [[10, 20], [10, 30], [20, 10], [20, 30], [30, 10], [30, 20]])
}
func testDocumentationExample3() {
@@ -144,14 +125,7 @@ final class PermutationsTests: XCTestCase {
let permutations = numbers2.permutations()
XCTAssertEqualSequences(
permutations,
[
[20, 10, 10],
[20, 10, 10],
[10, 20, 10],
[10, 10, 20],
[10, 20, 10],
[10, 10, 20],
])
[[20, 10, 10], [20, 10, 10], [10, 20, 10], [10, 10, 20], [10, 20, 10], [10, 10, 20]])
}
func testDocumentationExample4() {
@@ -161,22 +135,8 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqualSequences(
permutations,
[
[],
[10],
[20],
[30],
[10, 20],
[10, 30],
[20, 10],
[20, 30],
[30, 10],
[30, 20],
[10, 20, 30],
[10, 30, 20],
[20, 10, 30],
[20, 30, 10],
[30, 10, 20],
[30, 20, 10],
[], [10], [20], [30], [10, 20], [10, 30], [20, 10], [20, 30], [30, 10], [30, 20],
[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10],
])
}
@@ -187,12 +147,8 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqualSequences(
permutations,
[
["Alex", "Celeste"],
["Alex", "Davide"],
["Celeste", "Alex"],
["Celeste", "Davide"],
["Davide", "Alex"],
["Davide", "Celeste"],
["Alex", "Celeste"], ["Alex", "Davide"], ["Celeste", "Alex"], ["Celeste", "Davide"],
["Davide", "Alex"], ["Davide", "Celeste"],
])
}
@@ -203,15 +159,8 @@ final class PermutationsTests: XCTestCase {
XCTAssertEqualSequences(
permutations,
[
["Alex"],
["Celeste"],
["Davide"],
["Alex", "Celeste"],
["Alex", "Davide"],
["Celeste", "Alex"],
["Celeste", "Davide"],
["Davide", "Alex"],
["Davide", "Celeste"],
["Alex"], ["Celeste"], ["Davide"], ["Alex", "Celeste"], ["Alex", "Davide"],
["Celeste", "Alex"], ["Celeste", "Davide"], ["Davide", "Alex"], ["Davide", "Celeste"],
])
}
}
+5 -13
View File
@@ -16,9 +16,7 @@ import XCTest
final class ProductTests: XCTestCase {
func testProduct() {
XCTAssertEqualSequences(
[(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")],
product(1...2, "AB"),
by: ==)
[(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")], product(1...2, "AB"), by: ==)
XCTAssertEqualSequences(product(1...10, ""), [], by: ==)
XCTAssertEqualSequences(product("", 1...10), [], by: ==)
@@ -26,9 +24,8 @@ final class ProductTests: XCTestCase {
func testProductReversed() {
XCTAssertEqualSequences(
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")],
product(1...2, "AB").reversed(),
by: ==)
[(2, "B" as Character), (2, "A"), (1, "B"), (1, "A")], product(1...2, "AB").reversed(), by: ==
)
XCTAssertEqualSequences(product(1...10, "").reversed(), [], by: ==)
XCTAssertEqualSequences(product("", 1...10).reversed(), [], by: ==)
@@ -41,15 +38,10 @@ final class ProductTests: XCTestCase {
func testProductIndexTraversals() {
validateIndexTraversals(
product([1, 2, 3, 4], "abc"),
product([1, 2, 3, 4], ""),
product([], "abc"),
product([], ""),
product([1, 2, 3, 4], "abc"), product([1, 2, 3, 4], ""), product([], "abc"), product([], ""),
indices: { product in
product.base1.indices.flatMap { i1 in
product.base2.indices.map { i2 in
.init(i1: i1, i2: i2)
}
product.base2.indices.map { i2 in .init(i1: i1, i2: i2) }
} + [.init(i1: product.base1.endIndex, i2: product.base2.startIndex)]
})
}
@@ -14,18 +14,12 @@ import XCTest
@testable import Algorithms
func validateRandomSamples<S: Sequence>(
_ samples: [Int: Int],
elements: S,
expectedValue: Int,
file: StaticString = #file, line: UInt = #line
_ samples: [Int: Int], elements: S, expectedValue: Int, file: StaticString = #file,
line: UInt = #line
) where S.Element == Int {
let expectedRange = ((expectedValue / 3) * 2)...((expectedValue / 3) * 4)
XCTAssertEqualSequences(
samples.keys.sorted(), elements,
file: file, line: line)
for v in samples.values {
XCTAssert(expectedRange.contains(v), file: file, line: line)
}
XCTAssertEqualSequences(samples.keys.sorted(), elements, file: file, line: line)
for v in samples.values { XCTAssert(expectedRange.contains(v), file: file, line: line) }
}
private let n = 100
@@ -39,27 +33,21 @@ final class RandomSampleTests: XCTestCase {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
let sample = c.randomStableSample(count: k)
XCTAssert(sample.isSorted())
for x in sample {
result[x, default: 0] += 1
}
for x in sample { result[x, default: 0] += 1 }
}
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
}
func testRandomSampleCollection() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in c.randomSample(count: k) {
result[x, default: 0] += 1
}
for x in c.randomSample(count: k) { result[x, default: 0] += 1 }
}
validateRandomSamples(samples, elements: c, expectedValue: (k * iterations) / n)
}
func testRandomSampleSequence() {
let samples: [Int: Int] = (0..<iterations).reduce(into: [:]) { result, _ in
for x in s.randomSample(count: k) {
result[x, default: 0] += 1
}
for x in s.randomSample(count: k) { result[x, default: 0] += 1 }
}
validateRandomSamples(samples, elements: s, expectedValue: (k * iterations) / n)
}
@@ -99,9 +87,7 @@ final class RandomSampleTests: XCTestCase {
}
func testRandomSampleRandomEdgeCasesInternal() {
struct ZeroGenerator: RandomNumberGenerator {
mutating func next() -> UInt64 { 0 }
}
struct ZeroGenerator: RandomNumberGenerator { mutating func next() -> UInt64 { 0 } }
var zero = ZeroGenerator()
_ = nextOffset(w: 1, using: &zero) // must not crash
@@ -109,9 +95,7 @@ final class RandomSampleTests: XCTestCase {
private var forward: SplitMix64
private var count: Int = 0
init(seed: UInt64) {
forward = SplitMix64(seed: seed)
}
init(seed: UInt64) { forward = SplitMix64(seed: seed) }
mutating func next() -> UInt64 {
defer { count &+= 1 }
+7 -20
View File
@@ -89,36 +89,23 @@ final class StridingTests: XCTestCase {
func testIndexTraversals() {
let empty = [Int]()
validateIndexTraversals(
empty.striding(by: 1),
empty.striding(by: 2)
)
validateIndexTraversals(empty.striding(by: 1), empty.striding(by: 2))
let zero_to_one_hundered_range = 0...100
validateIndexTraversals(
zero_to_one_hundered_range.striding(by: 10),
zero_to_one_hundered_range.striding(by: 11),
zero_to_one_hundered_range.striding(by: 101)
)
zero_to_one_hundered_range.striding(by: 10), zero_to_one_hundered_range.striding(by: 11),
zero_to_one_hundered_range.striding(by: 101))
let zero_to_one_hundered_array = Array(zero_to_one_hundered_range)
validateIndexTraversals(
zero_to_one_hundered_array.striding(by: 10),
zero_to_one_hundered_array.striding(by: 11),
zero_to_one_hundered_array.striding(by: 101)
)
zero_to_one_hundered_array.striding(by: 10), zero_to_one_hundered_array.striding(by: 11),
zero_to_one_hundered_array.striding(by: 101))
let string = "swift rocks".map(String.init)
validateIndexTraversals(
string.striding(by: 1),
string.striding(by: 2),
string.striding(by: 10)
)
validateIndexTraversals(string.striding(by: 1), string.striding(by: 2), string.striding(by: 10))
}
func testOffsetBy() {
let a = (0...100).striding(by: 22)
let b = [0, 22, 44, 66, 88]
for i in 0..<a.count {
XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i])
}
for i in 0..<a.count { XCTAssertEqual(a[a.index(a.startIndex, offsetBy: i)], b[i]) }
}
func testOffsetByEndIndex() {
+36 -82
View File
@@ -17,11 +17,7 @@ extension Sequence {
}
}
extension Sequence where Element: Comparable {
func isSorted() -> Bool {
isSorted(by: <)
}
}
extension Sequence where Element: Comparable { func isSorted() -> Bool { isSorted(by: <) } }
extension Numeric {
func factorial() -> Self {
@@ -33,9 +29,7 @@ extension Numeric {
struct SplitMix64: RandomNumberGenerator {
private var state: UInt64
init(seed: UInt64) {
self.state = seed
}
init(seed: UInt64) { self.state = seed }
mutating func next() -> UInt64 {
self.state &+= 0x9e37_79b9_7f4a_7c15
@@ -47,9 +41,7 @@ struct SplitMix64: RandomNumberGenerator {
}
// An eraser helper to any mutable collection
struct AnyMutableCollection<Base> where Base: MutableCollection {
var base: Base
}
struct AnyMutableCollection<Base> where Base: MutableCollection { var base: Base }
extension AnyMutableCollection: MutableCollection {
typealias Index = Base.Index
@@ -58,9 +50,7 @@ extension AnyMutableCollection: MutableCollection {
var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex }
func index(after i: Index) -> Index {
return base.index(after: i)
}
func index(after i: Index) -> Index { return base.index(after: i) }
subscript(position: Base.Index) -> Base.Element {
_read { yield base[position] }
@@ -75,20 +65,16 @@ extension MutableCollection {
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
_ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
try XCTAssertEqualSequences(
expression1(), expression2(), by: ==,
message(), file: file, line: line)
expression1(), expression2(), by: ==, message(), file: file, line: line)
}
// Two sequences contains exactly the same element but not necessarily in the same order.
func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
_ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element: Equatable, S1.Element == S2.Element {
var s1 = Array(try expression1())
@@ -103,28 +89,22 @@ func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
XCTAssertTrue(
missing.isEmpty, "first sequence missing '\(missing)' elements from second sequence",
file: file, line: line
)
file: file, line: line)
XCTAssertTrue(
s1.isEmpty, "first sequence contains \(s1) missing from second sequence",
file: file, line: line
s1.isEmpty, "first sequence contains \(s1) missing from second sequence", file: file, line: line
)
}
func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
_ expression1: @autoclosure () throws -> S1,
_ expression2: @autoclosure () throws -> S2,
by areEquivalent: (S1.Element, S1.Element) -> Bool,
_ message: @autoclosure () -> String = "",
_ expression1: @autoclosure () throws -> S1, _ expression2: @autoclosure () throws -> S2,
by areEquivalent: (S1.Element, S1.Element) -> Bool, _ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) rethrows where S1.Element == S2.Element {
func fail(_ reason: String) {
let message = message()
XCTFail(
message.isEmpty ? reason : "\(message) - \(reason)",
file: file, line: line)
XCTFail(message.isEmpty ? reason : "\(message) - \(reason)", file: file, line: line)
}
var iter1 = try expression1().makeIterator()
@@ -139,10 +119,8 @@ func XCTAssertEqualSequences<S1: Sequence, S2: Sequence>(
fail(
"element \(e1) on first sequence does not match element \(e2) on second sequence at position \(idx)"
)
case (_?, nil):
fail("second sequence shorter than first")
case (nil, _?):
fail("first sequence shorter than second")
case (_?, nil): fail("second sequence shorter than first")
case (nil, _?): fail("first sequence shorter than second")
case (nil, nil): break
}
return
@@ -154,10 +132,8 @@ func XCTAssertLazyCollection<S: LazyCollectionProtocol>(_: S) {}
/// Asserts two collections are equal by using their indices to access elements.
func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
_ expression1: @autoclosure () throws -> C1,
_ expression2: @autoclosure () throws -> C2,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
_ expression1: @autoclosure () throws -> C1, _ expression2: @autoclosure () throws -> C2,
_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line
) rethrows where C1.Element: Equatable, C1.Element == C2.Element {
let c1 = try expression1()
let c2 = try expression2()
@@ -187,30 +163,21 @@ func XCTAssertEqualCollections<C1: Collection, C2: Collection>(
/// - Complexity: O(*n*^3) for each collection, where *n* is the length of the
/// collection.
func validateIndexTraversals<C>(
_ collections: C...,
indices: ((C) -> [C.Index])? = nil,
file: StaticString = #file, line: UInt = #line
_ collections: C..., indices: ((C) -> [C.Index])? = nil, file: StaticString = #file,
line: UInt = #line
) where C: BidirectionalCollection {
for c in collections {
let indicesIncludingEnd = indices?(c) ?? (c.indices + [c.endIndex])
let count = indicesIncludingEnd.count - 1
XCTAssertEqual(c.count, count, "Count mismatch", file: file, line: line)
XCTAssertEqual(c.isEmpty, count == 0, "Emptiness mismatch", file: file, line: line)
XCTAssertEqual(
c.count, count,
"Count mismatch",
c.startIndex, indicesIncludingEnd.first, "`startIndex` does not equal the first index",
file: file, line: line)
XCTAssertEqual(
c.isEmpty, count == 0,
"Emptiness mismatch",
file: file, line: line)
XCTAssertEqual(
c.startIndex, indicesIncludingEnd.first,
"`startIndex` does not equal the first index",
file: file, line: line)
XCTAssertEqual(
c.endIndex, indicesIncludingEnd.last,
"`endIndex` does not equal the last index",
file: file, line: line)
c.endIndex, indicesIncludingEnd.last, "`endIndex` does not equal the last index", file: file,
line: line)
// `index(after:)`
do {
@@ -223,8 +190,7 @@ func validateIndexTraversals<C>(
"""
`startIndex` incremented \(offset) times does not equal index at \
offset \(offset)
""",
file: file, line: line)
""", file: file, line: line)
}
}
@@ -239,8 +205,7 @@ func validateIndexTraversals<C>(
"""
`endIndex` decremented \(count - offset) times does not equal index \
at offset \(offset)
""",
file: file, line: line)
""", file: file, line: line)
}
}
@@ -248,33 +213,26 @@ func validateIndexTraversals<C>(
XCTAssertEqual(c.indices.count, count)
for (offset, index) in c.indices.enumerated() {
XCTAssertEqual(
index, indicesIncludingEnd[offset],
"Index mismatch at offset \(offset) in `indices`",
index, indicesIncludingEnd[offset], "Index mismatch at offset \(offset) in `indices`",
file: file, line: line)
}
// index comparison
for (offsetA, a) in indicesIncludingEnd.enumerated() {
XCTAssertEqual(
a, a,
"Index at offset \(offsetA) does not equal itself",
file: file, line: line)
a, a, "Index at offset \(offsetA) does not equal itself", file: file, line: line)
XCTAssertFalse(
a < a,
"Index at offset \(offsetA) is less than itself",
file: file, line: line)
a < a, "Index at offset \(offsetA) is less than itself", file: file, line: line)
for (offsetB, b) in indicesIncludingEnd[..<offsetA].enumerated() {
XCTAssertNotEqual(
a, b,
"Index at offset \(offsetA) equals index at offset \(offsetB)",
file: file, line: line)
a, b, "Index at offset \(offsetA) equals index at offset \(offsetB)", file: file,
line: line)
XCTAssertLessThan(
b, a,
"""
Index at offset \(offsetB) is not less than index at offset \(offsetA)
""",
file: file, line: line)
""", file: file, line: line)
}
}
@@ -288,15 +246,13 @@ func validateIndexTraversals<C>(
"""
Index at offset \(startOffset) offset by \(distance) does not equal \
index at offset \(endOffset)
""",
file: file, line: line)
""", file: file, line: line)
XCTAssertEqual(
c.distance(from: start, to: end), distance,
"""
Distance from index at offset \(startOffset) to index at offset \
\(endOffset) does not equal \(distance)
""",
file: file, line: line)
""", file: file, line: line)
}
}
@@ -318,8 +274,7 @@ func validateIndexTraversals<C>(
"""
Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal `nil`
""",
file: file, line: line)
""", file: file, line: line)
} else {
XCTAssertEqual(
end, indicesIncludingEnd[targetOffset],
@@ -327,8 +282,7 @@ func validateIndexTraversals<C>(
Index at offset \(startOffset) offset by \(distance) limited \
by index at offset \(limitOffset) does not equal index at \
offset \(targetOffset)
""",
file: file, line: line)
""", file: file, line: line)
}
}
}
+1 -3
View File
@@ -21,9 +21,7 @@ final class TrimTests: XCTestCase {
func testNoMatch() {
// No match (nothing trimmed).
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming {
$0.isMultiple(of: 2)
}
let results_nomatch = [1, 3, 5, 7, 9, 11, 13, 15].trimming { $0.isMultiple(of: 2) }
XCTAssertEqual(results_nomatch, [1, 3, 5, 7, 9, 11, 13, 15])
}
@@ -24,30 +24,22 @@ final class UniquePermutationsTests: XCTestCase {
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]],
// 3
[
[1, 1, 1], [1, 1, 2], [1, 1, 3],
[1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2],
[2, 1, 1], [2, 1, 3], [2, 3, 1],
[3, 1, 1], [3, 1, 2], [3, 2, 1],
[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 3], [1, 3, 1], [1, 3, 2], [2, 1, 1],
[2, 1, 3], [2, 3, 1], [3, 1, 1], [3, 1, 2], [3, 2, 1],
],
// 4
[
[1, 1, 1, 2], [1, 1, 1, 3],
[1, 1, 2, 1], [1, 1, 2, 3],
[1, 1, 3, 1], [1, 1, 3, 2],
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 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],
[3, 1, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1],
[1, 1, 1, 2], [1, 1, 1, 3], [1, 1, 2, 1], [1, 1, 2, 3], [1, 1, 3, 1], [1, 1, 3, 2],
[1, 2, 1, 1], [1, 2, 1, 3], [1, 2, 3, 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], [3, 1, 1, 1], [3, 1, 1, 2],
[3, 1, 2, 1], [3, 2, 1, 1],
],
// 5
[
[1, 1, 1, 2, 3], [1, 1, 1, 3, 2],
[1, 1, 2, 1, 3], [1, 1, 2, 3, 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, 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],
[3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1],
[1, 1, 1, 2, 3], [1, 1, 1, 3, 2], [1, 1, 2, 1, 3], [1, 1, 2, 3, 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, 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], [3, 1, 1, 1, 2], [3, 1, 1, 2, 1], [3, 1, 2, 1, 1], [3, 2, 1, 1, 1],
],
]
}
@@ -57,20 +49,15 @@ extension UniquePermutationsTests {
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 0), [[]])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1), [])
XCTAssertEqualSequences(
([] as [Int]).uniquePermutations(ofCount: 1...3), [])
XCTAssertEqualSequences(([] as [Int]).uniquePermutations(ofCount: 1...3), [])
}
func testSingleCounts() {
for (k, expectation) in Self.numbersPermutations.enumerated() {
XCTAssertEqualSequences(
expectation,
Self.numbers.uniquePermutations(ofCount: k))
XCTAssertEqualSequences(expectation, Self.numbers.uniquePermutations(ofCount: k))
}
XCTAssertEqualSequences(
Self.numbersPermutations[5],
Self.numbers.uniquePermutations())
XCTAssertEqualSequences(Self.numbersPermutations[5], Self.numbers.uniquePermutations())
}
func testRanges() {
@@ -98,17 +85,11 @@ extension UniquePermutationsTests {
private final class IntBox: Hashable {
var value: Int
init(_ value: Int) {
self.value = value
}
init(_ value: Int) { self.value = value }
static func == (lhs: IntBox, rhs: IntBox) -> Bool {
lhs.value == rhs.value
}
static func == (lhs: IntBox, rhs: IntBox) -> Bool { lhs.value == rhs.value }
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
func hash(into hasher: inout Hasher) { hasher.combine(value) }
}
func testFirstUnique() {
@@ -122,7 +103,5 @@ extension UniquePermutationsTests {
}
}
func testLaziness() {
XCTAssertLazySequence("ABCD".lazy.uniquePermutations())
}
func testLaziness() { XCTAssertLazySequence("ABCD".lazy.uniquePermutations()) }
}
+9 -19
View File
@@ -50,9 +50,7 @@ final class windowsTests: XCTestCase {
XCTAssertEqual(a.count, 3)
XCTAssertEqual(a.map { $0.reduce(0, +) }, [1, 1, 1])
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map {
$0.reduce(0, +)
}.reduce(0, +)
let a2 = [0, 1, 2, 3, 4, 5, 6].windows(ofCount: 3).map { $0.reduce(0, +) }.reduce(0, +)
XCTAssertEqual(a2, 3 + 6 + 9 + 12 + 15)
}
@@ -89,24 +87,16 @@ final class windowsTests: XCTestCase {
func testWindowsIndexTraversals() {
validateIndexTraversals(
"".windows(ofCount: 1),
"a".windows(ofCount: 1),
"ab".windows(ofCount: 1),
"abc".windows(ofCount: 1),
"".windows(ofCount: 3),
"a".windows(ofCount: 3),
"abc".windows(ofCount: 3),
"abcdefgh".windows(ofCount: 3),
indices: { windows in
let endIndex = windows.base.endIndex
"".windows(ofCount: 1), "a".windows(ofCount: 1), "ab".windows(ofCount: 1),
"abc".windows(ofCount: 1), "".windows(ofCount: 3), "a".windows(ofCount: 3),
"abc".windows(ofCount: 3), "abcdefgh".windows(ofCount: 3),
indices: { windows in let endIndex = windows.base.endIndex
let indices = windows.base.indices + [endIndex]
return zip(indices, indices.dropFirst(windows.size))
.map { .init(lowerBound: $0, upperBound: $1) }
+ [.init(lowerBound: endIndex, upperBound: endIndex)]
return zip(indices, indices.dropFirst(windows.size)).map {
.init(lowerBound: $0, upperBound: $1)
} + [.init(lowerBound: endIndex, upperBound: endIndex)]
})
}
func testWindowsLazy() {
XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2))
}
func testWindowsLazy() { XCTAssertLazyCollection([0, 1, 2, 3].lazy.windows(ofCount: 2)) }
}