Skip to content

Instantly share code, notes, and snippets.

@mingsai
Forked from ishikawa/NSStream.swift
Created February 12, 2016 19:40
Show Gist options
  • Save mingsai/2f782b2bc9d11634cd6e to your computer and use it in GitHub Desktop.
Save mingsai/2f782b2bc9d11634cd6e to your computer and use it in GitHub Desktop.
Generic read/write method
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