Module: BEncode

Defined in:
lib/bencode.rb,
lib/bencode/decode.rb,
lib/bencode/parser.rb

Overview

Support for loading and dumping bencoded data.

See BEncode.load and BEncode.dump.

Defined Under Namespace

Classes: DecodeError, EncodeError, Parser

Constant Summary collapse

VERSION =
"0.8.2"

Class Method Summary collapse

Class Method Details

.dump(obj) ⇒ String

Encodes the Ruby object obj into a bencoded string.

Parameters:

Returns:

  • (String)

    a bencoded string

Raises:

  • (EncodeError)

    if obj is not a supported object type



10
11
12
# File 'lib/bencode/decode.rb', line 10

def self.dump(obj)
  obj.bencode
end

.load(str, opts = {}) ⇒ Object

Decodes str into a Ruby structure.

Parameters:

  • str (String)

    a bencoded string

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :ignore_trailing_junk (Boolean) — default: false

    whether to ignore invalid bencode at the end of str

Returns:

Raises:



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

def self.load(str, opts = {})
  scanner = BEncode::Parser.new(str)
  obj = scanner.parse!
  raise BEncode::DecodeError unless (opts[:ignore_trailing_junk] || scanner.eos?)
  obj
end

.load_file(path, opts = {}) ⇒ Object

Decodes the file located at path.

Parameters:

  • path (String)

    path to the bencoded file

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :ignore_trailing_junk (Boolean) — default: false

    whether to ignore invalid bencode at the end of str

Returns:



33
34
35
36
37
# File 'lib/bencode/decode.rb', line 33

def self.load_file(path, opts = {})
  File.open(path, 'rb') do |io|
    load(io, opts)
  end
end