fixed_bigint/fixeduint/
prim_int_impl.rs1use super::{FixedUInt, MachineWord};
2
3use num_traits::One;
4
5impl<T: MachineWord, const N: usize> num_traits::PrimInt for FixedUInt<T, N> {
6 fn count_ones(self) -> u32 {
7 self.array.iter().map(|&val| val.count_ones()).sum()
8 }
9 fn count_zeros(self) -> u32 {
10 self.array.iter().map(|&val| val.count_zeros()).sum()
11 }
12 fn leading_zeros(self) -> u32 {
13 let mut ret = 0u32;
14 for index in (0..N).rev() {
15 let v = self.array[index];
16 ret += v.leading_zeros();
17 if !v.is_zero() {
18 break;
19 }
20 }
21 ret
22 }
23 fn trailing_zeros(self) -> u32 {
24 let mut ret = 0u32;
25 for index in 0..N {
26 let v = self.array[index];
27 ret += v.trailing_zeros();
28 if !v.is_zero() {
29 break;
30 }
31 }
32 ret
33 }
34 fn rotate_left(self, bits: u32) -> Self {
35 let shift = Self::normalize_shift(bits);
36 let a = self << shift;
37 let b = self >> (Self::BIT_SIZE as u32 - shift);
38 a | b
39 }
40 fn rotate_right(self, bits: u32) -> Self {
41 let shift = Self::normalize_shift(bits);
42 let a = self >> shift;
43 let b = self << (Self::BIT_SIZE as u32 - shift);
44 a | b
45 }
46 fn signed_shl(self, bits: u32) -> Self {
47 self.unsigned_shl(bits)
48 }
49 fn signed_shr(self, bits: u32) -> Self {
50 self.unsigned_shr(bits)
51 }
52 fn unsigned_shl(self, bits: u32) -> Self {
53 core::ops::Shl::<u32>::shl(self, bits)
54 }
55 fn unsigned_shr(self, bits: u32) -> Self {
56 core::ops::Shr::<u32>::shr(self, bits)
57 }
58 fn swap_bytes(self) -> Self {
59 let mut ret = Self::new();
60 for index in 0..N {
61 ret.array[index] = self.array[N - 1 - index].swap_bytes();
62 }
63
64 ret
65 }
66 fn from_be(source: Self) -> Self {
67 let mut ret = Self::new();
68 for index in 0..N {
69 ret.array[index] = source.array[N - 1 - index].swap_bytes();
70 }
71
72 ret
73 }
74 fn from_le(source: Self) -> Self {
75 let mut ret = Self::new();
76 for index in 0..N {
77 ret.array[index] = source.array[index];
78 }
79
80 ret
81 }
82 fn to_be(self) -> Self {
83 let mut ret = Self::new();
84 for index in 0..N {
85 ret.array[index] = self.array[N - 1 - index].swap_bytes();
86 }
87
88 ret
89 }
90 fn to_le(self) -> Self {
91 let mut ret = Self::new();
92 for index in 0..N {
93 ret.array[index] = self.array[index];
94 }
95
96 ret
97 }
98 fn pow(self, n: u32) -> Self {
99 if n == 0 {
100 Self::one()
101 } else {
102 let mut ret = self;
103 for _ in 1..n {
104 ret *= self;
105 }
106 ret
107 }
108 }
109}