Skip to main content

fastnum/bint/int/impls/
cast.rs

1use crate::{
2    bint::{intrinsics, Int, ParseError, UInt},
3    utils::const_generics::{Dimension, Narrow, Widen},
4    Cast, TryCast,
5};
6
7impl<const N: usize, const M: usize> Cast<Int<N>> for Int<M>
8where
9    Dimension<N, M>: Widen,
10{
11    #[inline(always)]
12    fn cast(self) -> Int<N> {
13        // SAFETY: `N` is always greater or equal than `M`. So we can safely cast to the
14        // widest type.
15        #[allow(unsafe_code)]
16        unsafe {
17            self._transmute()
18        }
19    }
20}
21
22impl<const N: usize, const M: usize> TryCast<Int<N>> for Int<M>
23where
24    Dimension<N, M>: Narrow,
25{
26    type Error = ParseError;
27
28    #[inline(always)]
29    fn try_cast(self) -> Result<Int<N>, Self::Error> {
30        // For signed integers, narrowing is valid if the upper (M-N) digits are
31        // properly sign-extended. That is, they should all be 0x00...00 for
32        // positive, or all 0xFF...FF for negative.
33
34        let bits = self.to_bits();
35        let digits = bits.digits();
36
37        // Determine the expected value for upper digits based on the sign bit of digit
38        // N-1 The sign bit is the MSB of digit N-1
39        let sign_digit = digits[N - 1];
40        // Branchless: use arithmetic right shift to propagate the sign bit
41        let expected_digit = ((sign_digit as i64) >> 63) as u64;
42
43        // Check if all upper digits match the expected sign extension
44        let mut i = N;
45        while i < M {
46            if digits[i] != expected_digit {
47                return Err(ParseError::PosOverflow);
48            }
49            i += 1;
50        }
51
52        // If we get here, the value fits. Manually create the narrow value by copying
53        // the lower N digits. SAFETY: We've verified that the upper (M-N)
54        // digits are properly sign-extended, so it's safe to transmute to the
55        // narrow type.
56        #[allow(unsafe_code)]
57        unsafe {
58            let narrow_digits = intrinsics::_transmute::<M, N, N>(digits);
59            Ok(Int::from_digits(narrow_digits))
60        }
61    }
62}
63
64impl<const N: usize, const M: usize> TryCast<UInt<N>> for Int<M> {
65    type Error = ParseError;
66
67    #[inline(always)]
68    fn try_cast(self) -> Result<UInt<N>, Self::Error> {
69        if self.is_negative() {
70            Err(ParseError::Signed)
71        } else if self.bits() <= Int::<N>::BITS {
72            // SAFETY: UInt<M> is wider (`N` < `M`) but its value fit to UInt<N>. So we can
73            // safely cast to the narrow type.
74            #[allow(unsafe_code)]
75            {
76                Ok(unsafe { self._transmute() }.to_bits())
77            }
78        } else {
79            Err(ParseError::PosOverflow)
80        }
81    }
82}