Run swift-format with default settings

This commit is contained in:
Nate Cook committed 2021-04-15 15:04:29 -05:00
1 parent 04d91803a2
commit 993b950250
43 files changed
+1032 -886

No files matched your search

+25 -28
View File
@@ -11,12 +11,11 @@
/// A concatenation of two sequences with the same element type.
public struct Chain2<Base1: Sequence, Base2: Sequence>
where Base1.Element == Base2.Element
{
where Base1.Element == Base2.Element {
/// The first sequence in this chain.
@usableFromInline
internal let base1: Base1
/// The second sequence in this chain.
@usableFromInline
internal let base2: Base2
@@ -33,22 +32,22 @@ extension Chain2: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator1: Base1.Iterator
@usableFromInline
internal var iterator2: Base2.Iterator
@inlinable
internal init(_ concatenation: Chain2) {
iterator1 = concatenation.base1.makeIterator()
iterator2 = concatenation.base2.makeIterator()
}
@inlinable
public mutating func next() -> Base1.Element? {
return iterator1.next() ?? iterator2.next()
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
@@ -64,7 +63,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
// from the penultimate index of the first collection to the start of the
// second.
@usableFromInline
internal enum Representation : Equatable {
internal enum Representation: Equatable {
case first(Base1.Index)
case second(Base2.Index)
}
@@ -98,7 +97,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
}
}
}
/// Converts an index of `Base1` to the corresponding `Index` by mapping
/// `base1.endIndex` to `base2.startIndex`.
@inlinable
@@ -138,16 +137,16 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
return Index(second: base2.index(after: i))
}
}
@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)
}
@inlinable
public func index(
_ i: Index,
@@ -168,14 +167,14 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
@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") }
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") }
else { fatalError("Index is out of bounds") }
return index
}
@@ -185,12 +184,12 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
) -> 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:))
case let (.first(i), .second(limit)):
if let j = base1.index(i, offsetBy: distance, limitedBy: base1.endIndex) {
// the offset stays within the bounds of `base1`
@@ -201,11 +200,11 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
return base2.index(base2.startIndex, offsetBy: distance - d, limitedBy: limit)
.map(Index.init(second:))
}
case (.second, .first):
// impossible because `limit >= i`
fatalError()
case let (.second(i), .second(limit)):
return base2.index(i, offsetBy: distance, limitedBy: limit)
.map(Index.init(second:))
@@ -218,16 +217,16 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
) -> 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:))
case (.first, .second):
// impossible because `limit <= i`
fatalError()
case let (.second(i), .first(limit)):
if let j = base2.index(i, offsetBy: -distance, limitedBy: base2.startIndex) {
// the offset stays within the bounds of `base2`
@@ -245,7 +244,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
.map(Index.init(second:))
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
switch (start.position, end.position) {
@@ -264,8 +263,7 @@ extension Chain2: Collection where Base1: Collection, Base2: Collection {
}
extension Chain2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex")
@@ -281,7 +279,7 @@ extension Chain2: BidirectionalCollection
}
extension Chain2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
//===----------------------------------------------------------------------===//
// chain(_:_:)
@@ -326,8 +324,7 @@ 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
{
where Element == S.Element {
Chain2(base1: self, base2: other)
}
}
+80 -71
View File
@@ -15,19 +15,19 @@ public struct Chunked<Base: Collection, Subject> {
/// The collection that this instance provides a view onto.
@usableFromInline
internal let base: Base
/// The projection function.
@usableFromInline
internal let projection: (Base.Element) -> Subject
/// The predicate.
@usableFromInline
internal let belongInSameGroup: (Subject, Subject) -> Bool
/// The upper bound of the first chunk.
@usableFromInline
internal var firstUpperBound: Base.Index
@inlinable
internal init(
base: Base,
@@ -38,7 +38,7 @@ public struct Chunked<Base: Collection, Subject> {
self.projection = projection
self.belongInSameGroup = belongInSameGroup
self.firstUpperBound = base.startIndex
if !base.isEmpty {
firstUpperBound = endOfChunk(startingAt: base.startIndex)
}
@@ -51,19 +51,19 @@ extension Chunked: LazyCollectionProtocol {
/// The range corresponding to the chunk at this position.
@usableFromInline
internal var baseRange: Range<Base.Index>
@inlinable
internal init(_ baseRange: Range<Base.Index>) {
self.baseRange = baseRange
}
@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 {
// Only use the lower bound to test for ordering, as above.
@@ -79,17 +79,17 @@ extension Chunked: LazyCollectionProtocol {
return base[base.index(after: start)...]
.endOfPrefix(while: { belongInSameGroup(subject, projection($0)) })
}
@inlinable
public var startIndex: Index {
Index(base.startIndex..<firstUpperBound)
}
@inlinable
public var endIndex: Index {
Index(base.endIndex..<base.endIndex)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i != endIndex, "Can't advance past endIndex")
@@ -98,7 +98,7 @@ extension Chunked: LazyCollectionProtocol {
let end = endOfChunk(startingAt: upperBound)
return Index(upperBound..<end)
}
@inlinable
public subscript(position: Index) -> Base.SubSequence {
precondition(position != endIndex, "Can't subscript using endIndex")
@@ -109,14 +109,13 @@ extension Chunked: LazyCollectionProtocol {
extension Chunked.Index: Hashable where Base.Index: Hashable {}
extension Chunked: BidirectionalCollection
where Base: 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 {
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]
@@ -152,7 +151,7 @@ extension LazyCollectionProtocol {
projection: { $0 },
belongInSameGroup: belongInSameGroup)
}
/// Returns a lazy collection of subsequences of this collection, chunked by
/// grouping elements that project to the same value.
///
@@ -185,10 +184,10 @@ extension Collection {
) rethrows -> [SubSequence] {
guard !isEmpty else { return [] }
var result: [SubSequence] = []
var start = startIndex
var subject = try projection(self[start])
for (index, element) in indexed().dropFirst() {
let nextSubject = try projection(element)
if try !belongInSameGroup(subject, nextSubject) {
@@ -197,14 +196,14 @@ extension Collection {
subject = nextSubject
}
}
if start != endIndex {
result.append(self[start..<endIndex])
}
return result
}
/// Returns a collection of subsequences of this collection, chunked by
/// the given predicate.
///
@@ -242,15 +241,15 @@ extension Collection {
/// * `c.chunks(ofCount: 3).map(f)` maps eagerly and returns a new array
/// * `c.lazy.chunks(ofCount: 3).map(f)` maps lazily and returns a `LazyMapCollection`
public struct ChunkedByCount<Base: Collection> {
public typealias Element = Base.SubSequence
@usableFromInline
internal let base: Base
@usableFromInline
internal let chunkCount: Int
@usableFromInline
internal var startUpperBound: Base.Index
@@ -262,13 +261,14 @@ public struct ChunkedByCount<Base: Collection> {
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
self.startUpperBound =
_base.index(
_base.startIndex, offsetBy: _chunkCount,
limitedBy: _base.endIndex
) ?? _base.endIndex
}
}
@@ -276,7 +276,7 @@ extension ChunkedByCount: Collection {
public struct Index {
@usableFromInline
internal let baseRange: Range<Base.Index>
@inlinable
internal init(_baseRange: Range<Base.Index>) {
self.baseRange = _baseRange
@@ -292,35 +292,40 @@ extension ChunkedByCount: Collection {
public var endIndex: Index {
Index(_baseRange: base.endIndex..<base.endIndex)
}
/// - Complexity: O(1)
@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 {
precondition(i < endIndex, "Advancing past end index")
let baseIdx = base.index(
i.baseRange.upperBound, offsetBy: chunkCount,
limitedBy: base.endIndex
) ?? base.endIndex
let baseIdx =
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 {
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 {
public static func < (
lhs: ChunkedByCount.Index,
rhs: ChunkedByCount.Index
) -> Bool {
lhs.baseRange.lowerBound < rhs.baseRange.lowerBound
}
}
@@ -331,19 +336,20 @@ where Base: RandomAccessCollection {
@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
let remainder = base.count % chunkCount
if remainder != 0 {
offset = remainder
}
}
let baseIdx = base.index(
i.baseRange.lowerBound, offsetBy: -offset,
limitedBy: base.startIndex
) ?? base.startIndex
let baseIdx =
base.index(
i.baseRange.lowerBound, offsetBy: -offset,
limitedBy: base.startIndex
) ?? base.startIndex
return Index(_baseRange: baseIdx..<i.baseRange.lowerBound)
}
}
@@ -352,8 +358,9 @@ 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)
base.distance(
from: start.baseRange.lowerBound,
to: end.baseRange.lowerBound)
let (quotient, remainder) =
distance.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum()
@@ -365,14 +372,14 @@ extension ChunkedByCount {
base.count.quotientAndRemainder(dividingBy: chunkCount)
return quotient + remainder.signum()
}
@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)
@@ -387,16 +394,17 @@ extension ChunkedByCount {
@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)
let idx =
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
@@ -409,14 +417,14 @@ extension ChunkedByCount {
limit: limit, by: >
)
}
// Convenience to compute offset backward base distance.
@inlinable
internal func computeOffsetBackwardBaseDistance(
_ i: Index, _ distance: Int
) -> Int {
if i == endIndex {
let remainder = base.count%chunkCount
let remainder = base.count % chunkCount
// We have to take it into account when calculating offsets.
if remainder != 0 {
// Distance "minus" one(at this point distance is negative)
@@ -427,21 +435,21 @@ extension ChunkedByCount {
}
return distance * chunkCount
}
@inlinable
internal func offsetBackward(
_ i: Index, offsetBy distance: Int, limit: Index? = nil
) -> Index? {
assert(distance < 0)
let baseDistance =
computeOffsetBackwardBaseDistance(i, distance)
computeOffsetBackwardBaseDistance(i, distance)
return makeOffsetIndex(
from: i, baseBound: base.startIndex,
distance: distance, baseDistance: baseDistance,
limit: limit, by: <
)
}
// Helper to compute index(offsetBy:) index.
@inlinable
internal func makeOffsetIndex(
@@ -452,7 +460,7 @@ extension ChunkedByCount {
i.baseRange.lowerBound, offsetBy: baseDistance,
limitedBy: baseBound
)
if let limit = limit {
if baseIdx == nil {
// If we past the bounds while advancing forward and the
@@ -478,12 +486,13 @@ extension ChunkedByCount {
return nil
}
}
let baseStartIdx = baseIdx ?? baseBound
let baseEndIdx = base.index(
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
) ?? base.endIndex
let baseEndIdx =
base.index(
baseStartIdx, offsetBy: chunkCount, limitedBy: base.endIndex
) ?? base.endIndex
return Index(_baseRange: baseStartIdx..<baseEndIdx)
}
}
@@ -516,6 +525,6 @@ extension ChunkedByCount.Index: Hashable where Base.Index: Hashable {}
// Lazy conditional conformance.
extension ChunkedByCount: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension ChunkedByCount: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
+24 -23
View File
@@ -14,16 +14,16 @@ public struct Combinations<Base: Collection> {
/// The collection to iterate over for combinations.
@usableFromInline
internal let base: Base
@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>?
/// Initializes a `Combinations` for all combinations of `base` of size `k`.
/// - Parameters:
/// - base: The collection to iterate over for combinations.
@@ -32,7 +32,7 @@ public struct Combinations<Base: Collection> {
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:
@@ -47,20 +47,21 @@ public struct Combinations<Base: Collection> {
let baseCount = base.count
self.baseCount = baseCount
let upperBound = baseCount + 1
self.kRange = range.lowerBound < upperBound
? range.clamped(to: 0 ..< upperBound)
self.kRange =
range.lowerBound < upperBound
? range.clamped(to: 0..<upperBound)
: nil
}
/// The total number of combinations.
@inlinable
public var count: Int {
guard let k = self.kRange else { return 0 }
let n = baseCount
if k == 0 ..< (n + 1) {
if k == 0..<(n + 1) {
return 1 << n
}
func binomial(n: Int, k: Int) -> Int {
switch k {
case n, 0: return 1
@@ -69,7 +70,7 @@ public struct Combinations<Base: Collection> {
default: return n * binomial(n: n - 1, k: k - 1) / k
}
}
return k.map {
binomial(n: n, k: $0)
}.reduce(0, +)
@@ -81,30 +82,30 @@ extension Combinations: Sequence {
public struct Iterator: IteratorProtocol {
@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>
/// Whether or not iteration is finished (`kRange` is empty)
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@usableFromInline
internal var indexes: [Base.Index]
@inlinable
internal init(_ combinations: Combinations) {
self.base = combinations.base
self.kRange = combinations.kRange ?? 0..<0
self.indexes = Array(combinations.base.indices.prefix(kRange.lowerBound))
}
/// Advances the current indices to the next set of combinations. If
/// `indexes.count == 3` and `base.count == 5`, the indices advance like
/// this:
@@ -130,12 +131,12 @@ extension Combinations: Sequence {
func advanceKRange() {
if kRange.lowerBound < kRange.upperBound {
let advancedLowerBound = kRange.lowerBound + 1
kRange = advancedLowerBound ..< kRange.upperBound
kRange = advancedLowerBound..<kRange.upperBound
indexes.removeAll(keepingCapacity: true)
indexes.append(contentsOf: base.indices.prefix(kRange.lowerBound))
}
}
guard !indexes.isEmpty else {
// Initial state for combinations of 0 elements is an empty array with
// `finished == false`. Even though no indexes are involved, advancing
@@ -143,11 +144,11 @@ extension Combinations: Sequence {
advanceKRange()
return
}
let i = indexes.count - 1
base.formIndex(after: &indexes[i])
if indexes[i] != base.endIndex { return }
var j = i
while indexes[i] == base.endIndex {
j -= 1
@@ -156,7 +157,7 @@ extension Combinations: Sequence {
advanceKRange()
return
}
base.formIndex(after: &indexes[j])
for k in indexes.indices[(j + 1)...] {
indexes[k] = base.index(after: indexes[k - 1])
@@ -166,7 +167,7 @@ extension Combinations: Sequence {
}
}
}
@inlinable
public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil }
@@ -174,7 +175,7 @@ extension Combinations: Sequence {
return indexes.map { i in base[i] }
}
}
public func makeIterator() -> Iterator {
Iterator(self)
}
@@ -254,7 +255,7 @@ extension Collection {
) -> 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.
///
+32 -29
View File
@@ -11,11 +11,11 @@
/// A `Sequence` that iterates over every non-nil element from the original `Sequence`.
public struct CompactedSequence<Base: Sequence, Element>: Sequence
where Base.Element == Element? {
where Base.Element == Element? {
@usableFromInline
let base: Base
@inlinable
init(base: Base) {
self.base = base
@@ -24,12 +24,12 @@ public struct CompactedSequence<Base: Sequence, Element>: Sequence
public struct Iterator: IteratorProtocol {
@usableFromInline
var base: Base.Iterator
@inlinable
init(base: Base.Iterator) {
self.base = base
}
@inlinable
public mutating func next() -> Element? {
while let wrapped = base.next() {
@@ -66,81 +66,84 @@ extension Sequence {
/// Complexity: O(1)
@inlinable
public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped>
where Element == 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? {
where Base.Element == Element? {
@usableFromInline
let 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
@inlinable
init(base: Base.Index) {
self.base = base
}
}
public var startIndex: Index
@inlinable
public var endIndex: Index { Index(base: base.endIndex) }
@inlinable
public subscript(position: Index) -> Element {
base[position.base]!
}
@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 }
else { return endIndex }
return Index(base: idx)
}
}
extension CompactedCollection: BidirectionalCollection
where Base: BidirectionalCollection {
where Base: BidirectionalCollection {
@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 {
extension CompactedCollection.Index: Comparable {
@inlinable
public static func < (lhs: CompactedCollection.Index,
rhs: CompactedCollection.Index) -> Bool {
public static func < (
lhs: CompactedCollection.Index,
rhs: CompactedCollection.Index
) -> Bool {
lhs.base < rhs.base
}
}
extension CompactedCollection.Index: Hashable
where Base.Index: Hashable {}
where Base.Index: Hashable {}
extension Collection {
/// Returns a new `Collection` that iterates over every non-nil element
@@ -163,7 +166,7 @@ extension Collection {
/// original `Collection`.
@inlinable
public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped>
where Element == Unwrapped? {
where Element == Unwrapped? {
CompactedCollection(base: self)
}
}
@@ -173,9 +176,9 @@ extension Collection {
//===----------------------------------------------------------------------===//
extension CompactedSequence: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension CompactedCollection: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
+17 -15
View File
@@ -14,7 +14,7 @@ public struct Cycle<Base: Collection> {
/// The collection to repeat.
@usableFromInline
internal let base: Base
@inlinable
internal init(base: Base) {
self.base = base
@@ -26,29 +26,29 @@ extension Cycle: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline
internal var current: Base.Index
@inlinable
internal init(base: Base) {
self.base = base
self.current = base.startIndex
}
@inlinable
public mutating func next() -> Base.Element? {
guard !base.isEmpty else { return nil }
if current == base.endIndex {
current = base.startIndex
}
defer { base.formIndex(after: &current) }
return base[current]
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base: base)
@@ -57,7 +57,6 @@ extension Cycle: Sequence {
extension Cycle: LazySequenceProtocol where Base: LazySequenceProtocol {}
/// A collection wrapper that repeats the elements of a base collection for a
/// finite number of times.
public struct FiniteCycle<Base: Collection> {
@@ -72,7 +71,7 @@ public struct FiniteCycle<Base: Collection> {
}
extension FiniteCycle: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazyCollectionProtocol { }
where Base: LazyCollectionProtocol {}
extension FiniteCycle: Collection {
@@ -137,9 +136,12 @@ extension FiniteCycle: Collection {
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard let productIndex = product.index(i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex) else {
guard
let productIndex = product.index(
i.productIndex,
offsetBy: distance,
limitedBy: limit.productIndex)
else {
return nil
}
return Index(productIndex)
@@ -152,7 +154,7 @@ extension FiniteCycle: Collection {
}
extension FiniteCycle: BidirectionalCollection
where Base: BidirectionalCollection {
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
let productIndex = product.index(before: i.productIndex)
@@ -161,7 +163,7 @@ extension FiniteCycle: BidirectionalCollection
}
extension FiniteCycle: RandomAccessCollection
where Base: RandomAccessCollection {}
where Base: RandomAccessCollection {}
//===----------------------------------------------------------------------===//
// cycled()
@@ -197,7 +199,7 @@ extension Collection {
public func cycled() -> Cycle<Self> {
Cycle(base: self)
}
/// Returns a sequence that repeats the elements of this collection the
/// specified number of times.
///
+2 -2
View File
@@ -13,7 +13,7 @@
// firstNonNil(_:)
//===----------------------------------------------------------------------===//
public extension Sequence {
extension Sequence {
/// Returns the first non-`nil` result obtained from applying the given
/// transformation to the elements of the sequence.
///
@@ -30,7 +30,7 @@ public 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.
func firstNonNil<Result>(
public func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
+11 -9
View File
@@ -14,11 +14,11 @@
public struct Indexed<Base: Collection> {
/// The element type for an `Indexed` collection.
public typealias Element = (index: Base.Index, element: Base.Element)
/// The base collection.
@usableFromInline
internal let base: Base
@inlinable
internal init(base: Base) {
self.base = base
@@ -30,32 +30,34 @@ extension Indexed: Collection {
public var startIndex: Base.Index {
base.startIndex
}
@inlinable
public var endIndex: Base.Index {
base.endIndex
}
@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(_ 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? {
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 {
base.distance(from: start, to: end)
+16 -17
View File
@@ -14,10 +14,10 @@
public struct Intersperse<Base: Sequence> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let separator: Base.Element
@inlinable
internal init(base: Base, separator: Base.Element) {
self.base = base
@@ -30,19 +30,19 @@ extension Intersperse: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal let separator: Base.Element
@usableFromInline
internal var state = State.start
@inlinable
internal init(iterator: Base.Iterator, separator: Base.Element) {
self.iterator = iterator
self.separator = separator
}
@usableFromInline
enum State {
case start
@@ -85,7 +85,7 @@ extension Intersperse: Collection where Base: Collection {
case element(Base.Index)
case separator(next: Base.Index)
}
@usableFromInline
internal let representation: Representation
@@ -98,14 +98,14 @@ extension Intersperse: Collection where Base: Collection {
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)),
let (.element(li), .separator(next: 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
}
}
@inlinable
static func element(_ index: Base.Index) -> Self {
Self(representation: .element(index))
@@ -145,7 +145,7 @@ extension Intersperse: Collection where Base: Collection {
case .separator: return separator
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
switch (i.representation, distance.isMultiple(of: 2)) {
@@ -169,15 +169,14 @@ extension Intersperse: Collection where Base: Collection {
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)):
let (.separator(start), .separator(end)):
return 2 * base.distance(from: start, to: end)
}
}
}
extension Intersperse: BidirectionalCollection
where Base: BidirectionalCollection
{
where Base: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex, "Can't move before startIndex")
@@ -191,13 +190,13 @@ extension Intersperse: BidirectionalCollection
}
extension Intersperse: RandomAccessCollection
where Base: RandomAccessCollection {}
where Base: RandomAccessCollection {}
extension Intersperse: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension Intersperse: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
extension Sequence {
+21 -13
View File
@@ -17,20 +17,20 @@ extension Sequence {
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)
}
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) }
assert(insertionIndex != result.endIndex)
result.removeLast()
result.insert(e, at: insertionIndex)
@@ -38,7 +38,7 @@ extension Sequence {
return result
}
/// Implementation for max(count:areInIncreasingOrder:)
@inlinable
internal func _maxImplementation(
@@ -46,14 +46,14 @@ extension Sequence {
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)
}
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 }
@@ -71,10 +71,10 @@ extension Sequence {
}
result[insertionIndex - 1] = e
}
return result
}
/// Returns the smallest elements of this sequence, as sorted by the given
/// predicate.
///
@@ -107,7 +107,9 @@ extension Sequence {
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
precondition(
count >= 0,
"""
Cannot find a minimum with a negative count of elements!
"""
)
@@ -152,7 +154,9 @@ extension Sequence {
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
precondition(
count >= 0,
"""
Cannot find a maximum with a negative count of elements!
"""
)
@@ -253,7 +257,9 @@ extension Collection {
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
precondition(
count >= 0,
"""
Cannot find a minimum with a negative count of elements!
"""
)
@@ -271,7 +277,7 @@ extension Collection {
guard prefixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
}
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
@@ -307,7 +313,9 @@ extension Collection {
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
precondition(
count >= 0,
"""
Cannot find a maximum with a negative count of elements!
"""
)
+12 -12
View File
@@ -25,7 +25,7 @@ extension MutableCollection {
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
if n == 0 { return subrange.lowerBound }
if n == 1 {
@@ -33,8 +33,9 @@ extension MutableCollection {
? subrange.lowerBound
: subrange.upperBound
}
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
let h = n / 2
let i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition(
count: h,
subrange: subrange.lowerBound..<i,
@@ -45,7 +46,7 @@ extension MutableCollection {
by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i)
}
/// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
@@ -60,14 +61,14 @@ extension MutableCollection {
@inlinable
public mutating func stablePartition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
subrange: subrange,
by: belongsInSecondPartition)
}
/// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
@@ -79,7 +80,7 @@ extension MutableCollection {
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws-> Bool
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
@@ -104,8 +105,8 @@ extension MutableCollection {
// 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 }
else { return subrange.upperBound }
var j = index(after: i)
while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) {
@@ -114,7 +115,7 @@ extension MutableCollection {
}
formIndex(after: &j)
}
return i
}
}
@@ -189,7 +190,7 @@ extension Collection {
) rethrows -> Index {
var n = count
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
@@ -203,4 +204,3 @@ extension Collection {
return l
}
}
+52 -55
View File
@@ -14,8 +14,7 @@
//===----------------------------------------------------------------------===//
extension MutableCollection
where Self: BidirectionalCollection, Element: Comparable
{
where Self: BidirectionalCollection, Element: Comparable {
/// Permutes this collection's elements through all the lexical orderings.
///
/// Call `nextPermutation()` repeatedly starting with the collection in
@@ -34,26 +33,26 @@ extension MutableCollection
guard !isEmpty else { return false }
var i = index(before: endIndex)
if i == startIndex { return false }
let upperBound = upperBound ?? endIndex
while true {
let ip1 = i
formIndex(before: &i)
// Find the last ascending pair (ie. ..., a, b, ... where a < b)
if self[i] < self[ip1] {
// Find the last element greater than self[i]
// This is _always_ at most `ip1` due to if statement above
let j = lastIndex(where: { self[i] < $0 })!
// At this point we have something like this:
// 0, 1, 4, 3, 2
// ^ ^
// i j
swapAt(i, j)
self.reverse(subrange: ip1 ..< endIndex)
self.reverse(subrange: ip1..<endIndex)
// Only return if we've made a change within ..<upperBound region
if i < upperBound {
return true
@@ -62,7 +61,7 @@ extension MutableCollection
continue
}
}
if i == startIndex {
self.reverse()
return false
@@ -80,16 +79,16 @@ public struct Permutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@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>
/// Initializes a `Permutations` for all permutations of `base` of size `k`.
/// - Parameters:
/// - base: The collection to iterate over for permutations
@@ -99,13 +98,13 @@ public struct Permutations<Base: Collection> {
internal init(_ base: Base, k: Int? = nil) {
let kRange: ClosedRange<Int>?
if let countToChoose = k {
kRange = countToChoose ... countToChoose
kRange = countToChoose...countToChoose
} else {
kRange = nil
}
self.init(base, kRange: kRange)
}
/// Initializes a `Permutations` for all combinations of `base` of sizes
/// within a given range.
/// - Parameters:
@@ -120,11 +119,11 @@ public struct Permutations<Base: Collection> {
let baseCount = base.count
self.baseCount = baseCount
let upperBound = baseCount + 1
self.kRange = kRange?.relative(to: 0 ..< .max)
.clamped(to: 0 ..< upperBound) ??
baseCount ..< upperBound
self.kRange =
kRange?.relative(to: 0 ..< .max)
.clamped(to: 0..<upperBound) ?? baseCount..<upperBound
}
/// The total number of permutations.
@inlinable
public var count: Int {
@@ -139,26 +138,26 @@ extension Permutations: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@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>
/// Whether or not iteration is finished (`kRange` is empty)
@inlinable
internal var isFinished: Bool {
return kRange.isEmpty
}
@usableFromInline
internal var indexes: [Base.Index]
@inlinable
internal init(_ permutations: Permutations) {
self.base = permutations.base
@@ -166,7 +165,7 @@ extension Permutations: Sequence {
self.kRange = permutations.kRange
self.indexes = Array(permutations.base.indices)
}
/// Advances the `indexes` array such that the first `countToChoose`
/// elements contain the next lexicographic ordering of elements.
///
@@ -182,44 +181,44 @@ extension Permutations: Sequence {
internal mutating func nextState() -> Bool {
let countToChoose = self.kRange.lowerBound
let edge = countToChoose - 1
// Find first index greater than the one at `edge`.
if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) {
indexes.swapAt(edge, i)
} else {
indexes.reverse(subrange: countToChoose ..< indexes.endIndex)
indexes.reverse(subrange: countToChoose..<indexes.endIndex)
// 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]) {
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 }) {
indexes.swapAt(lastAscent, i)
}
indexes.reverse(subrange: (lastAscent + 1) ..< indexes.endIndex)
indexes.reverse(subrange: (lastAscent + 1)..<indexes.endIndex)
}
return true
}
@inlinable
public mutating func next() -> [Base.Element]? {
guard !isFinished else { return nil }
/// Advances `kRange` by incrementing its `lowerBound` until the range is
/// empty, when iteration is finished.
func advanceKRange() {
kRange.removeFirst()
indexes = Array(base.indices)
}
let countToChoose = self.kRange.lowerBound
if countToChoose == 0 {
defer {
@@ -227,7 +226,7 @@ extension Permutations: Sequence {
}
return []
}
let permutesFullCollection = (countToChoose == baseCount)
if permutesFullCollection {
// If we're permuting the full collection, each iteration is just a
@@ -252,7 +251,7 @@ extension Permutations: Sequence {
}
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
@@ -328,7 +327,7 @@ extension Collection {
) -> Permutations<Self> where R.Bound == Int {
return Permutations(self, kRange: kRange)
}
/// Returns a collection of the permutations of this collection of the
/// specified length.
///
@@ -400,10 +399,10 @@ public struct UniquePermutations<Base: Collection> {
/// The base collection to iterate over for permutations.
@usableFromInline
internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
internal let kRange: Range<Int>
}
@@ -414,29 +413,28 @@ extension UniquePermutations where Base.Element: Hashable {
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) }
}
@inlinable
internal init(_ elements: Base) {
self.indexes = Self._indexes(elements)
self.base = elements
self.kRange = self.indexes.count ..< (self.indexes.count + 1)
self.kRange = self.indexes.count..<(self.indexes.count + 1)
}
@inlinable
internal init<R: RangeExpression>(_ base: Base, _ range: R)
where R.Bound == Int
{
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)
.clamped(to: 0..<upperBound)
}
}
@@ -445,10 +443,10 @@ extension UniquePermutations: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let base: Base
@usableFromInline
internal var indexes: [Base.Index]
@usableFromInline
internal var lengths: Range<Int>
@@ -461,14 +459,14 @@ extension UniquePermutations: Sequence {
self.indexes = indexes
self.lengths = lengths
}
@inlinable
public mutating func next() -> [Base.Element]? {
// In the end case, `lengths` is an empty range.
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
// always mutate the array _before_ returning a slice, which avoids
@@ -485,11 +483,11 @@ extension UniquePermutations: Sequence {
return nil
}
}
return indexes[..<lengths.lowerBound].map { base[$0] }
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base, indexes: indexes, lengths: kRange)
@@ -539,7 +537,7 @@ extension Collection where Element: Hashable {
/// collection.
public func uniquePermutations(ofCount k: Int? = nil) -> UniquePermutations<Self> {
if let k = k {
return UniquePermutations(self, k ..< (k + 1))
return UniquePermutations(self, k..<(k + 1))
} else {
return UniquePermutations(self)
}
@@ -575,8 +573,7 @@ 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
{
where R.Bound == Int {
UniquePermutations(self, kRange)
}
}
+76 -73
View File
@@ -14,11 +14,11 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
@usableFromInline
internal let base1: Base1
/// The inner sequence in the product.
@usableFromInline
internal let base2: Base2
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
@@ -28,7 +28,7 @@ public struct Product2<Base1: Sequence, Base2: Collection> {
extension Product2: Sequence {
public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
@@ -47,10 +47,12 @@ extension Product2: Sequence {
self.i2 = c.base2.makeIterator()
self.element1 = nil
}
@inlinable
public mutating func next() -> (Base1.Element,
Base2.Element)? {
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.
@@ -59,21 +61,21 @@ extension Product2: Sequence {
// once Base1 is exhausted, return `nil` forever
if element1 == nil { return nil }
}
// Get the next element from the second sequence, if not
// at end.
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 }
else { return nil }
i2 = base2.makeIterator()
if let element2 = i2.next() {
return (element1, element2)
@@ -95,43 +97,45 @@ extension Product2: Collection where Base1: Collection {
internal var i1: Base1.Index
@usableFromInline
internal var 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 {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
}
}
@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 endIndex: Index {
// `base2.startIndex` simplifies index calculations.
Index(i1: base1.endIndex, i2: base2.startIndex)
}
@inlinable
public subscript(position: Index) -> (Base1.Element,
Base2.Element) {
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.
@@ -141,24 +145,24 @@ extension Product2: Collection where Base1: Collection {
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
: Index(i1: i1, i2: i2)
}
@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) }
else { return -distance(from: end, to: start) }
guard start.i1 != end.i1
else { return base2.distance(from: start.i2, to: end.i2) }
else { return base2.distance(from: start.i2, to: end.i2) }
// The number of full cycles through `base2` between `start` and `end`,
// excluding the cycles that `start` and `end` are on.
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
if start.i2 <= end.i2 {
// start.i2
// v
@@ -169,11 +173,11 @@ extension Product2: Collection where Base1: Collection {
// end.i1 > [l l l c c c c c c|r r r]
// ^
// end.i2
let left = base2[..<start.i2].count
let center = base2[start.i2..<end.i2].count
let right = base2[end.i2...].count
return center + right
+ fullBase2Cycles * (left + center + right)
+ left + center
@@ -187,30 +191,30 @@ extension Product2: Collection where Base1: Collection {
// end.i1 > [l l l|c c c c c c r r r]
// ^
// end.i2
let left = base2[..<end.i2].count
let right = base2[start.i2...].count
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
// are on consecutive cycles.
guard fullBase2Cycles > 0 else { return right + left }
let center = base2[end.i2..<start.i2].count
return right
+ fullBase2Cycles * (left + center + right)
+ left
}
}
@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)
}
@inlinable
public func index(
_ i: Index,
@@ -231,36 +235,35 @@ extension Product2: Collection where Base1: Collection {
@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") }
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") }
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit >= i)
if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`.
//
// i.i2 limit.i2
// 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) }
}
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
// `distance` does not overflow `base2[i.i2...]`.
//
@@ -268,14 +271,14 @@ extension Product2: Collection where Base1: Collection {
// v v
// i.i1 > [x x x|x x x x x x|x x x]
// [ |> > > > > >| ] (`distance`)
return normalizeIndex(i.i1, i2)
}
let suffixCount = base2[i.i2...].count
let remaining = distance - suffixCount
let nextI1 = base1.index(after: i.i1)
if limit.i1 == nextI1 {
// Delegate to `base2` if the offset is limited to `nextI1`.
//
@@ -285,11 +288,11 @@ extension Product2: Collection where Base1: Collection {
// nextI1 > [x x x x x x x x x|x x x]
// ^
// limit.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) {
// `remaining` does not overflow `base2[..<i.i2]`.
//
@@ -301,20 +304,20 @@ extension Product2: Collection where Base1: Collection {
// nextI1 > [x x x|x x x x x x x x x]
// ^
// i2
return Index(i1: nextI1, i2: i2)
}
let prefixCount = base2[..<i.i2].count
let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
else { return nil }
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) }
@@ -326,18 +329,18 @@ extension Product2: Collection where Base1: Collection {
) -> Index? {
assert(distance >= 0)
assert(limit <= i)
if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`.
//
// limit.i2 i.i2
// 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) }
}
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
// `distance` does not underflow `base2[..<i.i2]`.
//
@@ -345,14 +348,14 @@ extension Product2: Collection where Base1: Collection {
// v v
// i.i1 > [x x x|x x x x x x|x x x]
// [ |< < < < < <| ] (`distance`)
return Index(i1: i.i1, i2: i2)
}
let prefixCount = base2[..<i.i2].count
let remaining = distance - prefixCount
let previousI1 = base1.index(i.i1, offsetBy: -1)
if limit.i1 == previousI1 {
// Delegate to `base2` if the offset is limited to `previousI1`.
//
@@ -362,11 +365,11 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x x x x x x x|x x x]
// ^
// i.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) {
// `remaining` does not underflow `base2[i.i2...]`.
//
@@ -378,17 +381,17 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x]
// ^
// i.i2
return Index(i1: previousI1, i2: i2)
}
let suffixCount = base2[i.i2...].count
let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count
// The distance from `base2.endIndex` to the target.
let base2Distance = remaining % base2Count
if base2Distance == 0 {
// We end up exactly between two cycles, so `base1Distance` would
// overshoot the target by 1.
@@ -401,7 +404,7 @@ extension Product2: Collection where Base1: Collection {
// i.i1 > [x x x|x x x x x x x x x]
// ^
// i.i2
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
let index = Index(i1: i1, i2: base2.startIndex)
return index < limit ? nil : index
@@ -409,10 +412,10 @@ extension Product2: Collection where Base1: Collection {
return nil
}
}
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
else { return nil }
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) }
@@ -420,12 +423,12 @@ extension Product2: Collection where Base1: Collection {
}
extension Product2: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex,
"Can't move before startIndex")
precondition(
i != startIndex,
"Can't move before startIndex")
if i.i2 == base2.startIndex {
return Index(
i1: base1.index(before: i.i1),
@@ -437,7 +440,7 @@ extension Product2: BidirectionalCollection
}
extension Product2: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {}
+19 -20
View File
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===//
// For log(_:) and root(_:_:)
@_implementationOnly
import RealModule
@_implementationOnly import RealModule
//===----------------------------------------------------------------------===//
// randomStableSample(count:)
@@ -33,13 +32,13 @@ extension Collection {
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var remainingCount = count
guard k < remainingCount else { return Array(self) }
var result: [Element] = []
result.reserveCapacity(k)
var i = startIndex
var countToSelect = k
while countToSelect > 0 {
@@ -52,10 +51,10 @@ extension Collection {
formIndex(after: &i)
remainingCount -= 1
}
return result
}
/// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order.
///
@@ -120,22 +119,22 @@ extension Collection {
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var i = startIndex
while i < endIndex, result.count < k {
result.append(self[i])
formIndex(after: &i)
}
while i < endIndex {
// Calculate the next value of w.
w *= nextW(k: k, using: &rng)
// Find index of the next element to swap into the reservoir.
let offset = nextOffset(w: w, using: &rng)
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
if i < endIndex {
// Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng)
@@ -143,12 +142,12 @@ extension Collection {
formIndex(after: &i)
}
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this collection.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
@@ -186,11 +185,11 @@ extension Sequence {
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var iterator = makeIterator()
while result.count < k, let el = iterator.next() {
@@ -200,26 +199,26 @@ extension Sequence {
while true {
// Calculate the next value of w.
w *= nextW(k: k, using: &rng)
// Find the offset of the next element to swap into the reservoir.
var offset = nextOffset(w: w, using: &rng)
// Skip over `offset` elements to find the selected element.
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.
let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = nextElement
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this sequence.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
+11 -9
View File
@@ -234,9 +234,10 @@ extension ExclusiveReductions: Sequence {
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
current: initial,
transform: transform)
Iterator(
iterator: base.makeIterator(),
current: initial,
transform: transform)
}
}
@@ -317,10 +318,10 @@ extension ExclusiveReductions: Collection where Base: Collection {
}
extension ExclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension ExclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
// MARK: - Inclusive Reductions
@@ -453,8 +454,9 @@ extension InclusiveReductions: Sequence {
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(),
transform: transform)
Iterator(
iterator: base.makeIterator(),
transform: transform)
}
}
@@ -537,10 +539,10 @@ extension InclusiveReductions: Collection where Base: Collection {
}
extension InclusiveReductions: LazySequenceProtocol
where Base: LazySequenceProtocol {}
where Base: LazySequenceProtocol {}
extension InclusiveReductions: LazyCollectionProtocol
where Base: LazyCollectionProtocol {}
where Base: LazyCollectionProtocol {}
// MARK: - ReductionsIndexRepresentation
+16 -16
View File
@@ -43,7 +43,7 @@ extension MutableCollection where Self: BidirectionalCollection {
}
return (lower, upper)
}
/// Reverses the elements within the given subrange.
///
/// This example reverses the numbers within the subrange at the start of the
@@ -100,15 +100,14 @@ extension MutableCollection {
) -> (Index, Index) {
assert(!lhs.isEmpty)
assert(!rhs.isEmpty)
var p = lhs.lowerBound
var q = rhs.lowerBound
repeat {
swapAt(p, q)
formIndex(after: &p)
formIndex(after: &q)
}
while p != lhs.upperBound && q != rhs.upperBound
} while p != lhs.upperBound && q != rhs.upperBound
return (p, q)
}
@@ -139,13 +138,14 @@ extension MutableCollection {
subrange: Range<Index>,
toStartAt newStart: Index
) -> Index {
var m = newStart, s = subrange.lowerBound
var m = newStart
var s = subrange.lowerBound
let e = subrange.upperBound
// Handle the trivial cases
if s == m { return e }
if m == e { return s }
// We have two regions of possibly-unequal length that need to be
// exchanged. The return value of this method is going to be the
// position following that of the element that is currently last
@@ -155,7 +155,7 @@ extension MutableCollection {
// ^ ^ ^ ^ ^ ^
// s m e s m e
//
var ret = e // start with a known incorrect result.
var ret = e // start with a known incorrect result.
while true {
// Exchange the leading elements of each region (up to the
// length of the shorter region).
@@ -167,7 +167,7 @@ extension MutableCollection {
// s s1 m m1/e s s1/m m1 e
//
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
if m1 == e {
// Left-hand case: we have moved element j into position. if
// we haven't already, we can capture the return value which
@@ -177,11 +177,11 @@ extension MutableCollection {
// comparison once the return value is known. I'm not sure
// it's a worthwhile optimization, though.
if ret == e { ret = s1 }
// If both regions were the same size, we're done.
if s1 == m { break }
}
// Now we have a smaller problem that is also a rotation, so we
// can adjust our bounds and repeat.
//
@@ -191,10 +191,10 @@ extension MutableCollection {
s = s1
if s == m { m = m1 }
}
return ret
}
/// Rotates the elements of this collection so that the element
/// at the specified index becomes the start of the collection.
///
@@ -287,11 +287,11 @@ extension MutableCollection {
@discardableResult
public mutating func rotate(
subrange: Range<Index>,
at newStart: Index) -> Index
{
at newStart: Index
) -> Index {
rotate(subrange: subrange, toStartAt: newStart)
}
@available(*, deprecated, renamed: "rotate(toStartAt:)")
@discardableResult
public mutating func rotate(at newStart: Index) -> Index {
+32 -31
View File
@@ -54,13 +54,13 @@ extension Collection {
/// A wrapper that strides over a base sequence.
public struct StrideSequence<Base: Sequence>: Sequence {
@usableFromInline
internal let base: Base
@usableFromInline
internal let stride: Int
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
@@ -70,24 +70,24 @@ public struct StrideSequence<Base: Sequence>: Sequence {
}
extension StrideSequence {
/// An iterator over a `Stride` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var iterator: Base.Iterator
@usableFromInline
internal let stride: Int
@usableFromInline
internal var striding: Bool = false
@inlinable
internal init(iterator: Base.Iterator, stride: Int) {
self.iterator = iterator
self.stride = stride
}
@inlinable
public mutating func next() -> Base.Element? {
guard striding else {
@@ -100,7 +100,7 @@ extension StrideSequence {
return iterator.next()
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(iterator: base.makeIterator(), stride: stride)
@@ -118,10 +118,10 @@ extension StrideSequence {
public struct StrideCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let stride: Int
@inlinable
internal init(base: Base, stride: Int) {
precondition(stride > 0, "striding must be greater than zero")
@@ -138,44 +138,44 @@ extension StrideCollection {
}
extension StrideCollection: Collection {
/// A position in a `Stride` collection.
public struct Index: Comparable {
@usableFromInline
internal let base: Base.Index
@usableFromInline
internal init(_ base: Base.Index) {
self.base = 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 endIndex: Index {
Index(base.endIndex)
}
@inlinable
public subscript(i: Index) -> Base.Element {
base[i.base]
}
@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,
@@ -184,12 +184,12 @@ extension StrideCollection: Collection {
) -> Index? {
guard n != 0 else { return i }
guard limit != i else { return nil }
return n > 0
? offsetForward(i, offsetBy: n, limitedBy: limit)
: offsetBackward(i, offsetBy: -n, limitedBy: limit)
}
@inlinable
internal func offsetForward(
_ i: Index,
@@ -219,34 +219,35 @@ extension StrideCollection: Collection {
: nil
}
}
@inlinable
internal func offsetBackward(
_ i: Index,
offsetBy n: Int,
limitedBy limit: Index
) -> Index? {
let distance = i == endIndex
let distance =
i == endIndex
? -((base.count - 1) % stride + 1) + (n - 1) * -stride
: n * -stride
return base.index(
i.base,
offsetBy: distance,
limitedBy: limit.base
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 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 {
precondition(distance <= 0 || i.base < base.endIndex, "Advancing past end index")
@@ -259,8 +260,8 @@ extension StrideCollection: Collection {
}
extension StrideCollection: BidirectionalCollection
where Base: RandomAccessCollection {
where Base: RandomAccessCollection {
@inlinable
public func index(before i: Index) -> Index {
precondition(i.base > base.startIndex, "Incrementing past start index")
+7 -7
View File
@@ -14,11 +14,11 @@ public struct Uniqued<Base: Sequence, Subject: Hashable> {
/// The base collection.
@usableFromInline
internal let base: Base
/// The projection function.
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline
internal init(base: Base, projection: @escaping (Base.Element) -> Subject) {
self.base = base
@@ -31,13 +31,13 @@ extension Uniqued: Sequence {
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var base: Base.Iterator
@usableFromInline
internal let projection: (Base.Element) -> Subject
@usableFromInline
internal var seen: Set<Subject> = []
@usableFromInline
internal init(
base: Base.Iterator,
@@ -46,7 +46,7 @@ extension Uniqued: Sequence {
self.base = base
self.projection = projection
}
@inlinable
public mutating func next() -> Base.Element? {
while let element = base.next() {
@@ -57,7 +57,7 @@ extension Uniqued: Sequence {
return nil
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(base: base.makeIterator(), projection: projection)
+70 -67
View File
@@ -49,10 +49,10 @@ extension Collection {
public struct Windows<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let size: Int
@usableFromInline
internal var firstUpperBound: Base.Index?
@@ -71,27 +71,27 @@ extension Windows: Collection {
public struct Index: Comparable {
@usableFromInline
internal var lowerBound: Base.Index
@usableFromInline
internal var 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 {
lhs.lowerBound == rhs.lowerBound
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound
}
}
@inlinable
public var startIndex: Index {
if let upperBound = firstUpperBound {
@@ -100,12 +100,12 @@ extension Windows: Collection {
return endIndex
}
}
@inlinable
public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
}
@inlinable
public subscript(index: Index) -> Base.SubSequence {
precondition(
@@ -113,7 +113,7 @@ extension Windows: Collection {
"Windows index is out of range")
return base[index.lowerBound..<index.upperBound]
}
@inlinable
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Advancing past end index")
@@ -123,16 +123,16 @@ extension Windows: Collection {
upperBound: base.index(after: index.upperBound)
)
}
@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)
}
@inlinable
public func index(
_ i: Index,
@@ -141,7 +141,7 @@ extension Windows: Collection {
) -> 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)
@@ -152,28 +152,28 @@ extension Windows: Collection {
: 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") }
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") }
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit > i)
// `endIndex` and the index before it both have `base.endIndex` as their
// upper bound, so we first advance to the base index _before_ the upper
// bound of the output, in order to avoid advancing past the end of `base`
@@ -184,31 +184,31 @@ extension Windows: Collection {
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
// |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
if distance >= size {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
// bound of the output is greater than or equal to the upper bound of the
// input.
// 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 limit.lowerBound >= i.upperBound,
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - size,
limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: size - 1,
limitedBy: limit.upperBound)
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - size,
limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
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))
@@ -216,35 +216,36 @@ extension Windows: Collection {
// 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 indexBeforeUpperBound = base.index(
i.upperBound,
offsetBy: distance - 1,
limitedBy: limit.upperBound)
guard
let indexBeforeUpperBound = base.index(
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 }
else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index(
lowerBound: base.index(i.lowerBound, offsetBy: distance),
upperBound: base.index(after: indexBeforeUpperBound))
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit < i)
if i == endIndex {
// Advance `base.endIndex` by `distance - 1`, because the index before
// `endIndex` also has `base.endIndex` as its upper bound.
@@ -254,13 +255,14 @@ extension Windows: Collection {
// input: [x x x x x x x x x x] (`endIndex`)
// |< < < < <|< < <|
// output: [x x|x x x x x|x x x]
guard let upperBound = base.index(
base.endIndex,
offsetBy: -(distance - 1),
limitedBy: limit.upperBound)
guard
let upperBound = base.index(
base.endIndex,
offsetBy: -(distance - 1),
limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
@@ -272,14 +274,14 @@ extension Windows: Collection {
// 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 limit.upperBound <= i.lowerBound,
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - size),
limitedBy: limit.upperBound)
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - size),
limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -size),
upperBound: upperBound)
@@ -287,19 +289,20 @@ extension Windows: Collection {
// 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)
guard
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))
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
guard start <= end else { return -distance(from: end, to: start) }
@@ -317,13 +320,13 @@ extension Windows: Collection {
// start: [x|x x x x|x x x x x x x]
// |- - - -|> >|
// end: [x x x x x x x|x x x x|x]
return size + base[start.upperBound..<end.lowerBound].count
} else {
// start: [x|x x x x x x|x x x x x]
// |> > > >|
// end: [x x x x x|x x x x x x|x]
return base[start.lowerBound..<end.lowerBound].count
}
}