Skip to content

Instantly share code, notes, and snippets.

@jenox
Last active June 20, 2022 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenox/f93996a296c4715ada629f3204ee7860 to your computer and use it in GitHub Desktop.
Save jenox/f93996a296c4715ada629f3204ee7860 to your computer and use it in GitHub Desktop.
Performing mutating operations on slices cause copies that are later written back to the source collection. Thus `array[range].sort()` is less efficient than a hypothetical `array.sort(in: range)`.
class Box<T> {
init(value: T) {
self.value = value
}
var value: T
}
struct MyArray<T> {
private var storage: Box<[T]> = Box(value: [])
}
extension MyArray: ExpressibleByArrayLiteral, MutableCollection, RandomAccessCollection {
init(arrayLiteral elements: T...) {
self.storage = Box(value: elements)
}
var startIndex: Int {
return self.storage.value.startIndex
}
var endIndex: Int {
return self.storage.value.endIndex
}
func index(after i: Int) -> Int {
return self.storage.value.index(after: i)
}
func index(before i: Int) -> Int {
return self.storage.value.index(before: i)
}
func index(_ i: Int, offsetBy distance: Int) -> Int {
return self.storage.value.index(i, offsetBy: distance)
}
func distance(from start: Int, to end: Int) -> Int {
return self.storage.value.distance(from: start, to: end)
}
subscript(position: Int) -> T {
get { return self.storage.value[position] }
set {
if !isKnownUniquelyReferenced(&self.storage) {
print("need copy")
self.storage = Box(value: self.storage.value)
}
self.storage.value[position] = newValue
}
}
}
var array: MyArray<Int> = [4,1,3,2]
array[0..<3].sort() // "need copy"
print(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment