Class: Kronk::Player::InputReader

Inherits:
Object
  • Object
show all
Defined in:
lib/kronk/player/input_reader.rb

Overview

Reads an IO stream and parses it with the given parser. Parser must respond to the following:

  • start_new?(line) - Returns true when line is the beginning of a new http request.

  • parse(str) - Parses the raw string into value Kronk#request options.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string_or_io, parser = nil) ⇒ InputReader

Returns a new instance of InputReader.



14
15
16
17
18
19
20
# File 'lib/kronk/player/input_reader.rb', line 14

def initialize string_or_io, parser=nil
  @io_buf = ""
  @buffer = []
  @parser = parser || Kronk::Player::RequestParser
  @io     = string_or_io
  @io     = StringIO.new(@io) if String === @io
end

Instance Attribute Details

#bufferObject

Returns the value of attribute buffer.



12
13
14
# File 'lib/kronk/player/input_reader.rb', line 12

def buffer
  @buffer
end

#ioObject

Returns the value of attribute io.



12
13
14
# File 'lib/kronk/player/input_reader.rb', line 12

def io
  @io
end

#parserObject

Returns the value of attribute parser.



12
13
14
# File 'lib/kronk/player/input_reader.rb', line 12

def parser
  @parser
end

Instance Method Details

#eof?Boolean

Returns true if there is no more input to read from.

Returns:

  • (Boolean)


87
88
89
# File 'lib/kronk/player/input_reader.rb', line 87

def eof?
  !@io || (@io.closed? || @io.eof?) && @buffer.empty?
end

#get_nextObject

Parse the next request in the IO instance.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/kronk/player/input_reader.rb', line 26

def get_next
  return if eof?

  @buffer << gets if @buffer.empty?

  until @io.eof? && @io_buf.empty?
    line = gets
    next unless line

    if @parser.start_new?(line) || @buffer.empty?
      @buffer << line
      break
    else
      @buffer.last << line
    end
  end

  return if @buffer.empty?
  @parser.parse(@buffer.slice!(0)) || self.get_next
end

#getsObject

Read one line from @io, thread-non-blocking.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/kronk/player/input_reader.rb', line 51

def gets
  return @io.gets if StringIO === @io

  next_line = io_buf_line
  return next_line if next_line

  until @io.eof?
    selected, = select [@io], nil, nil, 0.05

    if selected.nil? || selected.empty?
      Thread.pass
      next
    end

    @io_buf << @io.readpartial(1024)

    next_line = io_buf_line
    return next_line if next_line
  end
end

#io_buf_lineObject

Get the first line of the io buffer.



76
77
78
79
80
81
# File 'lib/kronk/player/input_reader.rb', line 76

def io_buf_line
  index = @io_buf.index "\n"
  return unless index

  @io_buf.slice!(0..index)
end