Created
July 11, 2014 00:45
-
-
Save mikeash/0f1db7b5d8d9ece1f61b to your computer and use it in GitHub Desktop.
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
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