ff_uint/uint/
traits.rs

1#[cfg(not(feature = "std"))]
2use alloc::vec::Vec;
3
4pub trait Uint:
5    Sized
6    + Clone
7    + Copy
8    + Default
9    + core::cmp::PartialEq
10    + core::cmp::Eq
11    + core::cmp::PartialOrd
12    + core::cmp::Ord
13    + From<bool>
14    + From<u8>
15    + From<u16>
16    + From<u32>
17    + From<u64>
18    + From<u128>
19    + From<i8>
20    + From<i16>
21    + From<i32>
22    + From<i64>
23    + From<i128>
24    + core::convert::TryInto<bool>
25    + core::convert::TryInto<u8>
26    + core::convert::TryInto<u16>
27    + core::convert::TryInto<u32>
28    + core::convert::TryInto<u64>
29    + core::convert::TryInto<u128>
30    + core::convert::TryInto<i8>
31    + core::convert::TryInto<i16>
32    + core::convert::TryInto<i32>
33    + core::convert::TryInto<i64>
34    + core::convert::TryInto<i128>
35    + core::hash::Hash
36    + core::str::FromStr
37    + From<&'static str>
38    + crate::traits::Borsh
39{
40    type Inner: AsMut<[u64]> + AsRef<[u64]> + Copy + Clone + Default + Sized;
41
42    const MAX: Self;
43    const ZERO: Self;
44    const ONE: Self;
45
46    const NUM_WORDS: usize;
47    const WORD_BITS: usize;
48
49    fn max_value() -> Self {
50        Self::MAX
51    }
52    fn min_value() -> Self {
53        Self::ZERO
54    }
55
56    fn is_even(&self) -> bool {
57        !self.bit(0)
58    }
59
60    fn is_odd(&self) -> bool {
61        self.bit(0)
62    }
63
64    #[cfg(feature = "rand_support")]
65    fn random<R: rand::Rng + ?Sized>(rng: &mut R) -> Self;
66
67    fn into_inner(self) -> Self::Inner;
68    fn as_inner(&self) -> &Self::Inner;
69    fn as_inner_mut(&mut self) -> &mut Self::Inner;
70
71    fn put_big_endian(&self, bytes: &mut [u8]);
72    fn put_little_endian(&self, bytes: &mut [u8]);
73    fn to_big_endian(&self) -> Vec<u8>;
74    fn to_little_endian(&self) -> Vec<u8>;
75    fn from_big_endian(slice: &[u8]) -> Self;
76    fn from_little_endian(slice: &[u8]) -> Self;
77
78    fn as_u64(&self) -> u64;
79    fn low_u64(&self) -> u64;
80    fn from_u64(v: u64) -> Self;
81
82    fn is_zero(&self) -> bool;
83    fn bits(&self) -> usize;
84
85    fn bit(&self, n: usize) -> bool {
86        if n >= Self::NUM_WORDS * Self::WORD_BITS {
87            panic!("Bit index overflow")
88        } else {
89            let limb = n / Self::WORD_BITS;
90            let bitpos = n % Self::WORD_BITS;
91            (self.as_inner().as_ref()[limb] >> bitpos) & 1 == 1
92        }
93    }
94    fn leading_zeros(&self) -> u32;
95    fn trailing_zeros(&self) -> u32;
96
97    fn div_mod(self, other: Self) -> (Self, Self);
98
99    fn overflowing_add(self, other: Self) -> (Self, bool);
100    fn overflowing_sub(self, other: Self) -> (Self, bool);
101    fn overflowing_mul_u64(self, other: u64) -> (Self, u64);
102    fn overflowing_mul(self, other: Self) -> (Self, bool);
103
104    fn overflowing_not(self) -> (Self, bool);
105    fn overflowing_bitand(self, other: Self) -> (Self, bool);
106    fn overflowing_bitor(self, other: Self) -> (Self, bool);
107    fn overflowing_bitxor(self, other: Self) -> (Self, bool);
108
109    fn overflowing_neg(self) -> (Self, bool);
110    fn overflowing_shr(self, other: u32) -> (Self, bool);
111    fn overflowing_shl(self, other: u32) -> (Self, bool);
112
113    #[inline]
114    fn overflowing_pow<S: BitIterBE>(self, exp: S) -> (Self, bool) {
115        let mut res = Self::ONE;
116        let mut overflow: bool = false;
117        let mut found_one = false;
118        for i in exp.bit_iter_be() {
119            if found_one {
120                res = overflowing!(res.overflowing_mul(res), overflow);
121            } else {
122                found_one = i;
123            }
124            if i {
125                res = overflowing!(res.overflowing_mul(self), overflow);
126            }
127        }
128        (res, overflow)
129    }
130
131    #[inline]
132    fn to_other<U: Uint>(self) -> Option<U> {
133        let mut res = U::default();
134        let res_inner = res.as_inner_mut().as_mut();
135        let res_inner_len = res_inner.len();
136
137        let self_inner = self.as_inner().as_ref();
138        let self_inner_len = self_inner.len();
139
140        let both_min = core::cmp::min(res_inner_len, self_inner_len);
141
142        res_inner[..both_min].copy_from_slice(&self_inner[..both_min]);
143
144        if self_inner[both_min..].iter().any(|&x| x != 0) {
145            None
146        } else {
147            Some(res)
148        }
149    }
150
151    fn wrapping_cmp(&self, other: &Self) -> core::cmp::Ordering;
152
153    #[inline]
154    fn unchecked_pow(self, other: Self) -> Self {
155        self.overflowing_pow(other).0
156    }
157
158    #[inline]
159    fn unchecked_add(self, other: Self) -> Self {
160        self.overflowing_add(other).0
161    }
162
163    #[inline]
164    fn unchecked_sub(self, other: Self) -> Self {
165        self.overflowing_sub(other).0
166    }
167
168    #[inline]
169    fn unchecked_mul(self, other: Self) -> Self {
170        self.overflowing_mul(other).0
171    }
172
173    /// Checked division. Returns `None` if `other == 0`.
174    #[inline]
175    fn overflowing_div(self, other: Self) -> (Self, bool) {
176        (self.div_mod(other).0, false)
177    }
178
179    #[inline]
180    fn unchecked_div(self, other: Self) -> Self {
181        self.div_mod(other).0
182    }
183
184    #[inline]
185    fn overflowing_rem(self, other: Self) -> (Self, bool) {
186        (self.div_mod(other).1, false)
187    }
188
189    #[inline]
190    fn unchecked_rem(self, other: Self) -> Self {
191        self.div_mod(other).1
192    }
193
194    #[inline]
195    fn unchecked_neg(self) -> Self {
196        self.overflowing_neg().0
197    }
198
199    #[inline]
200    fn unchecked_shr(self, rhs: u32) -> Self {
201        self.overflowing_shr(rhs).0
202    }
203
204    #[inline]
205    fn unchecked_shl(self, lhs: u32) -> Self {
206        self.overflowing_shl(lhs).0
207    }
208
209    crate::impl_wrapping_bin_method!(wrapping_pow, overflowing_pow, Self);
210    crate::impl_wrapping_bin_method!(wrapping_add, overflowing_add, Self);
211    crate::impl_wrapping_bin_method!(wrapping_sub, overflowing_sub, Self);
212    crate::impl_wrapping_bin_method!(wrapping_mul, overflowing_mul, Self);
213    crate::impl_wrapping_bin_method!(wrapping_div, overflowing_div, Self);
214    crate::impl_wrapping_bin_method!(wrapping_rem, overflowing_rem, Self);
215    crate::impl_wrapping_bin_method!(wrapping_shl, overflowing_shl, u32);
216    crate::impl_wrapping_bin_method!(wrapping_shr, overflowing_shr, u32);
217    crate::impl_wrapping_un_method!(wrapping_neg, overflowing_neg);
218    crate::impl_wrapping_un_method!(wrapping_not, overflowing_not);
219}
220
221pub struct BitIteratorLE<E> {
222    t: E,
223    i: usize,
224    n: usize,
225}
226
227impl<E: Uint> Iterator for BitIteratorLE<E> {
228    type Item = bool;
229
230    fn next(&mut self) -> Option<bool> {
231        if self.i >= self.n {
232            None
233        } else {
234            let part = self.i / 64;
235            let bit = self.i & 63;
236            self.i += 1;
237            Some((self.t.as_inner().as_ref()[part] >> bit) & 1 == 1)
238        }
239    }
240}
241
242pub trait BitIterLE {
243    type Iter: Iterator<Item = bool>;
244
245    fn bit_iter_le(&self) -> Self::Iter;
246}
247
248impl<I: Uint> BitIterLE for I {
249    type Iter = BitIteratorLE<I>;
250
251    fn bit_iter_le(&self) -> Self::Iter {
252        Self::Iter {
253            t: *self,
254            i: 0,
255            n: I::NUM_WORDS * I::WORD_BITS,
256        }
257    }
258}
259
260pub struct BitIteratorBE<E> {
261    t: E,
262    i: usize,
263}
264
265impl<E: Uint> Iterator for BitIteratorBE<E> {
266    type Item = bool;
267
268    fn next(&mut self) -> Option<bool> {
269        if self.i == 0 {
270            None
271        } else {
272            self.i -= 1;
273            let part = self.i / 64;
274            let bit = self.i & 63;
275            Some((self.t.as_inner().as_ref()[part] >> bit) & 1 == 1)
276        }
277    }
278}
279
280pub trait BitIterBE {
281    type Iter: Iterator<Item = bool>;
282
283    fn bit_iter_be(&self) -> Self::Iter;
284}
285
286impl<I: Uint> BitIterBE for I {
287    type Iter = BitIteratorBE<I>;
288
289    fn bit_iter_be(&self) -> Self::Iter {
290        Self::Iter {
291            t: *self,
292            i: I::NUM_WORDS * I::WORD_BITS,
293        }
294    }
295}