fixed_bigint/fixeduint/
num_traits_casts.rs1use 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 let iter_limit = core::cmp::min(8 / Self::WORD_SIZE, N);
23
24 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 let bytes = word.to_le_bytes();
34
35 for (j, &byte) in bytes.as_ref().iter().enumerate() {
37 let bit_shift = (i * Self::WORD_SIZE + j) * 8;
39
40 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 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]
81 fn test_numcast() {
82 assert!(cast::<Fixed>(123, 123));
83 assert!(cast::<Fixed>(225, 225));
84 }
85}