modular_bitfield/private/
impls.rs

1use crate::{
2    error::{InvalidBitPattern, OutOfBounds},
3    Specifier,
4};
5
6impl Specifier for bool {
7    const BITS: usize = 1;
8    type Bytes = u8;
9    type InOut = bool;
10
11    #[inline]
12    fn into_bytes(input: Self::InOut) -> Result<Self::Bytes, OutOfBounds> {
13        Ok(input.into())
14    }
15
16    #[inline]
17    fn from_bytes(bytes: Self::Bytes) -> Result<Self::InOut, InvalidBitPattern<Self::Bytes>> {
18        match bytes {
19            0 => Ok(false),
20            1 => Ok(true),
21            invalid_bytes => Err(InvalidBitPattern::new(invalid_bytes)),
22        }
23    }
24}
25
26macro_rules! impl_specifier_for_primitive {
27    ( $( ($prim:ty: $bits:literal) ),* $(,)? ) => {
28        $(
29            impl Specifier for $prim {
30                const BITS: usize = $bits;
31                type Bytes = $prim;
32                type InOut = $prim;
33
34                #[inline]
35                fn into_bytes(input: Self::InOut) -> Result<Self::Bytes, OutOfBounds> {
36                    Ok(input)
37                }
38
39                #[inline]
40                fn from_bytes(bytes: Self::Bytes) -> Result<Self::InOut, InvalidBitPattern<Self::Bytes>> {
41                    Ok(bytes)
42                }
43            }
44        )*
45    };
46}
47impl_specifier_for_primitive!(
48    (u8: 8),
49    (u16: 16),
50    (u32: 32),
51    (u64: 64),
52    (u128: 128),
53);