1use std::fmt;
4
5use num_bigint::{BigInt, Sign};
6use num_integer::Integer;
7use num_traits::{Signed, ToPrimitive, Zero};
8
9use crate::error::Fault;
10
11#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
21pub struct Int(BigInt);
22
23impl Int {
24 #[must_use]
28 pub fn from_limbs(limbs: &[u32]) -> Self {
29 Int(BigInt::from_slice(Sign::Plus, limbs))
30 }
31
32 pub fn parse(digits: &str) -> Option<Self> {
35 let magnitude = digits.strip_prefix('-').unwrap_or(digits);
36 if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
37 return None;
38 }
39 BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
40 }
41
42 #[must_use]
44 pub fn add(&self, other: &Int) -> Int {
45 Int(&self.0 + &other.0)
46 }
47
48 #[must_use]
50 pub fn sub(&self, other: &Int) -> Int {
51 Int(&self.0 - &other.0)
52 }
53
54 #[must_use]
56 pub fn mul(&self, other: &Int) -> Int {
57 Int(&self.0 * &other.0)
58 }
59
60 #[must_use]
62 pub fn neg(&self) -> Int {
63 Int(-&self.0)
64 }
65
66 pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
73 if divisor.0.is_zero() {
74 return Err(Fault::DivisionByZero);
75 }
76 Ok(Int(self.0.div_floor(&divisor.0)))
77 }
78
79 pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
86 if divisor.0.is_zero() {
87 return Err(Fault::DivisionByZero);
88 }
89 Ok(Int(self.0.mod_floor(&divisor.0)))
90 }
91
92 pub fn is_zero(&self) -> bool {
94 self.0.is_zero()
95 }
96
97 pub fn is_negative(&self) -> bool {
99 self.0.is_negative()
100 }
101
102 pub fn bits(&self) -> u64 {
105 self.0.bits()
106 }
107
108 pub fn to_index(&self) -> Option<usize> {
111 self.0.to_usize()
112 }
113
114 pub fn from_count(count: usize) -> Int {
116 Int(BigInt::from(count))
117 }
118
119 pub fn from_u64(value: u64) -> Int {
121 Int(BigInt::from(value))
122 }
123
124 pub fn as_bigint(&self) -> &BigInt {
126 &self.0
127 }
128
129 pub(crate) fn into_bigint(self) -> BigInt {
130 self.0
131 }
132}
133
134impl From<BigInt> for Int {
135 fn from(value: BigInt) -> Self {
136 Int(value)
137 }
138}
139
140impl From<i64> for Int {
141 fn from(value: i64) -> Self {
142 Int(BigInt::from(value))
143 }
144}
145
146impl fmt::Display for Int {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 fmt::Display::fmt(&self.0, f)
151 }
152}
153
154impl fmt::Debug for Int {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156 fmt::Display::fmt(&self.0, f)
157 }
158}