Skip to main content

fixed_bigint/fixeduint/
num_traits_casts.rs

1use super::{FixedUInt, MachineWord};
2
3use num_traits::{Bounded, FromPrimitive, ToPrimitive};
4
5impl<T: MachineWord, const N: usize> num_traits::NumCast for FixedUInt<T, N> {
6    fn from<X>(arg: X) -> Option<Self>
7    where
8        X: ToPrimitive,
9    {
10        Self::from_u64(arg.to_u64()?)
11    }
12}
13
14impl<T: MachineWord, const N: usize> num_traits::ToPrimitive for FixedUInt<T, N> {
15    fn to_i64(&self) -> Option<i64> {
16        None
17    }
18    fn to_u64(&self) -> Option<u64> {
19        let mut ret: u64 = 0;
20        // Determine how many words are needed to fill a u64 (64 bits)
21        // If WORD_SIZE is 4 (u32), we read 2 words. If 8 (u64), we read 1.
22        let iter_limit = core::cmp::min(8 / Self::WORD_SIZE, N);
23
24        // Overflow check: any remaining higher limbs must be zero
25        for i in iter_limit..N {
26            if self.array[i] != T::zero() {
27                return None;
28            }
29        }
30
31        for (i, word) in self.array.iter().take(iter_limit).enumerate() {
32            // Convert generic T to bytes (Little Endian)
33            let bytes = word.to_le_bytes();
34
35            // Iterate over bytes and shift them into the u64 result
36            for (j, &byte) in bytes.as_ref().iter().enumerate() {
37                // Calculate the global bit position for this byte
38                let bit_shift = (i * Self::WORD_SIZE + j) * 8;
39
40                // Safety check: ensure we don't shift out of u64 bounds
41                if bit_shift < 64 {
42                    ret |= (byte as u64) << bit_shift;
43                }
44            }
45        }
46
47        Some(ret)
48    }
49}
50
51impl<T: MachineWord, const N: usize> num_traits::FromPrimitive for FixedUInt<T, N> {
52    fn from_i64(_: i64) -> Option<Self> {
53        None
54    }
55    fn from_u64(input: u64) -> Option<Self> {
56        // If max_value() fits in a u64, verify the input does not exceed it.
57        // When to_u64() returns `None`, the target type is wider than 64 bits
58        // and therefore any u64 value will fit.
59        if let Some(max) = Self::max_value().to_u64() {
60            if input > max {
61                return None;
62            }
63        }
64        Some(Self::from_le_bytes(&input.to_le_bytes()))
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    fn cast<T: num_traits::NumCast + PartialEq>(a: u32, b: u8) -> bool {
73        let my_a = T::from(a).unwrap();
74        let my_b = T::from(b).unwrap();
75        my_a == my_b
76    }
77
78    type Fixed = FixedUInt<u8, 1>;
79    // Test numcast
80    #[test]
81    fn test_numcast() {
82        assert!(cast::<Fixed>(123, 123));
83        assert!(cast::<Fixed>(225, 225));
84    }
85}