Skip to content

The Rust implementation of Bencodex

License

Notifications You must be signed in to change notification settings

moreal/bencodex-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

993572c · Jan 30, 2025
Jan 30, 2025
Jul 3, 2024
Jan 30, 2025
Jan 2, 2021
Jun 29, 2024
Jul 3, 2024
Jul 4, 2024
Jun 9, 2024
Dec 30, 2020
Jul 4, 2024
Jan 30, 2025
Jan 30, 2025
Dec 29, 2020
Jan 30, 2025

Repository files navigation

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

About

The Rust implementation of Bencodex

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages