Class: Straycall::Reporter::Protocol::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/straycall/reporter/protocol.rb

Constant Summary collapse

LIMIT =
64 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Reader

Returns a new instance of Reader.



11
12
13
14
15
# File 'lib/straycall/reporter/protocol.rb', line 11

def initialize(socket)
  @socket = socket
  @buffer = String.new(capacity: LIMIT)
  @chunk = String.new(capacity: 4096)
end

Instance Method Details

#read(timeout: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/straycall/reporter/protocol.rb', line 17

def read(timeout: nil)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout if timeout
  loop do
    if (newline = @buffer.index("\n"))
      return @buffer.slice!(0, newline + 1)
    end
    if deadline
      remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
      return if remaining <= 0 || !IO.select([@socket], nil, nil, remaining)
    end

    @socket.readpartial(4096, @chunk)
    raise IOError, "reporter message exceeds #{LIMIT} bytes" if @buffer.bytesize + @chunk.bytesize > LIMIT

    @buffer << @chunk
  end
rescue EOFError
  nil
end