nettext/src/serde/mod.rs

151 lines
3.6 KiB
Rust

mod de;
mod error;
mod ser;
pub use de::{from_bytes, Deserializer};
pub use error::{Error, Result};
pub use ser::{to_bytes, to_term, Serializer};
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
fn test_bidir<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(
input: T,
expected: &[u8],
) {
let ser = to_bytes(&input).unwrap();
eprintln!("Serialized: {}", std::str::from_utf8(&ser).unwrap());
assert_eq!(&ser, expected);
assert_eq!(&from_bytes::<T>(&ser).unwrap(), &input);
}
#[test]
fn test_struct() {
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Test {
int: u32,
seq: Vec<String>,
}
let input = Test {
int: 1,
seq: vec!["a".to_string(), "b".to_string()],
};
let expected = br#"Test {
int = 1,
seq = YQ Yg,
}"#;
test_bidir(input, expected);
let input = vec![
Test {
int: 1,
seq: vec!["a".to_string(), "b".to_string()],
},
Test {
int: 2,
seq: vec!["c".to_string(), "d".to_string()],
},
];
let expected = br#"{.= Test {
int = 1,
seq = YQ Yg,
} } {.= Test {
int = 2,
seq = Yw ZA,
} }"#;
test_bidir(input, expected);
}
#[test]
fn test_enum() {
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum E {
Unit,
Newtype(u32),
Tuple(u32, u32),
Struct { a: u32 },
}
let input = E::Unit;
let expected = br#"E.Unit"#;
test_bidir(input, expected);
let input = E::Newtype(1);
let expected = br#"E.Newtype 1"#;
test_bidir(input, expected);
let input = E::Tuple(1, 2);
let expected = br#"E.Tuple 1 2"#;
test_bidir(input, expected);
let input = E::Struct { a: 1 };
let expected = br#"E.Struct { a = 1 }"#;
test_bidir(input, expected);
let input = vec![
E::Unit,
E::Unit,
E::Newtype(1),
E::Tuple(1, 2),
E::Struct { a: 1 },
E::Tuple(3, 2),
];
let expected = br#"E.Unit E.Unit {.= E.Newtype 1 } {.= E.Tuple 1 2 } {.= E.Struct { a = 1 } } {.=
E.Tuple 3 2 }"#;
test_bidir(input, expected);
}
#[test]
fn test_seq1() {
let input = (1, 2, 3, 4);
let expected = br#"1 2 3 4"#;
test_bidir(input, expected);
}
#[test]
fn test_seq2() {
let input = (1, 2, (2, 3, 4), 5, 6);
let expected = br#"1 2 {.= 2 3 4 } 5 6"#;
test_bidir(input, expected);
}
#[test]
fn test_seq3() {
let input = [1, 2, 3, 4];
let expected = br#"1 2 3 4"#;
test_bidir(input, expected);
}
#[test]
fn test_seq4() {
let input = [[1, 2], [2, 3], [3, 4]];
let expected = br#"{.= 1 2 } {.= 2 3 } {.= 3 4 }"#;
test_bidir(input, expected);
}
#[test]
fn test_dict() {
let mut input = HashMap::new();
input.insert("hello".to_string(), "world".to_string());
input.insert("dont".to_string(), "panic".to_string());
let expected = br#"{
ZG9udA = cGFuaWM,
aGVsbG8 = d29ybGQ,
}"#;
test_bidir(input, expected);
let mut input = HashMap::new();
input.insert(12, vec![42, 125]);
input.insert(33, vec![19, 22, 21]);
let expected = br#"{
12 = 42 125,
33 = 19 22 21,
}"#;
test_bidir(input, expected);
}
}