Method: Plux::Parser#decode

Defined in:
lib/plux/parser.rb

#decode(stream) ⇒ Object



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
# File 'lib/plux/parser.rb', line 13

def decode(stream)
  stream = @broken.concat(stream)
  result = []

  start = 0
  pending = stream.length

  until start >= pending
    sep_idx = stream.index(SEPERATOR, start)

    unless sep_idx
      len_str = stream[start, pending]
      @broken.clear
      @broken.concat(len_str)
      return result
    end

    len_str = stream[start, sep_idx - start]
    est_len = len_str.to_i(SYSTEM)
    start = sep_idx + 1
    msg = stream[start, est_len]
    act_len = msg.length

    if act_len < est_len
      @broken.clear
      @broken.concat(len_str)
      @broken.concat(SEPERATOR)
      @broken.concat(msg)
      return result
    end

    result << msg
    start += act_len
  end

  @broken.clear
  result
end