From 7556471090352d534720d06b7d36e22a4521427a Mon Sep 17 00:00:00 2001 From: Faerbit Date: Sun, 11 Aug 2024 20:16:13 +0200 Subject: [PATCH] [bencode] Implement round trip test --- src/bencode.rs | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/src/bencode.rs b/src/bencode.rs index 42e8c14..1eb0d31 100644 --- a/src/bencode.rs +++ b/src/bencode.rs @@ -1,4 +1,48 @@ pub mod custom; pub mod de; pub mod ser; -pub mod error; +pub mod error; + +#[cfg(test)] +mod test { + use std::collections::HashMap; + use serde::{Deserialize, Serialize}; + use crate::bencode::de::from_bytes; + use crate::bencode::ser::to_bytes; + + #[test] + fn test_roundtrip() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + struct A { + l: Vec, + li: Vec, + m: HashMap, + b: Vec<[u8; 4]> + } + + let a = A { + l: vec!["foo".to_string(), "bar".to_string(), "".to_string(), "💩".to_string()], + li: vec![18, 7, 26, 8, 9], + m: HashMap::from([ + ("foo".to_string(), "bar".to_string()), + ("💩".to_string(), "🤷‍♂️".to_string()), + ("18".to_string(), "asdf".to_string()) + ]), + b: vec![ + [4, 26, 7, 18], + [24, 13, 12, 4], + [8, 9, 10, 11] + ], + }; + + let ser = to_bytes(&a).unwrap(); + + let de = from_bytes(&ser).unwrap(); + + assert_eq!(a, de); + + let ser2 = to_bytes(&de).unwrap(); + + assert_eq!(ser, ser2) + } +}