Module: Bencode
- Defined in:
- lib/bencode.rb
Class Method Summary collapse
-
.dump(obj) ⇒ Object
Bencodes
obj
. -
.load(str) ⇒ Object
Bdecodes
str
. -
.load_file(path) ⇒ Object
Bdecodes the file located at
path
. -
.parse(scanner) ⇒ Object
:nodoc:.
Class Method Details
.dump(obj) ⇒ Object
Bencodes obj
183 184 185 |
# File 'lib/bencode.rb', line 183 def dump(obj) obj.bencode end |
.load(str) ⇒ Object
Bdecodes str
188 189 190 191 192 193 194 195 |
# File 'lib/bencode.rb', line 188 def load(str) require 'strscan' scanner = StringScanner.new(str) obj = parse(scanner) raise BdecodeError unless scanner.eos? return obj end |
.load_file(path) ⇒ Object
Bdecodes the file located at path
198 199 200 |
# File 'lib/bencode.rb', line 198 def load_file(path) load(File.open(path).read) end |
.parse(scanner) ⇒ Object
:nodoc:
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/bencode.rb', line 202 def parse(scanner) # :nodoc: case token = scanner.scan(/[ild]|\d+:|\s/) when nil raise BdecodeError when "i" number = scanner.scan(/0|(?:-?[1-9][0-9]*)/) raise BdecodeError unless number and scanner.scan(/e/) return number.to_i when "l" ary = [] until scanner.peek(1) == "e" ary.push(parse(scanner)) end scanner.pos += 1 return ary when "d" hsh = {} until scanner.peek(1) == "e" key, value = parse(scanner), parse(scanner) raise BdecodeError, "key must be a string" unless key.is_a? String hsh.store(key, value) end scanner.pos += 1 return hsh when /\d+:/ length = token.chop.to_i str = scanner.peek(length) scanner.pos += length return str when /\s/ nil else raise BdecodeError end end |