proc_bitfield/traits/
int_impls.rs

1use super::{Bit, Bits, SetBit, SetBits, WithBit, WithBits};
2
3macro_rules! impl_bits_for_int_type {
4    ($storage: ty, $value: ty) => {
5        impl Bits<$value> for $storage {
6            #[inline]
7            fn bits<const START: usize, const END: usize>(&self) -> $value {
8                const VALUE_BITS: usize = <$value>::BITS as usize;
9                let read_bits = END - START;
10                ((*self >> START) as $value) << (VALUE_BITS - read_bits) >> (VALUE_BITS - read_bits)
11            }
12        }
13
14        impl WithBits<$value> for $storage {
15            #[inline]
16            fn with_bits<const START: usize, const END: usize>(self, value: $value) -> Self {
17                let written_bits = END - START;
18                let mask = ((1 as $storage) << (written_bits - 1) << 1).wrapping_sub(1) << START;
19                (self & !mask) | ((value as $storage) << START & mask)
20            }
21        }
22
23        impl SetBits<$value> for $storage {
24            #[inline]
25            fn set_bits<const START: usize, const END: usize>(&mut self, value: $value) {
26                *self = self.with_bits::<START, END>(value);
27            }
28        }
29    };
30}
31
32macro_rules! impl_bits_for_int_types {
33    (=> $($dst_ty: ty),*) => {};
34    ($src_ty: ty $(, $other_src_ty: ty)* => $($dst_ty: ty),*) => {
35        $(
36            impl_bits_for_int_type!($src_ty, $dst_ty);
37        )*
38        impl_bits_for_int_types!($($other_src_ty),* => $($dst_ty),*);
39    };
40}
41
42impl_bits_for_int_types!(
43    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
44        => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
45);
46
47macro_rules! impl_bit_for_int_type {
48    ($t: ty) => {
49        impl Bit for $t {
50            #[inline]
51            fn bit<const BIT: usize>(&self) -> bool {
52                *self & 1 << BIT != 0
53            }
54        }
55
56        impl WithBit for $t {
57            #[inline]
58            fn with_bit<const BIT: usize>(self, value: bool) -> Self {
59                (self & !(1 << BIT)) | (value as $t) << BIT
60            }
61        }
62
63        impl SetBit for $t {
64            #[inline]
65            fn set_bit<const BIT: usize>(&mut self, value: bool) {
66                *self = self.with_bit::<BIT>(value);
67            }
68        }
69    };
70}
71
72macro_rules! impl_bit_for_int_types {
73    ($($t: ty),*) => {
74        $(impl_bit_for_int_type!($t);)*
75    };
76}
77
78impl_bit_for_int_types!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);