Created
January 16, 2010 05:36
-
-
Save chrislewis/278668 to your computer and use it in GitHub Desktop.
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
| /* | |
| * Quick sketch of wrapper to aid in raw stream processing. | |
| * Source is nice, but it blocks in some cases (ie, client | |
| * socket input streams). While loops suck, so .... | |
| * | |
| * import MIO._ | |
| * val in: InputStream = .... | |
| * consume(in) until("\r\n\r\n") | |
| * | |
| * chris@thegodcode.net | |
| */ | |
| import java.io._ | |
| object StreamConsumer { | |
| def read(in: InputStream) = { | |
| val buf = new scala.collection.mutable.ArrayBuffer[Byte] | |
| var b = 0 | |
| while({b = in.read; b} != -1) { | |
| buf += b.toByte | |
| } | |
| buf.toArray | |
| } | |
| def read(in: InputStream, byteSeq: Seq[Byte]) = { | |
| val buf = new scala.collection.mutable.ArrayBuffer[Byte] | |
| var stillSearching = true | |
| var b = 0 | |
| while({b = in.read; b} != -1 && stillSearching) { | |
| buf += b.toByte | |
| stillSearching = ! (buf.size >= byteSeq.size && byteSeq.equalsWith(buf.drop(buf.size - byteSeq.size).toArray) { _ == _ }) | |
| } | |
| buf.toArray | |
| } | |
| } | |
| class StreamConsumer(in: InputStream) { | |
| def fully = StreamConsumer.read(in) | |
| def until(byteSeq: Seq[Byte]) = StreamConsumer.read(in, byteSeq) | |
| def until(seq: String): String = new String(until(seq.getBytes).toArray) | |
| } | |
| object MIO { | |
| def consume(in: InputStream) = new StreamConsumer(in) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment