Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created September 4, 2016 06:42
Show Gist options
  • Save pyrtsa/f683a7fac160775a33a210e938f6b107 to your computer and use it in GitHub Desktop.
Save pyrtsa/f683a7fac160775a33a210e938f6b107 to your computer and use it in GitHub Desktop.
Looking at the memory layout of Array and AnyIterator in Swift
import Foundation
struct P : CustomStringConvertible {
var p: OpaquePointer?
init(_ p: OpaquePointer?) {
self.p = p
}
var description: String {
return String(format: "0x%0*zx", 2 * MemoryLayout<UInt>.size, unsafeBitCast(p, to: UInt.self))
}
subscript(offset: Int) -> P {
return P(unsafeBitCast(p!, to: UnsafePointer<OpaquePointer?>.self).advanced(by: offset).pointee)
}
}
let xs = [10, 20, 30, 0xdeadbeef]
let it = AnyIterator(xs.makeIterator())
let xsPtr = P(unsafeBitCast(xs, to: OpaquePointer.self))
let itPtr = P(unsafeBitCast(it, to: OpaquePointer.self))
print("xs:", xsPtr, (0 ..< 8).map { xsPtr[$0] })
print("it:", itPtr, (0 ..< 4).map { itPtr[$0] })
while let x = it.next() {
print("it:", itPtr, (0 ..< 4).map { itPtr[$0] }, "x:", x)
}
/*
Possible output:
xs: 0x00007f85ca49c2d0 [0x000000010d7b1030, 0x0000000200000008, 0x0000000000000004, 0x0000000000000008, 0x000000000000000a, 0x0000000000000014, 0x000000000000001e, 0x00000000deadbeef]
it: 0x00007f85ca46c040 [0x000000010d7ff030, 0x0000000200000004, 0x00007f85ca49c2d0, 0x0000000000000000]
it: 0x00007f85ca46c040 [0x000000010d7ff030, 0x0000000200000004, 0x00007f85ca49c2d0, 0x0000000000000001] x: 10
it: 0x00007f85ca46c040 [0x000000010d7ff030, 0x0000000200000004, 0x00007f85ca49c2d0, 0x0000000000000002] x: 20
it: 0x00007f85ca46c040 [0x000000010d7ff030, 0x0000000200000004, 0x00007f85ca49c2d0, 0x0000000000000003] x: 30
it: 0x00007f85ca46c040 [0x000000010d7ff030, 0x0000000200000004, 0x00007f85ca49c2d0, 0x0000000000000004] x: 3735928559
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment