Module: Bencoding::Parser

Extended by:
Parser
Included in:
Parser
Defined in:
lib/bencoding/parser.rb

Constant Summary collapse

DICTIONARY_TOKEN =

d # :nodoc:

100
LIST_TOKEN =

l # :nodoc:

108
INTEGER_TOKEN =

i # :nodoc:

105
TERMINATOR_TOKEN =

e # :nodoc:

101
SEPERATOR_TOKEN =

: # :nodoc:

58
ZERO_TOKEN =

: # :nodoc:

48
NINE_TOKEN =

: # :nodoc:

57

Instance Method Summary collapse

Instance Method Details

#load(io) ⇒ Object



14
15
16
17
# File 'lib/bencoding/parser.rb', line 14

def load(io)
  io = StringIO.new(io) if io.is_a? String
  parse_anytype(io)
end

#parse_anytype(io, typechar = nil) ⇒ Object

:nodoc:



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/bencoding/parser.rb', line 19

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)
  when (ZERO_TOKEN..NINE_TOKEN)
    io.ungetc typechar
    parse_string(io)
  else
    raise ParseError
  end
end

#parse_dictionary(io) ⇒ Object

:nodoc:



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bencoding/parser.rb', line 33

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
  dictionary
end

#parse_integer(io, terminator = TERMINATOR_TOKEN) ⇒ Object

:nodoc:



55
56
57
58
59
60
61
62
# File 'lib/bencoding/parser.rb', line 55

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

#parse_list(io) ⇒ Object

:nodoc:



45
46
47
48
49
50
51
52
53
# File 'lib/bencoding/parser.rb', line 45

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

#parse_string(io) ⇒ Object

:nodoc:



64
65
66
67
# File 'lib/bencoding/parser.rb', line 64

def parse_string(io) # :nodoc:
  length = parse_integer(io, SEPERATOR_TOKEN)
  io.read(length)
end