Skip to content

Commit

Permalink
feat: implement bencodex JSON format
Browse files Browse the repository at this point in the history
  • Loading branch information
moreal committed Jun 9, 2024
1 parent 3e22fc8 commit 1feca12
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 4 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ name = "bencodex"
itertools = "0.10.0"
num-traits = "0.2.14"
num-bigint = "0.3"
hex = "0.4.3"

[dev-dependencies]
yaml-rust = "0.4.4"
Expand Down
2 changes: 1 addition & 1 deletion bencodex/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ fn main() {
}
};

println!("{:?}", decoded);
println!("{}", decoded);
}
81 changes: 78 additions & 3 deletions src/codec/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use num_bigint::BigInt;
use std::collections::BTreeMap;
use std::{collections::BTreeMap, fmt::{Debug, Display}};

/// The type alias of `BTreepMap<BencodexKey, BencodexValue>` to reduce code size.
///
Expand Down Expand Up @@ -40,7 +40,7 @@ pub type BencodexList = Vec<BencodexValue>;
/// ```
pub const BENCODEX_NULL: BencodexValue = BencodexValue::Null;

#[derive(PartialEq, Debug, Clone)]
#[derive(PartialEq, Clone)]
pub enum BencodexValue {
Binary(Vec<u8>),
Text(String),
Expand All @@ -51,12 +51,75 @@ pub enum BencodexValue {
Null,
}

#[derive(PartialEq, Eq, PartialOrd, Debug, Clone, Ord)]
#[derive(PartialEq, Eq, PartialOrd, Clone, Ord)]
pub enum BencodexKey {
Binary(Vec<u8>),
Text(String),
}

impl Debug for BencodexValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Binary(arg0) => write!(f, "{:?}", BencodexKey::from(arg0)),
Self::Text(arg0) => write!(f, "{:?}", BencodexKey::from(arg0)),
Self::Boolean(arg0) => f.write_str(if *arg0 { "true" } else { "false" }),
Self::Number(arg0) => f.write_str(&arg0.to_string()),
Self::List(arg0) => f.debug_list().entries(arg0.iter()).finish(),
Self::Dictionary(arg0) => f.debug_map().entries(arg0.iter()).finish(),
Self::Null => write!(f, "null"),
}
}
}

impl Display for BencodexValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Binary(arg0) => f.write_fmt(format_args!("{}", BencodexKey::from(arg0))),
Self::Text(arg0) => f.write_fmt(format_args!("{}", BencodexKey::from(arg0))),
Self::Boolean(arg0) => f.write_str(if *arg0 { "true" } else { "false" }),
Self::Number(arg0) => f.write_str(&arg0.to_string()),
Self::List(arg0) => {
f.write_str("[")?;
for (i, item) in arg0.iter().enumerate() {
if i == arg0.len() - 1 {
write!(f, "{}", item)?;
} else {
write!(f, "{},", item)?;
}
}
f.write_str("]")
},
Self::Dictionary(arg0) => {
f.write_str("{")?;
let mut iter = arg0.iter().peekable();
while let Some((key, value)) = iter.next() {
write!(f, "{}:{}", key, value)?;
if iter.peek().is_some() {
f.write_str(",")?;
}
}
f.write_str("}")
},
Self::Null => write!(f, "null"),
}
}
}

impl Debug for BencodexKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{}", self))
}
}

impl Display for BencodexKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Binary(arg0) => write!(f, "\"0x{}\"", hex::encode(arg0)),
Self::Text(arg0) => write!(f, "\"\u{FEFF}{}\"", arg0),
}
}
}

impl From<&str> for BencodexKey {
fn from(val: &str) -> Self {
BencodexKey::Text(val.to_string())
Expand All @@ -69,12 +132,24 @@ impl From<String> for BencodexKey {
}
}

impl From<&String> for BencodexKey {
fn from(val: &String) -> Self {
BencodexKey::Text(val.clone())
}
}

impl From<Vec<u8>> for BencodexKey {
fn from(val: Vec<u8>) -> Self {
BencodexKey::Binary(val)
}
}

impl From<&Vec<u8>> for BencodexKey {
fn from(val: &Vec<u8>) -> Self {
BencodexKey::Binary(val.clone())
}
}

impl From<&[u8]> for BencodexKey {
fn from(val: &[u8]) -> Self {
BencodexKey::Binary(val.to_vec())
Expand Down

0 comments on commit 1feca12

Please sign in to comment.