bencode inspired tight self describing serialization format
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::to_bytes;

use super::*;
#[track_caller]
fn rtt<X: Serialize + PartialEq + std::fmt::Debug>(x: X)
where
    X: for<'a> Deserialize<'a>,
{
    let b = to_bytes(&x).unwrap();
    for &ch in &b {
        if ch.is_ascii_alphabetic() {
            print!("{},", ch as char);
        } else {
            print!("{ch},");
        }
    }
    println!("{:x?}", b);
    dbg!(from_bytes::<serde_json::Value>(&b).unwrap());
    // println!("{b:?}");
    let f = from_bytes::<X>(&b).unwrap_or_else(|e| {
        println!("{e}");
        panic!()
    });
    assert_eq!(f, x);
}

#[test]
fn basic() {
    rtt(4);
    rtt([1, 2, 3, 4]);
    rtt((1, 2, 3));
    rtt(("hello".to_string(), 5, vec![1, 2, 3]));
    rtt(HashMap::<u8, u16>::from_iter([(1, 5), (4, 2)]));
    rtt(Some(4));
    rtt(None::<u8>);
    rtt(-1);
    rtt(-487);
    let x: &str = from_bytes(&to_bytes(&"hi").unwrap()).unwrap();
}

#[test]
fn structs() {
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct Y {
        abra: u32,
        bada: u16,
        hocu: Vec<HashMap<u16, f32>>,
    }
    rtt(Y {
        abra: 4,
        bada: 5,
        hocu: vec![
            HashMap::from_iter([(1, 5.0), (41, 41.0)]),
            HashMap::default(),
        ],
    });
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct Z(u32);
    rtt(Z(4515161));
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct A;
    rtt(A);
}
#[test]
fn enums() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    enum E {
        Unit,
        Newtype(u32),
        Tuple(u32, u32),
        Struct { a: u32 },
    }

    rtt(E::Unit);
    rtt(E::Newtype(51));

    rtt(E::Tuple(1, 24151561));
    rtt(E::Struct { a: 1 });
}
#[test]
fn postcard_fails_these() {
    #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct A {
        #[serde(skip_serializing_if = "Option::is_none")]
        x: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        y: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        z: Option<u32>,
    }
    rtt(A {
        x: Some(4),
        y: None,
        z: Some(5),
    });
}