bin_layout/lib.rs
1#![doc = include_str!("../README.md")]
2// #![cfg_attr(feature = "nightly", feature(min_specialization))]
3
4pub use bin_layout_derive::*;
5pub mod len;
6mod record;
7mod types;
8mod utils;
9
10use len::*;
11use std::io::{self, Write};
12use utils::*;
13
14pub use record::*;
15
16type DynErr = Box<dyn std::error::Error + Send + Sync>;
17type Result<T> = std::result::Result<T, DynErr>;
18
19/// This trait used to serialize the data structure into binary format.
20pub trait Encoder {
21 /// Serialize the data into binary format.
22 fn encoder(&self, _: &mut impl Write) -> io::Result<()>;
23
24 /// ### Example
25 ///
26 /// ```
27 /// use bin_layout::Encoder;
28 ///
29 /// #[derive(Encoder)]
30 /// struct FooBar {
31 /// foo: u8,
32 /// bar: [u8; 2],
33 /// }
34 /// let bytes = FooBar { foo: 1, bar: [2, 3] }.encode();
35 /// assert_eq!(bytes, vec![1, 2, 3]);
36 /// ```
37 #[inline]
38 fn encode(&self) -> Vec<u8> {
39 let mut vec = Vec::new();
40 self.encoder(&mut vec).unwrap();
41 vec
42 }
43}
44
45/// This trait used to deserialize the data structure from binary format.
46pub trait Decoder<'de>: Sized {
47 /// Deserialize the data from binary format.
48 fn decoder(_: &mut &'de [u8]) -> Result<Self>;
49
50 /// ### Example
51 ///
52 /// ```
53 /// use bin_layout::Decoder;
54 ///
55 /// #[derive(Decoder, PartialEq, Debug)]
56 /// struct FooBar {
57 /// foo: u8,
58 /// bar: [u8; 2],
59 /// }
60 ///
61 /// let foobar = FooBar::decode(&[1, 2, 3]).unwrap();
62 /// assert_eq!(foobar, FooBar { foo: 1, bar: [2, 3] });
63 /// ```
64 #[inline]
65 fn decode(data: &'de [u8]) -> Result<Self> {
66 let mut reader = data;
67 Self::decoder(&mut reader)
68 }
69}