#bencode #codec #contrib #binary-encoding #library #message-parser

torrust-tracker-contrib-bencode

(contrib) Efficient decoding and encoding for bencode

5 releases (1 stable)

3.0.0 Oct 3, 2024
3.0.0-alpha.11 Sep 18, 2023
3.0.0-alpha.10 Sep 16, 2023
3.0.0-alpha.8 Sep 15, 2023

#484 in Encoding

Download history 8/week @ 2024-07-23 3/week @ 2024-07-30 11/week @ 2024-09-24 164/week @ 2024-10-01 8/week @ 2024-10-08

260 downloads per month
Used in torrust-tracker

Apache-2.0

59KB
1K SLoC

Bencode

This library allows for the creation and parsing of bencode encodings.

Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed).


lib.rs:

Library for parsing and converting bencoded data.

Examples

Decoding bencoded data:

    extern crate bencode;

    use bencode::{BencodeRef, BRefAccess, BDecodeOpt};

    fn main() {
        let data = b"d12:lucky_numberi7ee"; // cspell:disable-line
        let bencode = BencodeRef::decode(data, BDecodeOpt::default()).unwrap();

        assert_eq!(7, bencode.dict().unwrap().lookup("lucky_number".as_bytes())
            .unwrap().int().unwrap());
    }

Encoding bencoded data:

    #[macro_use]
    extern crate bencode;

    fn main() {
        let message = (ben_map!{
            "lucky_number" => ben_int!(7),
            "lucky_string" => ben_bytes!("7")
        }).encode();

        let data = b"d12:lucky_numberi7e12:lucky_string1:7e"; // cspell:disable-line
        assert_eq!(&data[..], &message[..]);
    }

Dependencies

~250–710KB
~17K SLoC