use structio::{Result, beve, json};
#[derive(Default, PartialEq, Debug)]
struct Sample {
id: u32,
label: String,
}
structio::object!(Sample { id, label });
fn json_long_to_alias<T: for<'de> json::Read<'de> + Default>(s: &str) -> Result<T> {
json_alias::<T>(s)
}
fn json_alias<T: json::ReadOwned>(s: &str) -> Result<T> {
json_long::<T>(s)
}
fn json_long<T: for<'de> json::Read<'de> + Default>(s: &str) -> Result<T> {
json::from_str(s)
}
#[test]
fn the_json_alias_is_the_bound_it_replaced() {
fn case<T: json::ReadOwned + PartialEq + core::fmt::Debug>(s: &str, want: T) {
assert_eq!(json_long_to_alias::<T>(s).unwrap(), want);
}
case("42", 42u32);
case(r#""hi""#, "hi".to_owned());
case("[1,2]", vec![1u8, 2]);
case(
r#"{"id":1,"label":"x"}"#,
Sample {
id: 1,
label: "x".to_owned(),
},
);
}
fn beve_long_to_alias<T: for<'de> beve::Read<'de> + Default>(b: &[u8]) -> Result<T> {
beve_alias::<T>(b)
}
fn beve_alias<T: beve::ReadOwned>(b: &[u8]) -> Result<T> {
beve_long::<T>(b)
}
fn beve_long<T: for<'de> beve::Read<'de> + Default>(b: &[u8]) -> Result<T> {
beve::from_slice(b)
}
#[test]
fn the_beve_alias_is_the_bound_it_replaced() {
fn case<T: beve::ReadOwned + PartialEq + core::fmt::Debug>(bytes: &[u8], want: T) {
assert_eq!(beve_long_to_alias::<T>(bytes).unwrap(), want);
}
case(&structio::to_beve(&7u32), 7u32);
case(&structio::to_beve(&vec![1u8, 2]), vec![1u8, 2]);
let sample = Sample {
id: 3,
label: "b".to_owned(),
};
let bytes = structio::to_beve(&sample);
case(&bytes, sample);
}
fn root_long_to_alias<T>(json: bool, body: &[u8]) -> Result<T>
where
T: for<'de> json::Read<'de> + for<'de> beve::Read<'de> + Default,
{
root_alias::<T>(json, body)
}
fn root_alias<T: structio::ReadOwned>(json: bool, body: &[u8]) -> Result<T> {
root_long::<T>(json, body)
}
fn root_long<T>(json: bool, body: &[u8]) -> Result<T>
where
T: for<'de> json::Read<'de> + for<'de> beve::Read<'de> + Default,
{
if json {
json::from_slice(body)
} else {
beve::from_slice(body)
}
}
#[test]
fn the_root_alias_is_the_bound_it_replaced() {
fn case<T: structio::ReadOwned + PartialEq + core::fmt::Debug>(
text: &str,
bytes: &[u8],
want: T,
) {
assert_eq!(
root_long_to_alias::<T>(true, text.as_bytes()).unwrap(),
want
);
assert_eq!(root_long_to_alias::<T>(false, bytes).unwrap(), want);
}
case("9", &structio::to_beve(&9u32), 9u32);
let sample = Sample {
id: 9,
label: "both".to_owned(),
};
let bytes = structio::to_beve(&sample);
case(r#"{"id":9,"label":"both"}"#, &bytes, sample);
}