Skip to content

Instantly share code, notes, and snippets.

@vyo
Last active July 10, 2017 06:42
Show Gist options
  • Save vyo/63d4e1885c67c658634b9ddae8f1e7d7 to your computer and use it in GitHub Desktop.
Save vyo/63d4e1885c67c658634b9ddae8f1e7d7 to your computer and use it in GitHub Desktop.
Raw, Unsafe, Pointy: CapnSwifty Babysteps
// watsonkitty playground
import Cocoa
protocol CapnSwiftyReader {
}
protocol CapnSwiftyBuilder {
}
class CapnSwiftyVersion {
private let pointer: UnsafeMutableRawPointer
init(pointer: UnsafeMutableRawPointer) {
self.pointer = pointer
initPointer()
}
init() {
pointer = UnsafeMutableRawPointer.allocate(bytes: 4, alignedTo: 1)
initPointer()
}
private func initPointer() {
pointer.storeBytes(of: 0, toByteOffset: 0, as: UInt16.self)
pointer.storeBytes(of: 0, toByteOffset: 2, as: UInt8.self)
pointer.storeBytes(of: 0, toByteOffset: 3, as: UInt8.self)
}
deinit {
pointer.deallocate(bytes: 4, alignedTo: 1)
}
var major: UInt16 {
@inline(__always) get {
return pointer.load(as: UInt16.self)
}
@inline(__always) set {
pointer.storeBytes(of: newValue, toByteOffset: 0, as: UInt16.self)
}
}
var minor: UInt8 {
@inline(__always) get {
return (pointer + 2).load(as: UInt8.self)
}
@inline(__always) set {
// let maxDist = newValue.distance(to: UInt8.max)
// let minDist = newValue.distance(to: UInt8.min)
// assert(maxDist >= 0 && minDist <= 0, "newValue is within bounds of UInt8") // not working in Playground? =(
pointer.storeBytes(of: newValue, toByteOffset: 2, as: UInt8.self)
}
}
var micro: UInt8 {
@inline(__always) get {
return (pointer + 3).load(as: UInt8.self)
}
@inline(__always) set {
pointer.storeBytes(of: newValue, toByteOffset: 3, as: UInt8.self)
}
}
}
let version = CapnSwiftyVersion()
version.major = 256
version.minor = 255
let major = version.major
let minor = version.minor
let micro = version.micro
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment