parst/
endian.rs

1use crate::{helpers::try_split_array, Deparsable, PResultBytes, Parsable};
2
3#[derive(Debug, Clone)]
4pub struct LE<T>(pub T);
5
6impl<T> AsRef<T> for LE<T> {
7	fn as_ref(&self) -> &T { &self.0 }
8}
9
10impl<T> AsMut<T> for LE<T> {
11	fn as_mut(&mut self) -> &mut T { &mut self.0 }
12}
13
14#[derive(Debug, Clone)]
15pub struct BE<T>(pub T);
16
17impl<T> AsRef<T> for BE<T> {
18	fn as_ref(&self) -> &T { &self.0 }
19}
20
21impl<T> AsMut<T> for BE<T> {
22	fn as_mut(&mut self) -> &mut T { &mut self.0 }
23}
24
25macro_rules! impl_prim {
26	($ty:ident $size:literal) => {
27		impl Parsable<'_, [u8]> for LE<$ty> {
28			fn read(source: &[u8], _context: ()) -> PResultBytes<Self> {
29				let (head, source) = try_split_array::<_, $size>(source)?;
30				let prim = $ty::from_le_bytes(*head);
31				Ok((Self(prim), source))
32			}
33		}
34
35		impl Parsable<'_, [u8]> for BE<$ty> {
36			fn read(source: &[u8], _context: ()) -> PResultBytes<Self> {
37				let (head, source) = try_split_array::<_, $size>(source)?;
38				let prim = $ty::from_be_bytes(*head);
39				Ok((Self(prim), source))
40			}
41		}
42
43		impl Deparsable for LE<$ty> {
44			fn write(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
45				w.write_all(&self.0.to_le_bytes())
46			}
47		}
48
49		impl Deparsable for BE<$ty> {
50			fn write(&self, w: &mut impl std::io::Write) -> std::io::Result<()> {
51				w.write_all(&self.0.to_be_bytes())
52			}
53		}
54	};
55}
56
57macro_rules! impl_prims {
58	($ty:ident $size:literal) => {
59		impl_prim!($ty $size);
60	};
61	($ty:ident $size:literal $( $other_ty:ident $other_size:literal )*) => {
62		impl_prim!($ty $size);
63        impl_prims!($( $other_ty $other_size )*);
64	};
65}
66
67impl_prims!(u8 1 i8 1 u16 2 i16 2 u32 4 i32 4 u64 8 i64 8 f32 4 f64 8);