Last active
July 10, 2017 06:42
Raw, Unsafe, Pointy: CapnSwifty Babysteps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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