Module BCodec
In: lib/bcodec/decode.rb
lib/bcodec/encode.rb
lib/bcodec.rb
 bcodec - Ruby library to decode/encode bencoded data
 Copyright (C) 2006,2007 Thomas <tochiro+bcodecNO@SPAMrubyforge.org>

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see <http://www.gnu.org/licenses/>.

bcodec

Description

bcodec is a Ruby library for encoding and decoding bencoded data used in the BitTorrent protocol (see www.bittorrent.org/).

Examples

Encoding

 require 'rubygems'
 require 'bcodec'
 include 'BCodec'

 encode("abcd")             # returns "4:abcd"
 encode(1000)               # returns "i1000e"
 encode([1,2,3])            # returns "li1ei2ei3ee"
 encode({"key" => "value"}) # returns "d3:key5:valuee"

Decoding

 require 'stringio'
 require 'rubygems'
 require 'bcodec'
 include 'BCodec'

 decode(StringIO.new("4:abcd"))      # returns "abcd"
 decode(StringIO.new("i666e"))       # returns 666
 decode(StringIO.new("l3abci666ee")) # returns [ "abc", 666 ]
 decode(StringIO.new("d3abci666ee")) # returns { "abc" => 666 }

As you probably noticed the BCodec#decode function takes an IO-like object, so if you have a String you‘ll have to wrap it in a StringIO.

Decode a .torrent file:

To decode a BitTorrent metafile you could do something like:

 hash = BCodec.decode(open("some.torrent", "r"))

See www.bittorrent.org/protocol.html for more information about the protocol.

That‘s basically all there is too it :-)

Methods

decode   encode  

Classes and Modules

Class BCodec::InvalidDataType
Class BCodec::InvalidInteger
Class BCodec::InvalidKey
Class BCodec::InvalidString
Class BCodec::UnknownData

Public Instance methods

Decodes bencoded data from an IO-like object (IO, File, StringIO or similar)

Returns the decoded object which is either of these: Array, Integer (Fixnum or Bignum), Hash or String

Encodes a Ruby object which must be either of these: Array, Integer (Fixnum or Bignum), Hash or String

Returns the encoded object(s) as a String

[Validate]