lib/bencoding/parser.rb in simonmenke-bencoding-0.0.1 vs lib/bencoding/parser.rb in simonmenke-bencoding-0.0.2
- old
+ new
@@ -1,33 +1,41 @@
module Bencoding
+ class ParseError < Exception ; end
+
module Parser
DICTIONARY_TOKEN = 100 # d # :nodoc:
LIST_TOKEN = 108 # l # :nodoc:
INTEGER_TOKEN = 105 # i # :nodoc:
TERMINATOR_TOKEN = 101 # e # :nodoc:
SEPERATOR_TOKEN = 58 # : # :nodoc:
+ ZERO_TOKEN = 48 # : # :nodoc:
+ NINE_TOKEN = 57 # : # :nodoc:
def load(io)
+ io = StringIO.new(io) if io.is_a? String
parse_anytype(io)
end
def parse_anytype(io, typechar=nil) # :nodoc:
typechar ||= io.getc
case typechar
when DICTIONARY_TOKEN then parse_dictionary(io)
when LIST_TOKEN then parse_list(io)
when INTEGER_TOKEN then parse_integer(io)
- else
+ when (ZERO_TOKEN..NINE_TOKEN)
io.ungetc typechar
parse_string(io)
+ else
+ raise ParseError
end
end
def parse_dictionary(io) # :nodoc:
dictionary = ::Hash.new
until (c = io.getc) == TERMINATOR_TOKEN
+ raise ParseError if c.nil?
io.ungetc c
key = parse_string(io)
val = parse_anytype(io)
dictionary[key] = val
end
@@ -35,18 +43,20 @@
end
def parse_list(io) # :nodoc:
list = ::Array.new
until (c = io.getc) == TERMINATOR_TOKEN
+ raise ParseError if c.nil?
val = parse_anytype(io, c)
list << val
end
list
end
def parse_integer(io, terminator=TERMINATOR_TOKEN) # :nodoc:
integer_string = ""
until (c = io.getc) == terminator
+ raise ParseError if c.nil?
integer_string << c.chr
end
integer_string.to_i
end