bit_int/bit_uint/
convert.rs

1// SPDX-FileCopyrightText: 2024 Shun Sakai
2//
3// SPDX-License-Identifier: Apache-2.0 OR MIT
4
5//! Implementations of conversions between [`BitUint`] and other types.
6
7use super::BitUint;
8
9macro_rules! impl_from_bit_uint_to_underlying_type {
10    ($T:ty) => {
11        impl<const N: u32> From<BitUint<$T, N>> for $T {
12            #[inline]
13            fn from(n: BitUint<$T, N>) -> Self {
14                n.get()
15            }
16        }
17    };
18}
19impl_from_bit_uint_to_underlying_type!(u8);
20impl_from_bit_uint_to_underlying_type!(u16);
21impl_from_bit_uint_to_underlying_type!(u32);
22impl_from_bit_uint_to_underlying_type!(u64);
23impl_from_bit_uint_to_underlying_type!(u128);
24impl_from_bit_uint_to_underlying_type!(usize);
25
26#[cfg(test)]
27mod tests {
28    use super::super::{BitU8, BitU16, BitU32, BitU64, BitU128, BitUsize};
29
30    #[test]
31    fn from_bit_uint_to_underlying_type() {
32        assert_eq!(u8::from(BitU8::<7>::MAX), u8::MAX >> 1);
33        assert_eq!(u16::from(BitU16::<15>::MAX), u16::MAX >> 1);
34        assert_eq!(u32::from(BitU32::<31>::MAX), u32::MAX >> 1);
35        assert_eq!(u64::from(BitU64::<63>::MAX), u64::MAX >> 1);
36        assert_eq!(u128::from(BitU128::<127>::MAX), u128::MAX >> 1);
37        assert_eq!(
38            usize::from(BitUsize::<{ usize::BITS - 1 }>::MAX),
39            usize::MAX >> 1
40        );
41    }
42}