Module: RLP

Defined in:
lib/encode.rb,
lib/rlp-ruby.rb,
lib/core_ext/array.rb,
lib/core_ext/fixnum.rb

Defined Under Namespace

Modules: Encode, Extensions

Class Method Summary collapse

Class Method Details

.decode(data, pos) ⇒ Object



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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rlp-ruby.rb', line 17

def self.decode(data, pos)
  value = data[pos]
  RLP.log("Data: #{data}")
  result = []

  # Reading a single byte
  if value <= 0x7f
    RLP.log("<= 0x7f, reading 1 byte")
    RLP.log("=> Read: #{value}")
    return value, pos+1
  # Reading a string up to and including 55 bytes long 
  elsif value <= 0xb7
    start_at = pos + 1
    read_length = value - 0x80
    RLP.log("<= 0xb7, starting reading at the #{start_at}th byte and reading #{read_length} bytes")
    read_data = data[start_at..(start_at+read_length-1)]
    RLP.log("=> Read: #{read_data}")
    return read_data, (start_at + read_length)
  # Reading a string that is longer then 55 bytes
  elsif value <= 0xbf
    start_at = pos + 1
    read_length = value - 0xb7

    read_length_length = data[start_at..(start_at+read_length-1)].first
    RLP.log("<= 0xbf, starting reading at the #{start_at}th byte and reading #{read_length_length} bytes")
    read_data = data[(start_at+1)..read_length_length]
    RLP.log("=> Read: #{read_data}")

    return read_data, read_length_length
  # Reading a list that is up to (and including) 55 bytes long
  elsif value <= 0xf7
    amount = value - 0xc0
    RLP.log("<= 0x7f, starting reading at the #{start_at}th byte and reading #{amount} bytes")
    pos += 1
    i = 0
    while i < amount do
      decoded, prev_pos = decode(data,pos)
      result << decoded
      i += (prev_pos - pos)
      pos = prev_pos
    end
    RLP.log("=> Read: #{result}")

    return result,pos
  # Reading a list that is longer then 55 bytes
  elsif value <= 0xff
    length = value - 0xf7
    start_at = pos + 1
    read_length_length = data[start_at..start_at+length-1]

    pos = length + start_at
    RLP.log("<= 0xff, starting reading at the #{start_at}th byte and reading #{read_length_length} bytes")
    prev_pos = read_length_length
    i = 0
    while i < read_length_length.reverse_bytes do
      decoded,prev_pos = decode(data,pos)
      result << decoded
      i += (prev_pos - pos)
      pos = prev_pos
    end

    RLP.log("=> Read: #{result}")
    return result, pos
  end
end

.decoder(data) ⇒ Object



13
14
15
# File 'lib/rlp-ruby.rb', line 13

def self.decoder(data)
  return self.decode(data,0)[0]
end

.log(message) ⇒ Object



7
8
9
10
11
# File 'lib/rlp-ruby.rb', line 7

def self.log(message)
  if false
    puts(message)
  end
end