Skip to content

Instantly share code, notes, and snippets.

@rctay
Created April 7, 2012 17:24
Show Gist options
  • Save rctay/2330613 to your computer and use it in GitHub Desktop.
Save rctay/2330613 to your computer and use it in GitHub Desktop.
BufferedReader, but better
import java.io
import collection.mutable
class PushbackBufferedStream(in: io.InputStream, lineSize: Int = 30, bufSize: Int = 4096)
extends io.PushbackInputStream(in, bufSize) {
def readLine(): String = {
val read_buf = new Array[Byte](bufSize)
val line_buf = new mutable.ArrayBuffer[Byte](lineSize * 2)
def loop(sz: Int): Unit = {
val r = read(read_buf, 0, sz)
val buf = read_buf.slice(0, r)
var index = buf.indexOf('\n')
if (index == -1) {
line_buf ++= buf
return loop(bufSize)
}
if (index == 0)
return ()
line_buf ++= buf.slice(0, index)
// +1 to skip '\n'
unread(buf, index + 1, r - (index + 1))
}
loop(if (pos == bufSize) bufSize else bufSize - pos)
if (line_buf.size == 0)
return ""
var upto = line_buf.size-1
if (line_buf(upto) != '\r')
upto += 1
return new String(line_buf.slice(0, upto).toArray)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment