Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created January 12, 2012 02:44
Show Gist options
  • Save karlseguin/1598236 to your computer and use it in GitHub Desktop.
Save karlseguin/1598236 to your computer and use it in GitHub Desktop.
reading length-prefixed streams
class StreamReader
constructor: (@callback) ->
read: (buffer) ->
unless @buffer?
if this.initialize(buffer)
@partial = null
@partialLength = 0
else
return
toRead = @buffer.length - @read
toRead = buffer.length if toRead > buffer.length
buffer.copy(@buffer, @read, 0, toRead)
@read += toRead
if @read == @buffer.length
@callback(new Buffer(@buffer))
@buffer = null
if toRead < buffer.length
this.read(buffer.slice(toRead))
initialize: (buffer) ->
if @partial?
if @partialLength + buffer.length >= 4
buffer.copy(@partial, @partialLength, 0, 4 - @partialLength)
@buffer = new Buffer(@partial.readInt32LE(0))
@partial.copy(@buffer, 0, 0, @partialLength)
@read = @partialLength
return true
buffer.copy(@partial, @partialLength, 0, buffer.length)
@partialLength += buffer.length
return false
if buffer.length < 4
@partial = new Buffer(4) #todo: reduce allocation/fragementation
buffer.copy(@partial)
@partialLength = buffer.length
return false
@buffer = new Buffer(buffer.readInt32LE(0))
@read = 0
return true
debug: ->
console.log("partial is ", @partial)
console.log("partial length is %d", @partialLength)
console.log("buffer is ", @buffer)
exports.StreamReader = StreamReader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment