Class: WebSocket::Driver::StreamReader

Inherits:
Object
  • Object
show all
Defined in:
lib/websocket/driver/stream_reader.rb

Constant Summary collapse

MINIMUM_AUTOMATIC_PRUNE_OFFSET =

Try to minimise the number of reallocations done:

128

Instance Method Summary collapse

Constructor Details

#initializeStreamReader

Returns a new instance of StreamReader.



8
9
10
11
# File 'lib/websocket/driver/stream_reader.rb', line 8

def initialize
  @buffer = String.new('').force_encoding(BINARY)
  @offset = 0
end

Instance Method Details

#each_byteObject



30
31
32
33
34
35
36
37
# File 'lib/websocket/driver/stream_reader.rb', line 30

def each_byte
  prune

  @buffer.each_byte do |octet|
    @offset += 1
    yield octet
  end
end

#put(chunk) ⇒ Object



13
14
15
16
# File 'lib/websocket/driver/stream_reader.rb', line 13

def put(chunk)
  return unless chunk and chunk.bytesize > 0
  @buffer << chunk.force_encoding(BINARY)
end

#read(length) ⇒ Object

Read bytes from the data:



19
20
21
22
23
24
25
26
27
28
# File 'lib/websocket/driver/stream_reader.rb', line 19

def read(length)
  return nil if (@offset + length) > @buffer.bytesize

  chunk = @buffer.byteslice(@offset, length)
  @offset += chunk.bytesize

  prune if @offset > MINIMUM_AUTOMATIC_PRUNE_OFFSET

  return chunk
end