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
#![doc = include_str!("../README.md")]
#![cfg_attr(feature = "nightly", feature(array_try_map))]
#![cfg_attr(feature = "auto_traits", feature(auto_traits))]
#![cfg_attr(feature = "auto_traits", feature(negative_impls))]

mod bytes;
mod cursor;
mod error;
pub mod lencoder;
mod record;
mod types;

use core::convert::TryInto;
use core::mem::{size_of, MaybeUninit};
use core::{fmt, ptr};

#[cfg(feature = "auto_traits")]
pub use auto_traits::*;
pub use bin_layout_derive::*;
pub use bytes::*;
pub use cursor::*;
pub use error::*;
pub use lencoder::Lencoder;
pub use record::*;

pub trait Encoder: Sized {
    /// The size of the data type in bytes. (padding not included)
    const SIZE: usize = size_of::<Self>();

    /// Serialize the data to binary format.
    fn encoder(self, _: &mut Cursor<impl Bytes>);

    /// Calculate total estimated size of the data structure in bytes.
    #[inline]
    fn size_hint(&self) -> usize {
        Self::SIZE
    }

    /// ### Example
    ///
    /// ```
    /// use bin_layout::Encoder;
    ///
    /// #[derive(Encoder)]
    /// struct FooBar {
    ///     foo: u8,
    ///     bar: [u8; 2],
    /// }
    /// let foobar = FooBar { foo: 1, bar: [2, 3] }.encode();
    /// assert_eq!(vec![1, 2, 3], foobar);
    /// ```
    #[inline]
    fn encode(self) -> Vec<u8> {
        let mut vec = Vec::with_capacity(self.size_hint());
        let mut cursor = Cursor::new(&mut vec);
        self.encoder(&mut cursor);
        vec
    }
}

pub trait Decoder<'de, E>: Sized {
    /// Deserialize the data from binary format.
    fn decoder(_: &mut Cursor<&'de [u8]>) -> Result<Self, E>;

    /// ### Example
    ///
    /// ```
    /// use bin_layout::Decoder;
    ///
    /// #[derive(Decoder, PartialEq, Debug)]
    /// struct FooBar {
    ///     foo: u8,
    ///     bar: [u8; 2],
    /// }
    ///
    /// let foobar: Result<FooBar, ()> = FooBar::decode(&[1, 2, 3]);
    /// assert_eq!(foobar, Ok(FooBar { foo: 1, bar: [2, 3] }));
    /// ```
    #[inline]
    fn decode(data: &'de [u8]) -> Result<Self, E> {
        Self::decoder(&mut Cursor::from(data))
    }
}

#[cfg(feature = "auto_traits")]
mod auto_traits {
    pub unsafe auto trait StaticSized {}

    impl !StaticSized for &str {}
    impl !StaticSized for String {}
    impl<T> !StaticSized for &[T] {}
    impl<T> !StaticSized for Vec<T> {}
}