#codec #decoding #bencodex

bin+lib bencodex-rs

The Rust implementation of Bencodex

7 releases (breaking)

0.5.0 Jul 4, 2024
0.4.0 Jun 28, 2024
0.3.1 Nov 3, 2021
0.2.0 Jan 9, 2021
0.0.1 Jan 2, 2021

#501 in Encoding

MIT license

66KB
1.5K SLoC

bencodex-rs

build codecov Docs-rs

The Rust implementation of Bencodex.

  • Correctness - Implement Bencodex spec and passed tests with its testsuites.
  • Bencodex JSON - Support encoding Bencodex to JSON and decoding JSON to Bencodex.
  • Feature flags - Support json, json-cli feature flags to minimize binary size in use.

Bencodex JSON feature

bencodex-rs implements Bencodex JSON feature, encoding and decoding both.

To use Bencodex JSON feature, you should enable json feature.

bencodex-rs = { version = "<VERSION>", features = ["json"] }

Encoding to JSON

To encode from Bencodex to JSON, you can use to_json function.

use bencodex::{ BencodexValue, json::to_json };

let json = to_json(&BencodexValue::Null);
println!("{}", json);

There are two ways to encode BencodexValue::Binary type, Hex and Base64. You can choose one way with bencodex::json::BinaryEncoding. And you can pass it with bencodex::json::JsonEncodeOptions to bencodex::json::to_json_with_options.

use bencodex::BencodexValue;
use bencodex::json::{ BinaryEncoding, JsonEncodeOptions, to_json_with_options };

let json = to_json_with_options(&BencodexValue::Null, JsonEncodeOptions {
  binary_encoding: BinaryEncoding::Base64,
});
println!("{}", json);

Decoding from JSON

To decode from JSON to Bencodex, you can use from_json_string and from_json function.

// from_json_string
use bencodex::{ BencodexValue, json::from_json_string };

let result = from_json_string("null");
assert!(result.is_ok());
assert_eq!(result.unwrap(), BencodexValue::Null);
// from_json
use serde_json::from_str;
use bencodex::{ BencodexValue, json::from_json };

let json = from_str("null").unwrap();
let result = from_json(&json);
assert!(result.is_ok());
assert_eq!(result.unwrap(), BencodexValue::Null);

CLI Tool

Also, it provides a CLI tool to encode from Bencodex to JSON and to decode from JSON to Bencodex. You can install it with json-cli feature like the below line:

cargo install bencodex-rs --features json-cli

You can use like the below:

# encode
$ echo -n 'n' | bencodex
null
$ echo -n 'i123e' | bencodex
"123"
$ echo -n '1:\x12' | bencodex
"0x12"
$ echo -n '1:\x12' | bencodex --base64
"b64:Eg=="

# decode
$ echo -n '"123"' | bencodex -d
123
$ echo -n 'null' | bencodex -d
n

Dependencies

~0.8–1.5MB
~30K SLoC