Create a gist now

Instantly share code, notes, and snippets.

class ArrayImpl<T> {
var space: Int
var count: Int
var ptr: UnsafeMutablePointer<T>
init(count: Int = 0, ptr: UnsafeMutablePointer<T> = nil) {
self.count = count
self.space = count
self.ptr = UnsafeMutablePointer<T>.alloc(count)
self.ptr.initializeFrom(ptr, count: count)
}
func append(obj: T) {
if space == count {
let newSpace = max(space * 2, 16)
let newPtr = UnsafeMutablePointer<T>.alloc(newSpace)
newPtr.moveInitializeFrom(ptr, count: count)
ptr.dealloc(count)
ptr = newPtr
space = newSpace
}
(ptr + count).initialize(obj)
count++
}
func remove(# index: Int) {
(ptr + index).destroy()
(ptr + index).moveInitializeFrom(ptr + index + 1, count: count - index - 1)
count--
}
func copy() -> ArrayImpl<T> {
return ArrayImpl<T>(count: count, ptr: ptr)
}
deinit {
ptr.destroy(count)
ptr.dealloc(count)
}
}
struct Array<T>: Printable, CollectionType {
private var impl: ArrayImpl<T> = ArrayImpl<T>()
private mutating func ensureUnique() {
if !isUniquelyReferencedNonObjC(&impl) {
impl = impl.copy()
}
}
mutating func append(value: T) {
ensureUnique()
impl.append(value)
}
mutating func remove(# index: Int) {
ensureUnique()
impl.remove(index: index)
}
var count: Int {
return impl.count
}
subscript(index: Int) -> T {
get {
return impl.ptr[index]
}
mutating set {
ensureUnique()
impl.ptr[index] = newValue
}
}
var description: String {
var str = ""
for value in self {
if !str.isEmpty {
str += ", "
}
str += toString(value)
}
return "(\(impl.ptr): " + str + ")"
}
typealias Index = Int
var startIndex: Index {
return 0
}
var endIndex: Index {
return count
}
typealias Generator = GeneratorOf<T>
func generate() -> Generator {
var index = 0
return GeneratorOf<T>{
if index < self.count {
return self[index++]
} else {
return nil
}
}
}
}
var array = Array<Int>()
var array2 = array
println((array, array2))
array.append(42)
array2.append(99)
array2.append(43)
println((array, array2))
var array3 = array2
array2[0] = 1
array3[0] = 0
println((array2, array3))
array3.remove(index: 1)
array3.remove(index: 0)
println(array3)
var array4 = Array<Int>()
for i in 0..<100 {
array4.append(i)
}
var array5 = array4
while array4.count > 3 {
array4.remove(index: 1)
}
println((array4, array5))
var strarray = Array<String>()
strarray.append("e")
for i in 0..<100 {
strarray.append("\(i)")
}
println(strarray)
var strarray2 = strarray
while strarray.count > 4 {
strarray.remove(index: 3)
}
while strarray2.count > 4 {
strarray2.remove(index: strarray2.count - 1)
}
println((strarray, strarray2))
for s in strarray {
println(s)
}
@alonecuzzo

👍

@ttilley
ttilley commented Sep 14, 2015

don't you want to dealloc space, not count?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment