bnum/
helpers.rs

1use crate::ExpType;
2
3pub trait Bits {
4    const BITS: ExpType;
5
6    fn bits(&self) -> ExpType;
7    fn bit(&self, index: ExpType) -> bool;
8}
9
10macro_rules! impl_bits_for_uint {
11    ($($uint: ty), *) => {
12        $(impl Bits for $uint {
13            const BITS: ExpType = Self::BITS as ExpType;
14
15            #[inline]
16            fn bits(&self) -> ExpType {
17                (Self::BITS - self.leading_zeros()) as ExpType
18            }
19
20            #[inline]
21            fn bit(&self, index: ExpType) -> bool {
22                self & (1 << index) != 0
23            }
24        })*
25    };
26}
27
28impl_bits_for_uint!(u8, u16, u32, u64, u128, usize);
29
30macro_rules! impl_bits_for_buint {
31    ($BUint: ident, $BInt: ident, $Digit: ident) => {
32        impl<const N: usize> crate::helpers::Bits for $BUint<N> {
33            const BITS: ExpType = Self::BITS;
34
35            #[inline]
36            fn bits(&self) -> ExpType {
37                Self::bits(&self)
38            }
39
40            #[inline]
41            fn bit(&self, index: ExpType) -> bool {
42                Self::bit(&self, index)
43            }
44        }
45    };
46}
47
48crate::macro_impl!(impl_bits_for_buint);
49
50pub trait Zero: Sized + PartialEq {
51    const ZERO: Self;
52
53    fn is_zero(&self) -> bool {
54        self == &Self::ZERO
55    }
56}
57
58pub trait One: Sized + PartialEq {
59    const ONE: Self;
60
61    fn is_one(&self) -> bool {
62        self == &Self::ONE
63    }
64}
65
66macro_rules! impl_zero_for_uint {
67    ($($uint: ty), *) => {
68        $(impl Zero for $uint {
69            const ZERO: Self = 0;
70        })*
71    };
72}
73
74impl_zero_for_uint!(u8, u16, u32, u64, u128, usize);
75
76macro_rules! impl_one_for_int {
77    ($($uint: ty), *) => {
78        $(impl One for $uint {
79            const ONE: Self = 1;
80        })*
81    };
82}
83
84impl_one_for_int!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
85
86macro_rules! impl_zero_for_buint {
87    ($BUint: ident, $BInt: ident, $Digit: ident) => {
88        impl<const N: usize> crate::helpers::Zero for $BUint<N> {
89            const ZERO: Self = Self::ZERO;
90        }
91    };
92}
93
94crate::macro_impl!(impl_zero_for_buint);
95
96macro_rules! impl_one_for_buint {
97    ($BUint: ident, $BInt: ident, $Digit: ident) => {
98        impl<const N: usize> crate::helpers::One for $BUint<N> {
99            const ONE: Self = Self::ONE;
100        }
101    };
102}
103
104crate::macro_impl!(impl_one_for_buint);
105
106#[inline]
107pub const fn tuple_to_option<T: Copy>((int, overflow): (T, bool)) -> Option<T> {
108    if overflow {
109        None
110    } else {
111        Some(int)
112    }
113}