public
Created

reading length-prefixed streams

  • Download Gist
gistfile1.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.