use std::fmt;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{Signed, ToPrimitive, Zero};
use crate::error::Fault;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Int(BigInt);
impl Int {
pub fn parse(digits: &str) -> Option<Self> {
let magnitude = digits.strip_prefix('-').unwrap_or(digits);
if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
}
#[must_use]
pub fn add(&self, other: &Int) -> Int {
Int(&self.0 + &other.0)
}
#[must_use]
pub fn sub(&self, other: &Int) -> Int {
Int(&self.0 - &other.0)
}
#[must_use]
pub fn mul(&self, other: &Int) -> Int {
Int(&self.0 * &other.0)
}
#[must_use]
pub fn neg(&self) -> Int {
Int(-&self.0)
}
pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
if divisor.0.is_zero() {
return Err(Fault::DivisionByZero);
}
Ok(Int(self.0.div_floor(&divisor.0)))
}
pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
if divisor.0.is_zero() {
return Err(Fault::DivisionByZero);
}
Ok(Int(self.0.mod_floor(&divisor.0)))
}
pub fn is_zero(&self) -> bool {
self.0.is_zero()
}
pub fn is_negative(&self) -> bool {
self.0.is_negative()
}
pub fn bits(&self) -> u64 {
self.0.bits()
}
pub fn to_index(&self) -> Option<usize> {
self.0.to_usize()
}
pub fn from_count(count: usize) -> Int {
Int(BigInt::from(count))
}
pub fn as_bigint(&self) -> &BigInt {
&self.0
}
pub(crate) fn into_bigint(self) -> BigInt {
self.0
}
}
impl From<BigInt> for Int {
fn from(value: BigInt) -> Self {
Int(value)
}
}
impl From<i64> for Int {
fn from(value: i64) -> Self {
Int(BigInt::from(value))
}
}
impl fmt::Display for Int {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Debug for Int {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}