Class: Plux::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/plux/parser.rb

Constant Summary collapse

SYSTEM =
36
SEPERATOR =
'.'.freeze
STREAM_MAX_LEN =
4096
LAST_MSG =
''.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



9
10
11
# File 'lib/plux/parser.rb', line 9

def initialize
  @broken = ''
end

Class Method Details

.encode(msg) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/plux/parser.rb', line 52

def self.encode(msg)
  len = msg.length.to_s(SYSTEM)

  msg = "#{len}#{SEPERATOR}#{msg}"
  len = msg.length

  return [msg] if len < STREAM_MAX_LEN

  div, mod = len.divmod(STREAM_MAX_LEN)
  (mod > 0 ? (div + 1) : div).times.map do |start|
    msg[start * STREAM_MAX_LEN, STREAM_MAX_LEN]
  end
end

Instance Method Details

#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