segsource/
marker.rs

1//! Markers for segsource.
2use crate::Endidness;
3use core::convert::TryInto;
4
5/// An extension trait for integers.
6pub trait Integer: Sized {
7    const WIDTH: usize;
8    fn from_be(bytes: &[u8]) -> Self;
9    fn from_le(bytes: &[u8]) -> Self;
10    fn from_ne(bytes: &[u8]) -> Self;
11    fn with_endidness(bytes: &[u8], endidness: Endidness) -> Self {
12        match endidness {
13            Endidness::Big => Self::from_be(bytes),
14            Endidness::Little => Self::from_le(bytes),
15        }
16    }
17}
18
19macro_rules! impl_integer {
20    ($type:ty, $width:literal, $be_method:ident, $le_method:ident, $ne_method:ident) => {
21        impl Integer for $type {
22            const WIDTH: usize = $width;
23            fn from_be(bytes: &[u8]) -> Self {
24                <$type>::$be_method(bytes.try_into().unwrap())
25            }
26            fn from_le(bytes: &[u8]) -> Self {
27                <$type>::$le_method(bytes.try_into().unwrap())
28            }
29            fn from_ne(bytes: &[u8]) -> Self {
30                <$type>::$ne_method(bytes.try_into().unwrap())
31            }
32        }
33    };
34    ($type:ty, $width:literal) => {
35        impl_integer! {$type, $width, from_be_bytes, from_le_bytes, from_ne_bytes}
36    };
37}
38
39impl_integer! {u8, 1}
40impl_integer! {u16, 2}
41impl_integer! {u32, 4}
42impl_integer! {u64, 8}
43impl_integer! {u128, 16}
44impl_integer! {i8, 1}
45impl_integer! {i16, 2}
46impl_integer! {i32, 4}
47impl_integer! {i64, 8}
48impl_integer! {i128, 16}