crypto_bigint/int/
resize.rs

1use crate::{Int, Limb, Uint};
2
3impl<const LIMBS: usize> Int<LIMBS> {
4    /// Resize the representation of `self` to an `Int<T>`.
5    /// Warning: this operation may lead to loss of information.
6    #[inline(always)]
7    pub const fn resize<const T: usize>(&self) -> Int<T> {
8        let mut limbs = [Limb::select(Limb::ZERO, Limb::MAX, self.is_negative()); T];
9        let mut i = 0;
10        let dim = if T < LIMBS { T } else { LIMBS };
11        while i < dim {
12            limbs[i] = self.0.limbs[i];
13            i += 1;
14        }
15        Uint { limbs }.as_int()
16    }
17}
18
19#[cfg(test)]
20mod tests {
21    use num_traits::WrappingSub;
22
23    use crate::{I128, I256};
24
25    #[test]
26    fn scale_down() {
27        assert_eq!(I256::MIN.resize::<{ I128::LIMBS }>(), I128::ZERO);
28        assert_eq!(I256::MINUS_ONE.resize::<{ I128::LIMBS }>(), I128::MINUS_ONE);
29        assert_eq!(I256::ZERO.resize::<{ I128::LIMBS }>(), I128::ZERO);
30        assert_eq!(I256::ONE.resize::<{ I128::LIMBS }>(), I128::ONE);
31        assert_eq!(I256::MAX.resize::<{ I128::LIMBS }>(), I128::MINUS_ONE);
32    }
33
34    #[test]
35    fn scale_up() {
36        assert_eq!(
37            I128::MIN.resize::<{ I256::LIMBS }>(),
38            I256::ZERO.wrapping_sub(&I256 {
39                0: I128::MIN.0.resize()
40            })
41        );
42        assert_eq!(I128::MINUS_ONE.resize::<{ I256::LIMBS }>(), I256::MINUS_ONE);
43        assert_eq!(I128::ZERO.resize::<{ I256::LIMBS }>(), I256::ZERO);
44        assert_eq!(I128::ONE.resize::<{ I256::LIMBS }>(), I256::ONE);
45        assert_eq!(
46            I128::MAX.resize::<{ I256::LIMBS }>(),
47            I128::MAX.0.resize().as_int()
48        );
49    }
50}