Skip to content

Instantly share code, notes, and snippets.

@kirilltitov
Last active July 10, 2018 12:48
Show Gist options
  • Save kirilltitov/ee7b05ee51a6cd6c2a8c29f0d6af95b2 to your computer and use it in GitHub Desktop.
Save kirilltitov/ee7b05ee51a6cd6c2a8c29f0d6af95b2 to your computer and use it in GitHub Desktop.
Swift 4 Any to Bytes (and back again) conversion (Foundationless! No Data or NSData!)
// Notice no Foundation :3
typealias Byte = UInt8
typealias Bytes = [Byte]
func getBytes<Input>(_ input: Input) -> Bytes {
return withUnsafeBytes(of: input) { Bytes($0) }
}
// You must be ABSOLUTELY SURE about input bytes, or enjoy your fresh and crispy BAD_ACCESS runtime error
// So obviously, this is very unsafe if you don't know what you're doing.
// But if you came here, you most probably know what you're doing :)
// Obviously, precondition stops working when you're dealing with non-trivial types (why would you?)
func cast<Result>(_ input: Bytes) -> Result {
precondition(
MemoryLayout<Result>.size == input.count,
"Memory layout size for result type '\(Result.self)' (\(MemoryLayout<Result>.size) bytes) does not match with given byte array length (\(input.count) bytes)"
)
return input.withUnsafeBytes {
$0.baseAddress!.assumingMemoryBound(to: Result.self).pointee
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment