-
-
Save mingsai/2f782b2bc9d11634cd6e 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