1use std::fmt;
4
5use num_bigint::BigInt;
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 pub fn parse(digits: &str) -> Option<Self> {
30 let magnitude = digits.strip_prefix('-').unwrap_or(digits);
31 if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
32 return None;
33 }
34 BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
35 }
36
37 #[must_use]
39 pub fn add(&self, other: &Int) -> Int {
40 Int(&self.0 + &other.0)
41 }
42
43 #[must_use]
45 pub fn sub(&self, other: &Int) -> Int {
46 Int(&self.0 - &other.0)
47 }
48
49 #[must_use]
51 pub fn mul(&self, other: &Int) -> Int {
52 Int(&self.0 * &other.0)
53 }
54
55 #[must_use]
57 pub fn neg(&self) -> Int {
58 Int(-&self.0)
59 }
60
61 pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
64 if divisor.0.is_zero() {
65 return Err(Fault::DivisionByZero);
66 }
67 Ok(Int(self.0.div_floor(&divisor.0)))
68 }
69
70 pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
73 if divisor.0.is_zero() {
74 return Err(Fault::DivisionByZero);
75 }
76 Ok(Int(self.0.mod_floor(&divisor.0)))
77 }
78
79 pub fn is_zero(&self) -> bool {
81 self.0.is_zero()
82 }
83
84 pub fn is_negative(&self) -> bool {
86 self.0.is_negative()
87 }
88
89 pub fn bits(&self) -> u64 {
92 self.0.bits()
93 }
94
95 pub fn to_index(&self) -> Option<usize> {
98 self.0.to_usize()
99 }
100
101 pub fn from_count(count: usize) -> Int {
103 Int(BigInt::from(count))
104 }
105
106 pub fn as_bigint(&self) -> &BigInt {
108 &self.0
109 }
110
111 pub(crate) fn into_bigint(self) -> BigInt {
112 self.0
113 }
114}
115
116impl From<BigInt> for Int {
117 fn from(value: BigInt) -> Self {
118 Int(value)
119 }
120}
121
122impl From<i64> for Int {
123 fn from(value: i64) -> Self {
124 Int(BigInt::from(value))
125 }
126}
127
128impl fmt::Display for Int {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 fmt::Display::fmt(&self.0, f)
133 }
134}
135
136impl fmt::Debug for Int {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 fmt::Display::fmt(&self.0, f)
139 }
140}