1pub trait Encoder<B, Item = Self> {
4 type Error;
6
7 fn encode(item: &Item, buf: &mut B) -> Result<(), Self::Error>;
16
17 fn size_of(item: &Item, buf: &B) -> usize;
28}
29
30#[cfg(test)]
31mod tests {
32 use crate as recode;
33 use crate::util::EncoderExt;
34 use crate::Encoder;
35
36 #[test]
37 fn basic_test() {
38 #[derive(Encoder)]
39 #[recode(encoder(buffer_name = "buf", error = "crate::Error"))]
40 struct TestType {
41 age: u32,
42 salary: u64,
43 first_name: crate::codec::Ascii<u8>,
44 last_name: crate::codec::Utf8<u16>,
45 image: crate::codec::Buffer<u32>,
46 }
47
48 const IMAGE_BUF: [u8; 32] = [
49 0xBA, 0x3E, 0x9D, 0x6B, 0xAE, 0xF5, 0x91, 0xCC, 0xE2, 0xF0, 0xCB,
50 0x4F, 0xBB, 0x5B, 0x2B, 0xBE, 0xA7, 0xF4, 0x9D, 0xFB, 0x87, 0x43,
51 0x0E, 0xDF, 0x30, 0x6F, 0x7D, 0x6E, 0x22, 0xAB, 0xCC, 0x47,
52 ];
53
54 let test_item = TestType {
55 age: 0x01234567,
56 salary: 0x1122334455667788,
57 first_name: "ayman".into(),
58 last_name: "القاضي".into(),
59 image: IMAGE_BUF.as_ref().into(),
60 };
61
62 let mut buf = bytes::BytesMut::new();
63
64 assert_eq!(test_item.age.size(&buf), 4);
65 assert_eq!(test_item.salary.size(&buf), 8);
66 assert_eq!(test_item.first_name.size(&buf), 1 + 5);
67 assert_eq!(test_item.last_name.size(&buf), 2 + 12);
68 assert_eq!(test_item.image.size(&buf), 4 + 32);
69 assert_eq!(test_item.size(&buf), 4 + 8 + (1 + 5) + (2 + 12) + (4 + 32));
70
71 TestType::encode(&test_item, &mut buf).unwrap();
72
73 const BUF: [u8; 68] = [
74 0x01, 0x23, 0x45, 0x67, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
77 0x05, b'a', b'y', b'm', b'a', b'n',
79 0x00, 0x0C, 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x82, 0xD8, 0xA7, 0xD8,
81 0xB6, 0xD9, 0x8A,
82 0x00, 0x00, 0x00, 0x20, 0xBA, 0x3E, 0x9D, 0x6B, 0xAE, 0xF5, 0x91,
84 0xCC, 0xE2, 0xF0, 0xCB, 0x4F, 0xBB, 0x5B, 0x2B, 0xBE, 0xA7, 0xF4,
85 0x9D, 0xFB, 0x87, 0x43, 0x0E, 0xDF, 0x30, 0x6F, 0x7D, 0x6E, 0x22,
86 0xAB, 0xCC, 0x47,
87 ];
88
89 assert_eq!(buf, BUF.as_ref());
90 }
91}