Timothy J. Warren
34a1989925
All checks were successful
timw4mail/rusty-numbers/pipeline/head This commit looks good
370 lines
8.5 KiB
Rust
370 lines
8.5 KiB
Rust
#![allow(unused_variables)]
|
|
//! \[WIP\] Arbitrarily large integers
|
|
use crate::num::*;
|
|
use core::ops::{
|
|
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
|
|
};
|
|
use core::usize;
|
|
use std::convert::TryInto;
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct BigInt {
|
|
inner: Vec<usize>,
|
|
sign: Sign,
|
|
}
|
|
|
|
impl Default for BigInt {
|
|
fn default() -> Self {
|
|
Self {
|
|
inner: vec![0],
|
|
sign: Sign::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<usize> for BigInt {
|
|
fn from(n: usize) -> Self {
|
|
Self {
|
|
inner: vec![n],
|
|
sign: Sign::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<&str> for BigInt {
|
|
fn from(s: &str) -> Self {
|
|
Self::from_str_radix(s, 10)
|
|
}
|
|
}
|
|
|
|
impl From<String> for BigInt {
|
|
fn from(s: String) -> Self {
|
|
Self::from_str_radix(s, 10)
|
|
}
|
|
}
|
|
|
|
impl BigInt {
|
|
/// Create a new Bigint, of value 0
|
|
///
|
|
/// The various `From` implementations are more useful in most cases
|
|
pub fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
fn new_empty() -> Self {
|
|
Self {
|
|
inner: Vec::new(),
|
|
sign: Sign::Positive,
|
|
}
|
|
}
|
|
|
|
/// Remove digits that are zero from the internal representation.
|
|
///
|
|
/// Similar to 007 -> 7 in base 10
|
|
pub fn trim_zeros(&mut self) {
|
|
let current_len = self.inner.len();
|
|
if current_len < 2 {
|
|
return
|
|
}
|
|
|
|
let mut trailing_zeros = 0usize;
|
|
for val in self.inner.iter().rev() {
|
|
if *val != 0 {
|
|
break
|
|
}
|
|
|
|
trailing_zeros += 1;
|
|
}
|
|
|
|
let new_len = current_len - trailing_zeros;
|
|
|
|
self.inner.truncate(new_len);
|
|
}
|
|
|
|
/// Remove unused digits, and shrink the internal vector
|
|
pub fn shrink_to_fit(&mut self) {
|
|
self.trim_zeros();
|
|
self.inner.shrink_to_fit();
|
|
}
|
|
|
|
/// Convert a `&str` or a `String` representing a number in the specified radix to a Bigint.
|
|
///
|
|
/// For radix 10, use the `from` associated function instead.
|
|
pub fn from_str_radix<T: ToString>(s: T, radix: usize) -> BigInt {
|
|
todo!();
|
|
}
|
|
}
|
|
|
|
impl Add for BigInt {
|
|
type Output = Self;
|
|
|
|
fn add(self, rhs: Self) -> Self::Output {
|
|
// @TODO: handle signs
|
|
let mut out = BigInt::new_empty();
|
|
|
|
let u_digits = self.inner.len();
|
|
let v_digits = rhs.inner.len();
|
|
|
|
let digits = if v_digits > u_digits {
|
|
v_digits
|
|
} else {
|
|
u_digits
|
|
};
|
|
|
|
let mut carry = 0usize;
|
|
for i in 0..=digits {
|
|
let a = *self.inner.get(i).unwrap_or(&0usize);
|
|
let b = *rhs.inner.get(i).unwrap_or(&0usize);
|
|
|
|
let (res, overflowed) = a.overflowing_add(b);
|
|
if overflowed {
|
|
out.inner.push(res + carry);
|
|
carry = 1;
|
|
} else if res < core::usize::MAX {
|
|
out.inner.push(res + carry);
|
|
carry = 0;
|
|
} else {
|
|
out.inner.push(0usize);
|
|
carry = 1;
|
|
}
|
|
}
|
|
|
|
out
|
|
}
|
|
}
|
|
|
|
impl Sub for BigInt {
|
|
type Output = Self;
|
|
|
|
fn sub(self, rhs: Self) -> Self::Output {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
impl Mul for BigInt {
|
|
type Output = Self;
|
|
|
|
fn mul(self, rhs: Self) -> Self::Output {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
impl Div for BigInt {
|
|
type Output = Self;
|
|
|
|
fn div(self, rhs: Self) -> Self::Output {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
impl Rem for BigInt {
|
|
type Output = Self;
|
|
|
|
fn rem(self, rhs: Self) -> Self::Output {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
impl AddAssign for BigInt {
|
|
fn add_assign(&mut self, rhs: Self) {
|
|
*self = self.clone() + rhs;
|
|
}
|
|
}
|
|
|
|
impl SubAssign for BigInt {
|
|
fn sub_assign(&mut self, rhs: Self) {
|
|
*self = self.clone() - rhs;
|
|
}
|
|
}
|
|
|
|
impl MulAssign for BigInt {
|
|
fn mul_assign(&mut self, rhs: Self) {
|
|
*self = self.clone() * rhs;
|
|
}
|
|
}
|
|
|
|
impl DivAssign for BigInt {
|
|
fn div_assign(&mut self, rhs: Self) {
|
|
*self = self.clone() / rhs;
|
|
}
|
|
}
|
|
|
|
impl RemAssign for BigInt {
|
|
fn rem_assign(&mut self, rhs: Self) {
|
|
*self = self.clone() % rhs;
|
|
}
|
|
}
|
|
|
|
impl Neg for BigInt {
|
|
type Output = Self;
|
|
|
|
/// Flip the sign of the current `BigInt` value
|
|
fn neg(self) -> Self::Output {
|
|
let mut output = self.clone();
|
|
output.sign = !output.sign;
|
|
|
|
output
|
|
}
|
|
}
|
|
|
|
impl Not for BigInt {
|
|
type Output = Self;
|
|
|
|
/// Do a bitwise negation of every digit's value
|
|
fn not(self) -> Self::Output {
|
|
let mut flipped: Vec<usize> = Vec::with_capacity(self.inner.len());
|
|
|
|
for val in self.inner.iter() {
|
|
let rev = !*val;
|
|
flipped.push(rev);
|
|
}
|
|
|
|
BigInt {
|
|
sign: self.sign,
|
|
inner: flipped,
|
|
}
|
|
}
|
|
}
|
|
|
|
macro_rules! impl_from_smaller {
|
|
($(($s: ty, $u: ty)),* ) => {
|
|
$(
|
|
impl From<$s> for BigInt {
|
|
/// Create a `BigInt` from a signed integer primitive
|
|
fn from(n: $s) -> Self {
|
|
let sign = if n < 0 { Sign::Negative } else { Sign::Positive };
|
|
let n = n.abs();
|
|
let raw: usize = <$s>::try_into(n).unwrap();
|
|
|
|
Self {
|
|
inner: vec![raw],
|
|
sign,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<$u> for BigInt {
|
|
/// Create a `BigInt` from an unsigned integer primitive
|
|
fn from(n: $u) -> Self {
|
|
let mut new = Self::new_empty();
|
|
new.inner.push(n as usize);
|
|
|
|
new
|
|
}
|
|
}
|
|
)*
|
|
}
|
|
}
|
|
|
|
macro_rules! impl_from_larger {
|
|
($(($s: ty, $u: ty)),* ) => {
|
|
$(
|
|
impl From<$s> for BigInt {
|
|
/// Create a `BigInt` from a signed integer primitive
|
|
fn from(n: $s) -> Self {
|
|
todo!();
|
|
}
|
|
}
|
|
|
|
impl From<$u> for BigInt {
|
|
/// Create a `BigInt` from an unsigned integer primitive
|
|
fn from(n: $u) -> Self {
|
|
use core::usize::MAX;
|
|
|
|
let base_usize_value = n / MAX as $u;
|
|
let rem = n % MAX as $u;
|
|
|
|
if base_usize_value == 0 {
|
|
Self::from(rem as usize)
|
|
} else {
|
|
todo!();
|
|
}
|
|
}
|
|
}
|
|
)*
|
|
};
|
|
}
|
|
|
|
#[cfg(target_pointer_width = "32")]
|
|
impl_from_larger!((i64, u64), (i128, u128));
|
|
#[cfg(target_pointer_width = "32")]
|
|
impl_from_smaller!((i8, u8), (i16, u16), (i32, u32));
|
|
#[cfg(target_pointer_width = "32")]
|
|
static BITS:usize = 32;
|
|
|
|
#[cfg(target_pointer_width = "64")]
|
|
impl_from_larger!((i128, u128));
|
|
#[cfg(target_pointer_width = "64")]
|
|
impl_from_smaller!((i8, u8), (i16, u16), (i32, u32), (i64, u64));
|
|
#[cfg(target_pointer_width = "64")]
|
|
static BITS:usize = 64;
|
|
|
|
#[cfg(test)]
|
|
#[cfg_attr(tarpaulin, skip)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn sanity_checks() {
|
|
let int = BigInt::from(45u8);
|
|
assert_eq!(int.inner[0], 45usize)
|
|
}
|
|
|
|
#[test]
|
|
fn test_add() {
|
|
// MAX is 2^Bitsize - 1,
|
|
// so the sum should be
|
|
// [MAX -1, 1]
|
|
// Compare base 10: 9 + 9 = 18
|
|
let a = BigInt::from(core::usize::MAX);
|
|
let b = BigInt::from(core::usize::MAX);
|
|
|
|
let sum = a + b;
|
|
|
|
assert_eq!(
|
|
sum.inner[0],
|
|
core::usize::MAX - 1,
|
|
"least significant place should be MAX - 1"
|
|
);
|
|
assert_eq!(sum.inner[1], 1usize, "most significant place should be 1");
|
|
|
|
let a = BigInt::from(core::usize::MAX);
|
|
let b = BigInt::from(1usize);
|
|
let sum = a + b;
|
|
assert_eq!(sum.inner[0], 0usize);
|
|
assert_eq!(sum.inner[1], 1usize);
|
|
}
|
|
|
|
#[test]
|
|
fn test_not() {
|
|
let a = BigInt::from(0u8);
|
|
let b = !a;
|
|
|
|
assert_eq!(b.inner[0], core::usize::MAX);
|
|
}
|
|
|
|
#[test]
|
|
fn test_add_assign() {
|
|
let mut a = BigInt::from(core::usize::MAX);
|
|
let b = BigInt::from(core::usize::MAX);
|
|
|
|
a += b;
|
|
|
|
assert_eq!(
|
|
a.inner[0],
|
|
core::usize::MAX - 1,
|
|
"least significant place should be MAX - 1"
|
|
);
|
|
assert_eq!(a.inner[1], 1usize, "most significant place should be 1");
|
|
}
|
|
|
|
#[test]
|
|
fn test_from() {
|
|
// Signed numbers
|
|
assert_eq!(-BigInt::from(2), BigInt::from(-2));
|
|
|
|
// Larger than usize
|
|
assert_eq!(BigInt::from(45u128), BigInt::from(45usize));
|
|
}
|
|
}
|