-
-
Save seanlilmateus/f8cf55d3fdb84c9b5c0c 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
struct InputStreamGenerator : Generator { | |
var inputStream : NSInputStream | |
var chunkSize : Int | |
init(inputStream : NSInputStream, chunkSize : Int) { | |
self.inputStream = inputStream | |
self.chunkSize = chunkSize | |
} | |
func next() -> SequenceOf<UInt8>? { | |
var buffer = UInt8[](count: chunkSize, repeatedValue: 0) | |
println("performing read of \(chunkSize) bytes") | |
var length = inputStream.read(&buffer, maxLength: chunkSize) | |
if (length > 0) { | |
// Split to separate lines to point out the Range and Slice types | |
// Hopefully there is sugar i'm not aware of for slicing | |
let range = Range<Int>(start: 0, end: length) | |
let slice : Slice<UInt8> = buffer[range] | |
let sequenceOf = SequenceOf<UInt8>(slice) | |
return Optional.Some(sequenceOf) | |
} else { | |
return Optional.None | |
} | |
} | |
} | |
struct InputStreamSequence : Sequence { | |
var inputStream : NSInputStream | |
var chunkSize : Int | |
init(inputStream : NSInputStream, chunkSize : Int) { | |
self.inputStream = inputStream | |
self.chunkSize = chunkSize | |
} | |
func generate() -> InputStreamGenerator { | |
return InputStreamGenerator(inputStream: self.inputStream, chunkSize: self.chunkSize) | |
} | |
} | |
extension NSInputStream : Sequence { | |
typealias GeneratorType = GeneratorOf<SequenceOf<UInt8>> | |
func sequenceWithReadLength(chunkSize: Int) -> SequenceOf<SequenceOf<UInt8>> { | |
return SequenceOf<SequenceOf<UInt8>>(InputStreamSequence(inputStream: self, chunkSize: chunkSize)) | |
} | |
func generate() -> GeneratorOf<SequenceOf<UInt8>> { | |
return self.sequenceWithReadLength(4096).generate() | |
} | |
} | |
// basic usage | |
var data : NSData = "Are we not drawn onward to new era?".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) | |
var stream : NSInputStream = NSInputStream(data: data) | |
stream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) | |
stream.open() | |
for chunk : SequenceOf<UInt8> in stream.sequenceWithReadLength(2) { | |
for byte in chunk { | |
println(byte) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment