Skip to content

Improve performance of Collection.removeFirst(_:) where Self == SubSequence #32451

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 5 commits into from
Jun 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions stdlib/public/core/Collection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1664,8 +1664,10 @@ extension Collection where SubSequence == Self {
public mutating func removeFirst(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: k)..<endIndex]
guard let idx = index(startIndex, offsetBy: k, limitedBy: endIndex) else {
_preconditionFailure(
"Can't remove more items from a collection than it contains")
}
self = self[idx..<endIndex]
}
}
15 changes: 9 additions & 6 deletions stdlib/public/core/RangeReplaceableCollection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -590,9 +590,10 @@ extension RangeReplaceableCollection {
public mutating func removeFirst(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it has")
let end = index(startIndex, offsetBy: k)
guard let end = index(startIndex, offsetBy: k, limitedBy: endIndex) else {
_preconditionFailure(
"Can't remove more items from a collection than it has")
}
removeSubrange(startIndex..<end)
}

Expand Down Expand Up @@ -698,9 +699,11 @@ extension RangeReplaceableCollection where SubSequence == Self {
public mutating func removeFirst(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: k)..<endIndex]
guard let idx = index(startIndex, offsetBy: k, limitedBy: endIndex) else {
_preconditionFailure(
"Can't remove more items from a collection than it contains")
}
self = self[idx..<endIndex]
}
}

Expand Down