Module: BEncode

Defined in:
lib/bencode.rb,
lib/bencode/list.rb,
lib/bencode/parser.rb,
lib/bencode/string.rb,
lib/bencode/integer.rb,
lib/bencode/dictionary.rb

Defined Under Namespace

Modules: Dictionary, Integer, List, Parser, String Classes: BEncodeError

Class Method Summary collapse

Class Method Details

.decode(string) ⇒ ::String, ...

This method decodes a bencoded string.

BEncode.decode("6:string") #=> "string"

Parameters:

  • string (::String)

    the bencoded string to decode

Returns:

  • (::String, ::Integer, ::Hash, ::Array)

    the decoded object



21
22
23
24
# File 'lib/bencode.rb', line 21

def decode(string)
  scanner = StringScanner.new(string)
  Parser.parse_object(scanner) or raise BEncodeError, "Invalid bencoding"
end

.decode_file(file) ⇒ ::String, ...

This method decodes a bencoded file.

BEncode.decode_file("simple.torrent") #=> "d8:announce32:http://www..."

Parameters:

  • file (::String)

    the file to decode

Returns:

  • (::String, ::Integer, ::Hash, ::Array)

    the decoded object



32
33
34
# File 'lib/bencode.rb', line 32

def decode_file(file)
  decode(File.open(file, 'rb') {|f| f.read})
end

.encode(object) ⇒ ::String

This method encodes a bencoded object.

BEncode.encode("string") #=> "6:string"

Parameters:

  • object (#bencode)

    the object to encode

Returns:

  • (::String)

    the bencoded object



42
43
44
# File 'lib/bencode.rb', line 42

def encode(object)
  object.bencode
end

.encode_file(file, object) ⇒ Object

This method encodes a bencoded object.

BEncode.encode("string") #=> "6:string"

Parameters:

  • file (::String)

    the file to write the bencoded object to

  • object (#bencode)

    the object to encode



52
53
54
# File 'lib/bencode.rb', line 52

def encode_file(file, object)
  File.open(file, 'wb') {|f| f.write encode(object)}
end