Crates.io | bencodex-rs |
lib.rs | bencodex-rs |
version | 0.5.0 |
source | src |
created_at | 2021-01-02 17:10:37.785908 |
updated_at | 2024-07-04 01:15:38.546808 |
description | The Rust implementation of Bencodex |
homepage | https://github.com/bencodex/bencodex-rs |
repository | https://github.com/bencodex/bencodex-rs |
max_upload_size | |
id | 330653 |
size | 141,558 |
The Rust implementation of Bencodex.
json
, json-cli
feature flags to minimize binary size in use.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"] }
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);
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);
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