Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created July 11, 2014 00:45
Show Gist options
  • Save mikeash/0f1db7b5d8d9ece1f61b to your computer and use it in GitHub Desktop.
Save mikeash/0f1db7b5d8d9ece1f61b to your computer and use it in GitHub Desktop.
enum Endianness {
case Big
case Little
func swapWithNative(slice: Slice<UInt8>) -> Slice<UInt8> {
#if true
let native = Little
#else
let native = Big
#endif
return (self == native ? slice : slice.reverse())
}
}
func DeserializeBytes<T>(storage: [UInt8], offset: Int, _ endianness: Endianness = .Big) -> T {
let swap = true
let size = sizeof(T)
let slice = storage[offset..<(offset + size)]
let swapped = endianness.swapWithNative(slice)
return swapped.withUnsafePointerToElements{ UnsafePointer<T>($0).memory }
}
struct Y {
let storage: [UInt8]
var field: Int8 { return DeserializeBytes(storage, 0) }
var field2: Int32 { return DeserializeBytes(storage, 1) }
}
let y = Y(storage: [ 1, 0, 1, 0, 0 ])
println(y.field, y.field2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment