Class: FPM::Fry::StreamParser

Inherits:
Object
  • Object
show all
Defined in:
lib/fpm/fry/stream_parser.rb

Defined Under Namespace

Classes: Instance, ShortRead

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(out, err) ⇒ StreamParser

Returns a new instance of StreamParser.



64
65
66
67
68
69
# File 'lib/fpm/fry/stream_parser.rb', line 64

def initialize(out, err)
  @out, @err = out, err
  @state = :null
  @left = 0
  @streams = { 1 => out, 2 => err }
end

Instance Attribute Details

#errObject (readonly)

Returns the value of attribute err.



62
63
64
# File 'lib/fpm/fry/stream_parser.rb', line 62

def err
  @err
end

#outObject (readonly)

Returns the value of attribute out.



62
63
64
# File 'lib/fpm/fry/stream_parser.rb', line 62

def out
  @out
end

#streamsObject (readonly)

Returns the value of attribute streams.



62
63
64
# File 'lib/fpm/fry/stream_parser.rb', line 62

def streams
  @streams
end

Instance Method Details

#new(stack) ⇒ Object



71
72
73
# File 'lib/fpm/fry/stream_parser.rb', line 71

def new(stack)
  Instance.new(stack, self)
end

#parse(socket) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/fpm/fry/stream_parser.rb', line 75

def parse(socket)
  loop do
    type = read_exactly(socket,4){|part|
      if part.bytesize == 0
        return
      else
        raise ShortRead
      end
    }.unpack("c".freeze)[0]
    stream = streams.fetch(type){ raise ArgumentError, "Wrong stream type: #{type}"}
    len  = read_exactly(socket,4).unpack('I>')[0]
    while len > 0
      chunk = socket.read([64,len].min)
      raise ShortRead if chunk.nil?
      len -= chunk.bytesize
      stream.write(chunk)
    end
  end
end

#parse_chunked(socket) ⇒ Object



113
114
115
116
117
118
119
120
121
122
# File 'lib/fpm/fry/stream_parser.rb', line 113

def parse_chunked(socket)
  loop do
    line = socket.readline
    chunk_size = line.chomp.to_i(16)
    break if chunk_size.zero?
    chunk = socket.read(chunk_size)
    parse(StringIO.new(chunk))
    line = socket.readline
  end
end

#read_exactly(socket, len) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/fpm/fry/stream_parser.rb', line 95

def read_exactly(socket, len)
  buf = ""
  left = len
  while left != 0
    read = socket.read(left)
    if read.nil?
      if block_given?
        yield buf
      else
        raise ShortRead
      end
    end
    buf << read
    left = len - buf.bytesize
  end
  return buf
end