class Decoder

Decoder for a bencoded string

Public Class Methods

new(encoded) click to toggle source
# File lib/rbencode.rb, line 58
def initialize(encoded)
  @encoded_buffer = encoded.chars
end

Public Instance Methods

decode() click to toggle source
# File lib/rbencode.rb, line 62
def decode
  type = @encoded_buffer[0]
  if /[\d]/.match? type
    parse_string
  elsif type == 'i'
    parse_int
  elsif type == 'l'
    parse_array
  elsif type == 'd'
    parse_hash
  else
    raise MalformedData
  end
end
parse_array() click to toggle source
# File lib/rbencode.rb, line 96
def parse_array
  @encoded_buffer.shift  # drop the l
  array = []
  array.push(decode) while @encoded_buffer[0] != 'e'
  @encoded_buffer.shift  # drop the e
  array
end
parse_hash() click to toggle source
# File lib/rbencode.rb, line 104
def parse_hash
  @encoded_buffer.shift  # drop the l
  hash = {}
  while @encoded_buffer[0] != 'e'
    key = decode
    value = decode
    hash[key] = value
  end
  @encoded_buffer.shift  # drop the e
  hash
end
parse_int() click to toggle source
# File lib/rbencode.rb, line 88
def parse_int
  @encoded_buffer.shift  # drop the i
  int_chars = []
  int_chars.push(@encoded_buffer.shift) while @encoded_buffer[0] != 'e'
  @encoded_buffer.shift  # drop the e
  int_chars.join.to_i
end
parse_string() click to toggle source
# File lib/rbencode.rb, line 77
def parse_string
  count_chars = []
  count_chars.push(@encoded_buffer.shift) while @encoded_buffer[0] != ':'
  @encoded_buffer.shift  # Drop the colon
  count = count_chars.join.to_i

  raise MalformedData if @encoded_buffer.length < count

  @encoded_buffer.shift(count).join
end