1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
use crate::prelude::*;
use std::{collections::VecDeque, vec};
/// A loosely-packed arbitrary base big int.
/// See `Loose<BASE>` for implementation details.
pub type LooseInt<const BASE: usize> = BigInt<BASE, Loose<BASE>>;
/// A loosely-packed arbitrary base big int implementation.
/// Supports any base from 2-u64::MAX.
///
/// Each digit requires 8 bytes of storage, making this a somewhat space-inefficient
/// implementation. however, the lack of additional complexity improves runtime efficiency on the
/// tightly-packed implementation.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: LooseInt<10> = 593.into();
/// let b = a * 96.into();
/// assert_eq!(b, 56928.into());
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Loose<const BASE: usize> {
sign: Sign,
digits: Vec<Digit>,
}
impl<const BASE: usize> Loose<BASE> {
/// Create a new `Loose` int directly from a `Vec` of individual digits.
///
/// Ensure the resulting int is properly normalized, and that no digits are greater than or
/// equal to the base, to preserve soundness.
///
/// To construct a negative int from raw parts, simply apply the negation
/// operator (`-`) afterwards.
///
/// ```
/// use big_int::prelude::*;
///
/// assert_eq!(
/// -BigInt(unsafe { Loose::<10>::from_raw_parts(vec![1, 5]) }),
/// (-15).into()
/// );
/// ```
pub unsafe fn from_raw_parts(digits: Vec<Digit>) -> Self {
let sign = Positive;
Loose { sign, digits }
}
/// Extract the underlying digit Vec from the int.
///
/// Can only be used to recreate the original int with the unsafe `from_raw_parts` fn.
///
/// ```
/// use big_int::prelude::*;
///
/// assert_eq!(
/// LooseInt::<10>::from(539).0.digits(),
/// vec![5, 3, 9]
/// );
/// ```
pub fn digits(self) -> Vec<Digit> {
self.digits
}
}
impl<const BASE: usize> BigIntImplementation<BASE> for Loose<BASE> {
type Builder = LooseBuilder<{ BASE }>;
fn len(&self) -> usize {
self.digits.len()
}
fn get_digit(&self, digit: usize) -> Option<Digit> {
self.digits.get(digit).copied()
}
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Loose<10> = unsafe { Loose::from_raw_parts(vec![1, 2]) };
/// a.set_digit(1, 0);
/// assert_eq!(a, unsafe { Loose::from_raw_parts(vec![1, 0]) });
/// ```
fn set_digit(&mut self, digit: usize, value: Digit) {
if let Some(digit) = self.digits.get_mut(digit) {
*digit = value;
}
}
fn zero() -> Self {
let sign = Positive;
let digits = vec![0];
Loose { sign, digits }
}
fn with_sign(self, sign: Sign) -> Self {
Loose { sign, ..self }
}
/// Return a normalized version of the int. Remove trailing zeros, and disable the parity flag
/// if the resulting number is zero.
///
/// ```
/// use big_int::prelude::*;
///
/// let n = BigInt(unsafe { Loose::<10>::from_raw_parts(vec![0, 0, 8, 3]) });
/// assert_eq!(n.normalized(), 83.into());
/// ```
fn normalized(self) -> Self {
match self.digits.iter().position(|digit| *digit != 0) {
None => Self::zero(),
Some(pos @ 1..) => Loose {
digits: self.digits[pos..].to_vec(),
..self
},
_ => self,
}
}
type DigitIterator<'a> = LooseIter<'a, BASE>;
fn sign(&self) -> Sign {
self.sign
}
fn set_sign(&mut self, sign: Sign) {
self.sign = sign;
}
fn push_back(&mut self, digit: crate::Digit) {
self.digits.push(digit);
}
unsafe fn push_front(&mut self, digit: crate::Digit) {
self.digits.insert(0, digit);
}
fn shr_assign(&mut self, amount: usize) {
self.digits =
self.digits[..self.digits.len().checked_sub(amount).unwrap_or_default()].to_vec();
}
fn shl_assign(&mut self, amount: usize) {
self.digits.extend(vec![0; amount]);
}
fn iter<'a>(&'a self) -> Self::DigitIterator<'a> {
LooseIter {
index: 0,
back_index: self.len(),
int: self,
}
}
}
pub struct LooseIter<'a, const BASE: usize> {
index: usize,
back_index: usize,
int: &'a Loose<BASE>,
}
impl<const BASE: usize> Iterator for LooseIter<'_, BASE> {
type Item = Digit;
fn next(&mut self) -> Option<Self::Item> {
(self.index < self.back_index)
.then_some(&mut self.index)
.and_then(|index| {
*index += 1;
self.int.digits.get(*index - 1)
})
.copied()
}
}
impl<const BASE: usize> DoubleEndedIterator for LooseIter<'_, BASE> {
fn next_back(&mut self) -> Option<Self::Item> {
(self.back_index > self.index)
.then_some(&mut self.back_index)
.and_then(|index| {
*index -= 1;
self.int.digits.get(*index)
})
.copied()
}
}
#[derive(Debug)]
pub struct LooseBuilder<const BASE: usize> {
sign: Sign,
digits: VecDeque<Digit>,
}
impl<const BASE: usize> BigIntBuilder<BASE> for LooseBuilder<BASE> {
fn new() -> Self {
LooseBuilder {
sign: Positive,
digits: VecDeque::new(),
}
}
fn push_front(&mut self, digit: Digit) {
self.digits.push_front(digit);
}
fn push_back(&mut self, digit: Digit) {
self.digits.push_back(digit);
}
fn with_sign(self, sign: Sign) -> Self {
LooseBuilder { sign, ..self }
}
fn is_empty(&self) -> bool {
self.digits.is_empty()
}
}
impl<const BASE: usize> Build<Loose<BASE>> for LooseBuilder<BASE> {
fn build(self) -> Loose<BASE> {
Loose::<BASE>::from(self).normalized()
}
}
impl<const BASE: usize> From<LooseBuilder<BASE>> for Loose<BASE> {
fn from(value: LooseBuilder<BASE>) -> Self {
let sign = value.sign;
let digits = value.digits.into();
Loose { sign, digits }
}
}