Skip to main content

o1_utils/
biguint_helpers.rs

1//! Bit operations on big integers.
2//!
3//! In particular, it gives XOR and NOT for `BigUint`.
4use num_bigint::BigUint;
5
6/// Helpers for [`BigUint`]
7pub trait BigUintHelpers<Rhs = Self> {
8    /// Returns the minimum number of bits required to represent a `BigUint`.
9    /// As opposed to `BigUint::bits`, this function returns 1 for the input zero
10    fn bitlen(&self) -> usize;
11
12    /// Creates a `BigUint` from an hexadecimal string in big endian
13    fn from_hex(s: &str) -> Self;
14}
15
16impl BigUintHelpers for BigUint {
17    #[allow(clippy::cast_possible_truncation)]
18    fn bitlen(&self) -> usize {
19        if self.to_bytes_le() == [0u8] {
20            1
21        } else {
22            self.bits() as usize
23        }
24    }
25    fn from_hex(s: &str) -> Self {
26        Self::parse_bytes(s.as_bytes(), 16).unwrap()
27    }
28}