Class: Decoder
- Inherits:
-
Object
- Object
- Decoder
- Defined in:
- lib/rbencode.rb
Overview
Decoder for a bencoded string
Instance Method Summary collapse
- #decode ⇒ Object
-
#initialize(encoded) ⇒ Decoder
constructor
A new instance of Decoder.
- #parse_array ⇒ Object
- #parse_hash ⇒ Object
- #parse_int ⇒ Object
- #parse_string ⇒ Object
Constructor Details
#initialize(encoded) ⇒ Decoder
Returns a new instance of Decoder.
58 59 60 |
# File 'lib/rbencode.rb', line 58 def initialize(encoded) @encoded_buffer = encoded.chars end |
Instance Method Details
#decode ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# 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 ⇒ Object
96 97 98 99 100 101 102 |
# 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 ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 |
# 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 ⇒ Object
88 89 90 91 92 93 94 |
# 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 ⇒ Object
77 78 79 80 81 82 83 84 85 86 |
# 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 |