Last active
February 12, 2016 19:40
-
-
Save ishikawa/8320da3dcc8814c8b83a to your computer and use it in GitHub Desktop.
Generic read/write method
This file contains hidden or 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
extension NSInputStream { | |
func read<T : Integer>() -> T? { | |
var buffer : T = 0 | |
let n = withUnsafePointer(&buffer) { (p) in | |
self.read(UnsafePointer<UInt8>(p), maxLength: sizeof(T)) | |
} | |
if n > 0 { | |
assert(n == sizeof(T), "read length must be sizeof(T)") | |
return buffer | |
} else { | |
return nil | |
} | |
} | |
} | |
extension NSOutputStream { | |
func write<T : Integer>(var source: T) -> Int { | |
return withUnsafePointer(&source) { (p) in | |
self.write(ConstUnsafePointer<UInt8>(p), maxLength: sizeof(T)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment