fastnum/bint/int/impls/
cast.rs1use 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 #[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 let bits = self.to_bits();
35 let digits = bits.digits();
36
37 let sign_digit = digits[N - 1];
40 let expected_digit = ((sign_digit as i64) >> 63) as u64;
42
43 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 #[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 #[allow(unsafe_code)]
75 {
76 Ok(unsafe { self._transmute() }.to_bits())
77 }
78 } else {
79 Err(ParseError::PosOverflow)
80 }
81 }
82}