Skip to content

Instantly share code, notes, and snippets.

@dabrahams
Last active June 24, 2024 16:19
Show Gist options
  • Save dabrahams/2132fced6473955a0698d247f574c166 to your computer and use it in GitHub Desktop.
Save dabrahams/2132fced6473955a0698d247f574c166 to your computer and use it in GitHub Desktop.
extension RangeReplaceableCollection {
public fun remove<E>(where exclude: [E](Element)->Bool) inout {
let end = end_position()
var i = first(where: exclude)
if i == end { return }
let include =
var j = self[self.position(after: i)...]
.first(where: x => !exclude(x) )
var k = j
// invariant: i <= j <= k
// - self[..<i] is all included elements
// - self[i..<j] is all excluded elements
// - self[j..<k] is uninitialized
while k != end {
if exclude(self[k]) {
unsafe_deinitialize(at: k)
}
else {
if i != j {
unsafe_move_assign(from: k, to: i)
}
else {
unsafe_move_initialize(from: k, to: i)
&j = index(after: j)
}
&i = index(after: i)
}
&k = index(after: k)
}
let z = i.copy()
while i != j {
unsafe_deinitialize(at: i)
&i = index(after: i)
}
unsafe_remove_uninitialized(z...)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment