Class: ListDeserializer::Deserializer

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyslim/list_deserializer.rb

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ Deserializer

Returns a new instance of Deserializer.



19
20
21
# File 'lib/rubyslim/list_deserializer.rb', line 19

def initialize(string)
  @string = string;
end

Instance Method Details

#consume_lengthObject

Consume the 6-digit length prefix, and return the length as an integer.



62
63
64
65
66
# File 'lib/rubyslim/list_deserializer.rb', line 62

def consume_length
  length = @string[@pos...@pos+6].to_i
  @pos += 7
  length
end

#deserializeObject



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
51
52
53
54
55
56
57
58
# File 'lib/rubyslim/list_deserializer.rb', line 23

def deserialize
  @pos = 1
  @list = []
  number_of_items = consume_length

  # For each item in the list
  number_of_items.times do
    length_of_item = consume_length
    item = @string[@pos...@pos+length_of_item]
    length_in_bytes = length_of_item

    until (item.jlength > length_of_item) do
      length_in_bytes += 1
      item = @string[@pos...@pos+length_in_bytes]
    end

    length_in_bytes -= 1
    item = @string[@pos...@pos+length_in_bytes]

    # Ensure the ':' list-termination character is found
    term_char = @string[@pos+length_in_bytes,1]
    if term_char != ':'
      raise SyntaxError.new("List termination character ':' not found" +
                           " (got '#{term_char}' instead)")
    end

    @pos += length_in_bytes+1
    begin
      sublist = ListDeserializer.deserialize(item)
      @list << sublist
    rescue ListDeserializer::SyntaxError
      @list << item
    end
  end
  @list
end