Skip to content

Instantly share code, notes, and snippets.

@LucianoPAlmeida
Created February 17, 2019 20:29
Show Gist options
  • Save LucianoPAlmeida/e5e36b6ff30dc0b016e549ad618bda8b to your computer and use it in GitHub Desktop.
Save LucianoPAlmeida/e5e36b6ff30dc0b016e549ad618bda8b to your computer and use it in GitHub Desktop.
Playing around with Swift pointers
import Foundation
struct P {
var b: Bool
var i: Int
}
MemoryLayout<P>.size // returns 9
MemoryLayout<P>.alignment // returns 8
MemoryLayout<P>.stride // returns 16
// Arrays
var array = [1,2, 3, 4, 5]
var array2 = [6, 7, 8, 9, 10]
var integer = 1
array.withUnsafeMutableBufferPointer { (buffer) -> Void in
array2.withUnsafeMutableBufferPointer({ (buffer2) -> Void in
buffer.baseAddress?.moveAssign(from: buffer2.baseAddress!, count: 3)
})
}
print(array)
print(array2)
// Raw Pointers
let pointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<Int>.size, alignment: MemoryLayout<Int>.alignment)
pointer.storeBytes(of: 5, as: Int.self)
(pointer + MemoryLayout<Int>.stride).storeBytes(of: 6, as: Int.self)
let buff = UnsafeBufferPointer(start: pointer.assumingMemoryBound(to: Int.self), count: 2)
let s = buff.map({ $0 })
print(s)
buff.deallocate()
// Generic Pointers
let p = UnsafeMutablePointer<Int>.allocate(capacity: 4)
p.initialize(to: 4)
p.advanced(by: 1).initialize(to: 3)
var b = UnsafeBufferPointer<Int>(start: p, count: 4)
print(b.map({ $0 }))
p.deinitialize(count: 4)
p.deallocate()
let i = UnsafeMutablePointer<NSMutableString>.allocate(capacity: 2)
i.initialize(repeating: NSMutableString(), count: 2)
i.pointee.append("hue")
i.advanced(by: 1).pointee = NSMutableString(extendedGraphemeClusterLiteral: "dlsakj")
var strs = UnsafeBufferPointer<NSMutableString>(start: i, count: 2)
print(strs.map({ $0 }))
i.deinitialize(count: 2)
strs.deallocate()
// Bytes manipulation
var ps = P(b: true, i: 10)
withUnsafeMutableBytes(of: &ps) { (pointer) in
pointer.swapAt(0, 1)
}
print(ps.i)
let i8: UInt8 = 0
print(~i8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment