-
Notifications
You must be signed in to change notification settings - Fork 450
Add Stride for Collection #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
17cb07e
Add Stride for Collection
ollieatkinson 6df6133
Refactor to index(_:offsetBy:limitedBy:) and utilise the new test uti…
ollieatkinson 4a194ca
remove redundant limit
ollieatkinson dcdef50
make base and stride internal
ollieatkinson 6f7148d
Implementation of feedback from @timvermeulen
ollieatkinson 28bbed8
Add implementation for Sequence iterator
ollieatkinson 377bb72
small documentation tweek collection -> sequence
ollieatkinson 92b2846
Add unbounded striding tests to check empty and sequence implementation
ollieatkinson 0a6bcc3
compute the stride only when the next element is requested
ollieatkinson 3669ff0
offsetBackward n is positive and remove init? from Index
ollieatkinson dfcc611
consistant negative stride
ollieatkinson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
# Stride | ||
|
||
[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Stride.swift) | | ||
[Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/StrideTests.swift)] | ||
|
||
A type that steps over sequence elements by the specified amount. | ||
|
||
This is available through the `striding(by:)` method on any `Sequence`. | ||
|
||
```swift | ||
(0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] | ||
``` | ||
|
||
If the stride is larger than the count, the resulting wrapper only contains the | ||
first element. | ||
|
||
The stride amount must be a positive value. | ||
|
||
## Detailed Design | ||
|
||
The `striding(by:)` method is declared as a `Sequence` extension, and returns a | ||
`Stride` type: | ||
|
||
```swift | ||
extension Sequence { | ||
public func striding(by step: Int) -> Stride<Self> | ||
} | ||
``` | ||
|
||
A custom `Index` type is defined so that it's not possible to get confused when trying | ||
to access an index of the stride collection. | ||
|
||
```swift | ||
[0, 1, 2, 3, 4].striding(by: 2)[1] // == 1 | ||
[0, 1, 2, 3, 4].striding(by: 2).map { $0 }[1] // == 2 | ||
``` | ||
|
||
A careful thought was given to the composition of these strides by giving a custom | ||
implementation to `index(_:offsetBy:limitedBy)` which multiplies the offset by the | ||
stride amount. | ||
|
||
```swift | ||
base.index(i.base, offsetBy: distance * stride, limitedBy: base.endIndex) | ||
``` | ||
|
||
The following two lines of code are equivalent, including performance: | ||
|
||
```swift | ||
(0...10).striding(by: 6) | ||
(0...10).striding(by: 2).stride(by: 3) | ||
``` | ||
|
||
### Complexity | ||
|
||
The call to `striding(by: k)` is always O(_1_) and access to the next value in the stride | ||
is O(_1_) if the collection conforms to `RandomAccessCollection`, otherwise O(_k_). | ||
|
||
### Comparison with other languages | ||
|
||
[rust has `Strided`](https://docs.rs/strided/0.2.9/strided/) available in a crate. | ||
[c++ has std::slice::stride](http://www.cplusplus.com/reference/valarray/slice/stride/) | ||
|
||
The semantics of `striding` described in this documentation are equivalent. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,224 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift Algorithms open source project | ||
// | ||
// Copyright (c) 2020 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See https://swift.org/LICENSE.txt for license information | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
//===----------------------------------------------------------------------===// | ||
// striding(by:) | ||
//===----------------------------------------------------------------------===// | ||
|
||
extension Sequence { | ||
/// Returns a sequence stepping through the elements every `step` starting | ||
/// at the first value. Any remainders of the stride will be trimmed. | ||
/// | ||
/// (0...10).striding(by: 2) // == [0, 2, 4, 6, 8, 10] | ||
/// (0...10).striding(by: 3) // == [0, 3, 6, 9] | ||
/// | ||
/// - Complexity: O(1). Access to successive values is O(1) if the | ||
/// collection conforms to `RandomAccessCollection`; otherwise, | ||
/// O(_k_), where _k_ is the striding `step`. | ||
/// | ||
/// - Parameter step: The amount to step with each iteration. | ||
/// - Returns: Returns a sequence or collection for stepping through the | ||
/// elements by the specified amount. | ||
public func striding(by step: Int) -> Stride<Self> { | ||
Stride(base: self, stride: step) | ||
} | ||
} | ||
|
||
public struct Stride<Base: Sequence> { | ||
|
||
let base: Base | ||
let stride: Int | ||
|
||
init(base: Base, stride: Int) { | ||
precondition(stride > 0, "striding must be greater than zero") | ||
self.base = base | ||
self.stride = stride | ||
} | ||
} | ||
|
||
extension Stride { | ||
public func striding(by step: Int) -> Self { | ||
Stride(base: base, stride: stride * step) | ||
} | ||
} | ||
|
||
extension Stride: Sequence { | ||
|
||
public struct Iterator: IteratorProtocol { | ||
|
||
var iterator: Base.Iterator | ||
let stride: Int | ||
|
||
public mutating func next() -> Base.Element? { | ||
defer { | ||
for _ in 0..<(stride - 1) { | ||
guard iterator.next() != nil else { break } | ||
} | ||
} | ||
return iterator.next() | ||
ollieatkinson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
public func makeIterator() -> Stride<Base>.Iterator { | ||
Iterator(iterator: base.makeIterator(), stride: stride) | ||
} | ||
} | ||
|
||
extension Stride: Collection where Base: Collection { | ||
|
||
public struct Index: Comparable { | ||
|
||
let base: Base.Index | ||
|
||
init(_ base: Base.Index) { | ||
self.base = base | ||
} | ||
|
||
init?(_ base: Base.Index?) { | ||
guard let base = base else { return nil } | ||
self.base = base | ||
} | ||
ollieatkinson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
public static func < (lhs: Index, rhs: Index) -> Bool { | ||
lhs.base < rhs.base | ||
} | ||
} | ||
|
||
public var startIndex: Index { | ||
Index(base.startIndex) | ||
} | ||
|
||
public var endIndex: Index { | ||
Index(base.endIndex) | ||
} | ||
|
||
public subscript(i: Index) -> Base.Element { | ||
base[i.base] | ||
} | ||
|
||
public func index(after i: Index) -> Index { | ||
precondition(i.base < base.endIndex, "Advancing past end index") | ||
return index(i, offsetBy: 1) | ||
} | ||
|
||
public func index( | ||
_ i: Index, | ||
offsetBy n: Int, | ||
limitedBy limit: Index | ||
) -> 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) | ||
ollieatkinson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
private 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 | ||
) { | ||
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 | ||
) { | ||
return Index(idx) | ||
} else { | ||
return distance(from: i, to: limit) == n | ||
? endIndex | ||
: nil | ||
} | ||
} | ||
|
||
private 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 Index( | ||
base.index( | ||
i.base, | ||
offsetBy: distance, | ||
limitedBy: limit.base | ||
) | ||
) | ||
} | ||
|
||
public var count: Int { | ||
base.isEmpty ? 0 : (base.count - 1) / stride + 1 | ||
} | ||
|
||
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() | ||
} | ||
|
||
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 | ||
let idx = index(i, offsetBy: distance, limitedBy: limit) | ||
precondition(idx != nil, "The distance \(distance) is not valid for this collection") | ||
return idx! | ||
} | ||
} | ||
|
||
extension Stride: BidirectionalCollection | ||
where Base: RandomAccessCollection { | ||
|
||
public func index(before i: Index) -> Index { | ||
precondition(i.base > base.startIndex, "Incrementing past start index") | ||
return index(i, offsetBy: -1) | ||
} | ||
} | ||
|
||
extension Stride: RandomAccessCollection | ||
where Base: RandomAccessCollection {} | ||
|
||
extension Stride: Equatable | ||
where Base.Element: Equatable { | ||
|
||
public static func == (lhs: Stride, rhs: Stride) -> Bool { | ||
lhs.elementsEqual(rhs, by: ==) | ||
} | ||
|
||
} | ||
|
||
extension Stride: Hashable | ||
where Base.Element: Hashable { | ||
|
||
public func hash(into hasher: inout Hasher) { | ||
hasher.combine(stride) | ||
for element in self { | ||
hasher.combine(element) | ||
} | ||
} | ||
|
||
} | ||
|
||
extension Stride.Index: Hashable | ||
where Base.Index: Hashable {} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.