big_int/lib.rs
1//! `big_int` - Arbitrary precision, arbitrary base integer arithmetic library.
2//!
3//! ```
4//! use big_int::prelude::*;
5//!
6//! let mut a: Loose<10> = "9000000000000000000000000000000000000000".parse().unwrap();
7//! a /= 13.into();
8//! assert_eq!(a, "692307692307692307692307692307692307692".parse().unwrap());
9//!
10//! let mut b: Loose<16> = a.convert();
11//! assert_eq!(b, "208D59C8D8669EDC306F76344EC4EC4EC".parse().unwrap());
12//! b >>= 16.into();
13//!
14//! let c: Loose<2> = b.convert();
15//! assert_eq!(c, "100000100011010101100111001000110110000110011010011110110111000011".parse().unwrap());
16//!
17//! let mut d: Tight<256> = c.convert();
18//! d += vec![15, 90, 0].into();
19//! assert_eq!(d, vec![2, 8, 213, 156, 141, 134, 121, 71, 195].into());
20//!
21//! let e: Tight<10> = d.convert();
22//! assert_eq!(format!("{e}"), "37530075201422313411".to_string());
23//! ```
24//!
25//! This crate contains five primary big int implementations:
26//! * `LooseBytes<BASE>` - A collection of loosely packed 8-bit byte values representing each digit.
27//! Slightly memory inefficient, but with minimal performance overhead.
28//! Capable of representing any base from 2-256.
29//! * `LooseShorts<BASE>` - A collection of loosely packed 16-bit short values representing each digit.
30//! Somewhat memory inefficient, but with minimal performance overhead.
31//! Capable of representing any base from 2-65536.
32//! * `LooseWords<BASE>` - A collection of loosely packed 32-bit word values representing each digit.
33//! Fairly memory inefficient, but with minimal performance overhead.
34//! Capable of representing any base from 2-2^32.
35//! * `Loose<BASE>` - A collection of loosely packed 64-bit ints representing each digit.
36//! Very memory inefficient, but with minimal performance overhead.
37//! Capable of representing any base from 2-2^64.
38//! * `Tight<BASE>` - A collection of tightly packed bits representing each digit.
39//! Maximally memory efficient, and capable of representing any base from
40//! 2-2^64. However, the additional indirection adds some performance overhead.
41//!
42//! Ints support most basic arithmetic operations, including addition, subtraction, multiplication,
43//! division, exponentiation, logarithm, nth root, and left/right shifting. Notably, shifting acts
44//! on the `BASE` of the associated number, increasing or decreasing the magnitude by powers of `BASE`
45//! as opposed to powers of 2.
46
47extern crate self as big_int;
48
49use std::{
50 cmp::Ordering,
51 fmt::Display,
52 ops::{
53 Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Shl, ShlAssign, Shr, ShrAssign, Sub,
54 SubAssign,
55 },
56 str::FromStr,
57};
58
59use error::{BigIntError, ParseError};
60use get_back::GetBack;
61
62use self::Sign::*;
63
64pub use big_int_proc::*;
65
66pub mod prelude {
67 //! Default exports: includes `Loose`, `Tight`, `Sign`, & `Denormal`
68 pub use crate::denormal::*;
69 pub use crate::loose::*;
70 pub use crate::tight::*;
71 pub use crate::Sign::*;
72 pub use crate::*;
73}
74
75mod tests;
76
77pub(crate) mod test_utils;
78
79pub mod base64;
80pub mod denormal;
81pub mod error;
82pub mod get_back;
83pub mod loose;
84pub mod tight;
85
86/// Standard alphabet used when translating between text and big ints.
87pub const STANDARD_ALPHABET: &str =
88 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
89
90/// Size of an individual big int digit.
91pub type Digit = u64;
92pub(crate) type DoubleDigit = u128;
93
94/// Safely create a bitmask of `n` bits in size shifted
95/// to the right side of the number without overflowing.
96#[macro_export(local_inner_macros)]
97macro_rules! mask {
98 ($n:expr) => {
99 (((1 << (($n) - 1)) - 1) << 1) + 1
100 };
101}
102
103/// A big int.
104///
105/// Represents an arbitrary precision, arbitrary base natural number.
106///
107/// Supports basic arithmetic operations, as well as all utilities necessary for
108/// coercing to and from various builtin types, such as primitive int types, `Vec`s, and `String`s.
109///
110/// ### For implementors:
111/// If implementing this trait for your own type, don't be alarmed by the massive list of `Self`
112/// constraints. Use the included derive macro `big_int::BigIntTraits` to automatically derive
113/// all traits using default `*_inner` implementations pre-provided by `BigInt`.
114///
115/// At least one of `normalize` or `normalized` must be defined to prevent recursion.\
116/// At least one of `shl_inner` or `shl_assign_inner` must be defined to prevent recursion.\
117/// At least one of `shr_inner` or `shr_assign_inner` must be defined to prevent recursion.\
118///
119/// ```
120/// use big_int::prelude::*;
121///
122/// let mut a = TightBuilder::<10>::new();
123/// a.push_back(1);
124/// a.push_back(0);
125/// a.push_back(4);
126/// let a: DenormalTight<10> = a.into();
127/// let a: Tight<10> = a.unwrap();
128/// assert_eq!(a, 104.into());
129/// ```
130pub trait BigInt<const BASE: usize>
131where
132 Self: GetBack<Item = Digit>
133 + Clone
134 + Default
135 + std::fmt::Debug
136 + Display
137 + PartialEq
138 + Eq
139 + PartialOrd
140 + Ord
141 + Neg<Output = Self>
142 + Add<Output = Self>
143 + AddAssign
144 + Sub<Output = Self>
145 + SubAssign
146 + Div<Output = Self>
147 + DivAssign
148 + Mul<Output = Self>
149 + MulAssign
150 + Shl<Output = Self>
151 + ShlAssign
152 + Shr<Output = Self>
153 + ShrAssign
154 + FromStr<Err = BigIntError>
155 + FromIterator<Digit>
156 + IntoIterator<Item = Digit, IntoIter = BigIntIntoIter<BASE, Self>>
157 + From<Vec<Digit>>
158 + From<u8>
159 + From<u16>
160 + From<u32>
161 + From<u64>
162 + From<u128>
163 + From<usize>
164 + From<i8>
165 + From<i16>
166 + From<i32>
167 + From<i64>
168 + From<i128>
169 + From<isize>
170 + Into<u8>
171 + Into<u16>
172 + Into<u32>
173 + Into<u64>
174 + Into<u128>
175 + Into<usize>
176 + Into<i8>
177 + Into<i16>
178 + Into<i32>
179 + Into<i64>
180 + Into<i128>
181 + Into<isize>,
182{
183 type Builder: BigIntBuilder<{ BASE }> + Into<Self::Denormal> + Into<Self>;
184 type Denormal: BigInt<BASE> + From<Self> + UnsafeInto<Self> + Unwrap<Self>;
185
186 const BITS_PER_DIGIT: usize = bits_per_digit(BASE);
187
188 /// Default implementation of `big_int::GetBack`.
189 ///
190 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
191 fn get_back_inner(&self, index: usize) -> Option<Digit> {
192 self.len()
193 .checked_sub(index)
194 .and_then(|index| self.get_digit(index))
195 }
196
197 /// Default implementation of `Default`.
198 ///
199 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
200 fn default_inner() -> Self {
201 Self::zero()
202 }
203
204 /// Default implementation of `Display`.
205 ///
206 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
207 fn fmt_inner(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 write!(
209 f,
210 "{}",
211 self.display(STANDARD_ALPHABET)
212 .map_err(|_| std::fmt::Error)?
213 )
214 }
215
216 /// Default implementation of `PartialOrd`.
217 ///
218 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
219 fn partial_cmp_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> Option<Ordering> {
220 Some(self.cmp_inner(other))
221 }
222
223 /// Default implementation of `Ord`.
224 ///
225 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
226 fn cmp_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> Ordering {
227 if self.is_zero() && other.is_zero() {
228 Ordering::Equal
229 } else {
230 match (self.sign(), other.sign()) {
231 (Positive, Negative) => Ordering::Greater,
232 (Negative, Positive) => Ordering::Less,
233 (Positive, Positive) => self.cmp_magnitude(other),
234 (Negative, Negative) => other.cmp_magnitude(self),
235 }
236 }
237 }
238
239 /// Default implementation of `PartialEq`.
240 ///
241 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
242 fn eq_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> bool {
243 matches!(self.cmp_inner(other), Ordering::Equal)
244 }
245
246 /// Default implementation of `Neg`.
247 ///
248 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
249 fn neg_inner(self) -> Self::Denormal {
250 let sign = self.sign();
251 self.with_sign(-sign).into()
252 }
253
254 /// Default implementation of `Add`.
255 ///
256 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
257 fn add_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(self, rhs: RHS) -> OUT::Denormal {
258 if self.sign() != rhs.sign() {
259 self.sub_inner::<_, OUT>(rhs.neg())
260 } else {
261 let sign = self.sign();
262 let mut carry = 0;
263 let mut result = OUT::Builder::new();
264 for i in 1.. {
265 match (self.get_back(i), rhs.get_back(i), carry) {
266 (None, None, 0) => break,
267 (left_digit, right_digit, carry_in) => {
268 let left_digit = left_digit.unwrap_or_default() as DoubleDigit;
269 let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
270 let mut sum = left_digit + right_digit + carry_in;
271 if sum >= BASE as DoubleDigit {
272 sum -= BASE as DoubleDigit;
273 carry = 1;
274 } else {
275 carry = 0;
276 }
277 result.push_front(sum as Digit);
278 }
279 }
280 }
281 result.with_sign(sign).into()
282 }
283 }
284
285 /// Default implementation of `AddAssign`.
286 ///
287 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
288 ///
289 /// If this method is used directly, it may cause the number to become denormalized.
290 unsafe fn add_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
291 if self.sign() != rhs.sign() {
292 self.sub_assign_inner(rhs.neg_inner());
293 } else {
294 let self_len = self.len();
295 let mut carry = 0;
296 for i in 1.. {
297 match (self.get_back(i), rhs.get_back(i), carry) {
298 (None, None, 0) => break,
299 (left_digit, right_digit, carry_in) => {
300 let left_digit = left_digit.unwrap_or_default() as DoubleDigit;
301 let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
302 let mut sum = left_digit + right_digit + carry_in;
303 if sum >= BASE as DoubleDigit {
304 sum -= BASE as DoubleDigit;
305 carry = 1;
306 } else {
307 carry = 0;
308 }
309 if i <= self_len {
310 self.set_digit(self_len - i, sum as Digit);
311 } else {
312 self.push_front(sum as Digit);
313 }
314 }
315 }
316 }
317 }
318 }
319
320 /// Default implementation of `Sub`.
321 ///
322 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
323 fn sub_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
324 mut self,
325 rhs: RHS,
326 ) -> OUT::Denormal {
327 if self.sign() != rhs.sign() {
328 self.add_inner::<_, OUT>(rhs.neg_inner())
329 } else if rhs.cmp_magnitude(&self).is_gt() {
330 unsafe { rhs.sub_inner::<_, OUT>(self).unsafe_into() }.neg_inner()
331 } else {
332 let sign = self.sign();
333 let mut result = OUT::Builder::new();
334 let self_len = self.len();
335 for i in 1.. {
336 match (self.get_back(i), rhs.get_back(i)) {
337 (None, None) => break,
338 (left_digit, right_digit) => {
339 let mut left_digit = left_digit.unwrap_or_default() as DoubleDigit;
340 let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
341 if left_digit < right_digit {
342 for j in i + 1.. {
343 match self.get_back(j) {
344 None => unreachable!("big int subtraction with overflow"),
345 Some(0) => {
346 self.set_digit(self_len - j, (BASE - 1) as Digit);
347 }
348 Some(digit) => {
349 self.set_digit(self_len - j, digit - 1);
350 break;
351 }
352 }
353 }
354 left_digit += BASE as DoubleDigit;
355 }
356 result.push_front((left_digit - right_digit) as Digit);
357 }
358 }
359 }
360 result.with_sign(sign).into()
361 }
362 }
363
364 /// Default implementation of `SubAssign`.
365 ///
366 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
367 ///
368 /// If this method is used directly, it may cause the number to become denormalized.
369 unsafe fn sub_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
370 if self.sign() != rhs.sign() {
371 self.add_assign_inner(rhs.neg_inner());
372 } else if rhs.cmp_magnitude(self).is_gt() {
373 *self = rhs
374 .sub_inner::<_, Self>(self.clone())
375 .unsafe_into()
376 .neg_inner()
377 .unsafe_into();
378 } else {
379 let self_len = self.len();
380 for i in 1.. {
381 match (self.get_back(i), rhs.get_back(i)) {
382 (None, None) => break,
383 (left_digit, right_digit) => {
384 let mut left_digit = left_digit.unwrap_or_default() as DoubleDigit;
385 let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
386 if left_digit < right_digit {
387 for j in i + 1.. {
388 match self.get_back(j) {
389 None => unreachable!("big int subtraction with overflow"),
390 Some(0) => {
391 self.set_digit(self_len - j, (BASE - 1) as Digit);
392 }
393 Some(digit) => {
394 self.set_digit(self_len - j, digit - 1);
395 break;
396 }
397 }
398 }
399 left_digit += BASE as DoubleDigit;
400 }
401 let difference = (left_digit - right_digit) as Digit;
402 if i <= self_len {
403 self.set_digit(self_len - i, difference);
404 } else {
405 self.push_front(difference);
406 }
407 }
408 }
409 }
410 }
411 }
412
413 /// Default implementation of `Mul`.
414 ///
415 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
416 fn mul_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
417 mut self,
418 mut rhs: RHS,
419 ) -> OUT::Denormal {
420 let sign = self.sign() * rhs.sign();
421 self.set_sign(Positive);
422 rhs.set_sign(Positive);
423 let mut shift = 0;
424 if !self.is_zero() {
425 while let Some(0) = self.get_back(1) {
426 unsafe {
427 self.shr_assign_inner(1);
428 }
429 shift += 1;
430 }
431 }
432 if !rhs.is_zero() {
433 while let Some(0) = rhs.get_back(1) {
434 unsafe {
435 rhs.shr_assign_inner(1);
436 }
437 shift += 1;
438 }
439 }
440 let mut result = OUT::zero();
441 let mut addends = rhs.clone().addends().memo();
442 for digit in self.into_iter().rev() {
443 for index in 0..Self::BITS_PER_DIGIT {
444 if digit & (1 << index) != 0 {
445 unsafe {
446 result.add_assign_inner(addends.get(index).unwrap().clone());
447 }
448 }
449 unsafe {
450 addends.get_mut(index).unwrap().shl_assign_inner(1);
451 }
452 }
453 }
454 OUT::from(result.with_sign(sign)).shl_inner(shift)
455 }
456
457 /// Default implementation of `MulAssign`.
458 ///
459 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
460 ///
461 /// If this method is used directly, it may cause the number to become denormalized.
462 unsafe fn mul_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
463 *self = self.clone().mul_inner::<_, Self>(rhs).unsafe_into();
464 }
465
466 /// Default implementation of `Div`.
467 ///
468 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
469 fn div_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(self, rhs: RHS) -> OUT::Denormal {
470 self.div_rem_inner::<_, OUT>(rhs).unwrap().0
471 }
472
473 /// Default implementation of `DivAssign`.
474 ///
475 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
476 ///
477 /// If this method is used directly, it may cause the number to become denormalized.
478 unsafe fn div_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
479 *self = self
480 .clone()
481 .div_rem_inner::<_, Self>(rhs)
482 .unwrap()
483 .0
484 .unsafe_into();
485 }
486
487 /// Default implementation of `FromStr`.
488 ///
489 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
490 ///
491 /// ### Errors:
492 /// * `ParseFailed` if parsing of the string fails.
493 fn from_str_inner(s: &str) -> Result<Self::Denormal, BigIntError> {
494 Self::parse(s, STANDARD_ALPHABET).map_err(BigIntError::ParseFailed)
495 }
496
497 /// Default implementation of `FromIterator`.
498 ///
499 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
500 fn from_iter_inner<T: IntoIterator<Item = Digit>>(iter: T) -> Self::Denormal {
501 let mut builder = Self::Builder::new();
502 for digit in iter {
503 builder.push_back(digit);
504 }
505 builder.into()
506 }
507
508 /// Default implementation of `From<_>` for all unsigned primitive int types.
509 ///
510 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
511 fn from_u128_inner(mut value: u128) -> Self::Denormal {
512 let base = BASE as u128;
513 let mut result = Self::Builder::new();
514 while value >= base {
515 let (new_value, rem) = (value / base, value % base);
516 value = new_value;
517 result.push_front(rem as Digit);
518 }
519 result.push_front(value as Digit);
520 result.into()
521 }
522
523 /// Default implementation of `From<_>` for all signed primitive int types.
524 ///
525 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
526 fn from_i128_inner(value: i128) -> Self::Denormal {
527 if value < 0 {
528 -Self::from_u128_inner((-value) as u128)
529 } else {
530 Self::from_u128_inner(value as u128)
531 }
532 }
533
534 /// Default implementation of `Into<_>` for all unsigned primitive int types.
535 ///
536 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
537 fn into_u128_inner(self) -> u128 {
538 if self.sign() == Negative {
539 panic!("uint conversion with underflow");
540 }
541 let mut total: u128 = 0;
542 let mut place: u128 = 0;
543 for digit in self.into_iter().rev() {
544 place = if place == 0 { 1 } else { place * BASE as u128 };
545 total += (digit as u128) * place;
546 }
547 total
548 }
549
550 /// Default implementation of `Into<_>` for all signed primitive int types.
551 ///
552 /// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
553 fn into_i128_inner(self) -> i128 {
554 let mut total: i128 = 0;
555 let mut place: i128 = 0;
556 let sign = self.sign();
557 for digit in self.into_iter().rev() {
558 place = if place == 0 { 1 } else { place * BASE as i128 };
559 total += (digit as i128) * place;
560 }
561 if sign == Negative {
562 total = -total;
563 }
564 total
565 }
566
567 /// The length of the big int in digits.
568 ///
569 /// ```
570 /// use big_int::prelude::*;
571 ///
572 /// let a: Tight<10> = 211864.into();
573 /// assert_eq!(a.len(), 6);
574 /// ```
575 fn len(&self) -> usize;
576
577 /// Get the digit of the big int at position `digit`,
578 /// or None if the number does not have that many digits.
579 ///
580 ///
581 /// ```
582 /// use big_int::prelude::*;
583 ///
584 /// let a: Tight<10> = 12345.into();
585 /// assert_eq!(a.get_digit(2), Some(3));
586 /// assert_eq!(a.get_digit(6), None);
587 /// ```
588 fn get_digit(&self, digit: usize) -> Option<Digit>;
589
590 /// Set the digit of the big int to `value` at position `digit`.
591 ///
592 /// If the set digit causes the leftmost digit of the number to be zero,
593 /// the number will become denormal, and should be normalized before being used.
594 ///
595 /// ```
596 /// use big_int::prelude::*;
597 ///
598 /// let mut a: Tight<10> = 10000.into();
599 /// a.set_digit(1, 7);
600 /// a.set_digit(4, 9);
601 /// assert_eq!(a, 17009.into());
602 /// ```
603 fn set_digit(&mut self, digit: usize, value: Digit);
604
605 /// The value zero represented as a big int.
606 ///
607 /// ```
608 /// use big_int::prelude::*;
609 ///
610 /// let a: Tight<10> = 13.into();
611 /// let b = 13.into();
612 /// assert_eq!(a - b, BigInt::zero());
613 /// ```
614 fn zero() -> Self;
615
616 /// Check if the big int is zero.
617 ///
618 /// ```
619 /// use big_int::prelude::*;
620 ///
621 /// let a: Tight<10> = 13.into();
622 /// let b = 13.into();
623 /// assert!((a - b).is_zero());
624 /// ```
625 fn is_zero(&self) -> bool {
626 self.iter().all(|digit| digit == 0)
627 }
628
629 /// The sign of the big int.
630 ///
631 /// ```
632 /// use big_int::prelude::*;
633 ///
634 /// let mut a: Tight<10> = 5.into();
635 /// assert_eq!(a.sign(), Positive);
636 /// a -= 14.into();
637 /// assert_eq!(a.sign(), Negative);
638 /// ```
639 fn sign(&self) -> Sign;
640
641 /// The big int with the given sign.
642 ///
643 /// ```
644 /// use big_int::prelude::*;
645 ///
646 /// let a: Tight<10> = 95.into();
647 /// assert_eq!(a.with_sign(Negative), (-95).into());
648 /// ```
649 fn with_sign(self, sign: Sign) -> Self;
650
651 /// Set the sign of the big int to `sign`.
652 ///
653 /// ```
654 /// use big_int::prelude::*;
655 ///
656 /// let mut a: Tight<10> = (-109).into();
657 /// a.set_sign(Positive);
658 /// assert_eq!(a, 109.into());
659 /// ```
660 fn set_sign(&mut self, sign: Sign);
661
662 /// Append a digit to the right side of the int. Equivalent to `(int << 1) + digit`
663 ///
664 /// ```
665 /// use big_int::prelude::*;
666 ///
667 /// let mut a: Tight<10> = 6.into();
668 /// a.push_back(1);
669 /// assert_eq!(a, 61.into());
670 /// ```
671 fn push_back(&mut self, digit: Digit);
672
673 /// Append a digit to the left side of the int.
674 ///
675 /// If a zero is pushed onto the end
676 /// of the int, it will become denormalized.
677 ///
678 /// ```
679 /// use big_int::prelude::*;
680 ///
681 /// let mut a: Tight<10> = 6.into();
682 /// unsafe {
683 /// a.push_front(1);
684 /// }
685 /// assert_eq!(a.normalized(), 16.into());
686 /// ```
687 unsafe fn push_front(&mut self, digit: Digit);
688
689 /// Pop the rightmost digit from the end of the int, and return it.
690 ///
691 /// If the last digit is popped, the number will become denormalized.
692 ///
693 /// ```
694 /// use big_int::prelude::*;
695 ///
696 /// let mut a: Tight<10> = 651.into();
697 /// let digit = unsafe { a.pop_back() };
698 /// assert_eq!(a, 65.into());
699 /// assert_eq!(digit, Some(1));
700 /// ```
701 unsafe fn pop_back(&mut self) -> Option<Digit>;
702
703 /// Pop the leftmost digit from the end of the int, and return it.
704 ///
705 /// If the last digit is popped, the number will become denormalized.
706 ///
707 /// ```
708 /// use big_int::prelude::*;
709 ///
710 /// let mut a: Tight<10> = 651.into();
711 /// let digit = unsafe { a.pop_front() };
712 /// assert_eq!(a, 51.into());
713 /// assert_eq!(digit, Some(6));
714 /// ```
715 unsafe fn pop_front(&mut self) -> Option<Digit>;
716
717 /// Divide the int by BASE^amount.
718 ///
719 /// Note: works in powers of BASE, not in powers of 2.
720 ///
721 /// Defined in terms of `shr_assign`; at least one of `shr`
722 /// or `shr_assign` must be defined by implementers.
723 ///
724 /// Also acts as the default implementation of the `Shr` trait,
725 /// as provided automatically by `big_int_proc::BigIntTraits`.
726 ///
727 /// ```
728 /// use big_int::prelude::*;
729 ///
730 /// let a: Tight<10> = 600.into();
731 /// assert_eq!(a.shr_inner(2), 6.into());
732 /// ```
733 fn shr_inner(mut self, amount: usize) -> Self::Denormal {
734 unsafe {
735 self.shr_assign_inner(amount);
736 }
737 self.into()
738 }
739
740 /// Divide the int by BASE^amount in place.
741 ///
742 /// Note: works in powers of BASE, not in powers of 2.
743 ///
744 /// Defined in terms of `shr`; at least one of `shr`
745 /// or `shr_assign` must be defined by implementers.
746 ///
747 /// Also acts as the default implementation of the `ShrAssign` trait,
748 /// as provided automatically by `big_int_proc::BigIntTraits`.
749 ///
750 /// If the last number is shifted off, may cause the number to become denormalized.
751 ///
752 /// ```
753 /// use big_int::prelude::*;
754 ///
755 /// let mut a: Tight<10> = 600.into();
756 /// unsafe {
757 /// a.shr_assign_inner(2);
758 /// }
759 /// assert_eq!(a, 6.into());
760 /// ```
761 unsafe fn shr_assign_inner(&mut self, amount: usize) {
762 *self = self.clone().shr_inner(amount).unsafe_into();
763 }
764
765 /// Multiply the int by BASE^amount.
766 ///
767 /// Note: works in powers of BASE, not in powers of 2.
768 ///
769 /// Defined in terms of `shl_assign`; at least one of `shl`
770 /// or `shl_assign` must be defined by implementers.
771 ///
772 /// Also acts as the default implementation of the `Shl` trait,
773 /// as provided automatically by `big_int_proc::BigIntTraits`.
774 ///
775 /// ```
776 /// use big_int::prelude::*;
777 ///
778 /// let a: Tight<10> = 3.into();
779 /// assert_eq!(a.shl_inner(2), 300.into());
780 /// ```
781 fn shl_inner(mut self, amount: usize) -> Self::Denormal {
782 unsafe {
783 self.shl_assign_inner(amount);
784 }
785 self.into()
786 }
787
788 /// Multiply the int by BASE^amount in place.
789 ///
790 /// Note: works in powers of BASE, not in powers of 2.
791 ///
792 /// Defined in terms of `shl`; at least one of `shl`
793 /// or `shl_assign` must be defined by implementers.
794 ///
795 /// Also acts as the default implementation of the `ShlAssign` trait,
796 /// as provided automatically by `big_int_proc::BigIntTraits`.
797 ///
798 /// ```
799 /// use big_int::prelude::*;
800 ///
801 /// let mut a: Tight<10> = 3.into();
802 /// unsafe {
803 /// a.shl_assign_inner(2);
804 /// }
805 /// assert_eq!(a, 300.into());
806 /// ```
807 unsafe fn shl_assign_inner(&mut self, amount: usize) {
808 *self = self.clone().shl_inner(amount).unsafe_into();
809 }
810
811 /// Divide one int by another, returning the quotient & remainder as a pair.
812 /// Returns the result as a denormalized pair.
813 ///
814 /// ### Errors:
815 /// * `DivisionByZero` if `rhs` is zero.
816 ///
817 /// ```
818 /// use big_int::prelude::*;
819 ///
820 /// let a: Loose<10> = 999_999_999.into();
821 /// let b: Loose<10> = 56_789.into();
822 /// assert_eq!(a.div_rem_inner::<_, Loose<10>>(b), Ok((17_609.into(), 2_498.into())));
823 /// ```
824 fn div_rem_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
825 mut self,
826 mut rhs: RHS,
827 ) -> Result<(OUT::Denormal, OUT::Denormal), BigIntError> {
828 if rhs.is_zero() {
829 return Err(BigIntError::DivisionByZero);
830 }
831 if rhs.len() > self.len() {
832 return Ok((OUT::Denormal::zero(), self.convert_inner::<BASE, OUT>()));
833 }
834 let mut shift = 0;
835 while let (Some(0), Some(0)) = (self.get_back(1), rhs.get_back(1)) {
836 unsafe {
837 self.shr_assign_inner(1);
838 rhs.shr_assign_inner(1);
839 }
840 shift += 1;
841 }
842 let sign = self.sign() * rhs.sign();
843 self.set_sign(Positive);
844 rhs.set_sign(Positive);
845 let quot_digits = self.len() - rhs.len() + 1;
846 let mut quot = OUT::Builder::new();
847 let mut prod = Self::zero();
848 let mut addends = rhs.clone().shl_inner(quot_digits - 1).addends().memo();
849
850 for _ in 0..quot_digits {
851 let mut digit_value = 0;
852 for index in (0..Self::BITS_PER_DIGIT).rev() {
853 let power = 1 << index;
854 let new_prod = unsafe {
855 prod.clone()
856 .add_inner::<_, Self>(addends.get(index).unwrap().clone())
857 .unsafe_into()
858 };
859 if new_prod <= self {
860 digit_value += power;
861 prod = new_prod;
862 }
863 unsafe {
864 addends.get_mut(index).unwrap().shr_assign_inner(1);
865 }
866 }
867 quot.push_back(digit_value);
868 }
869
870 let mut rem: OUT::Denormal = self.sub_inner::<_, OUT>(prod);
871 if !rem.is_zero() {
872 rem.set_sign(sign);
873 }
874 unsafe {
875 rem.shl_assign_inner(shift);
876 }
877
878 Ok((quot.with_sign(sign).into(), rem))
879 }
880
881 /// Divide one int by another, returning the quotient & remainder as a pair.
882 ///
883 /// ### Errors:
884 /// * `DivisionByZero` if `rhs` is zero.
885 ///
886 /// ```
887 /// use big_int::prelude::*;
888 ///
889 /// let a: Loose<10> = 999_999_999.into();
890 /// let b: Loose<10> = 56_789.into();
891 /// assert_eq!(a.div_rem::<_, Loose<10>>(b), Ok((17_609.into(), 2_498.into())));
892 /// ```
893 fn div_rem<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
894 self,
895 rhs: RHS,
896 ) -> Result<(OUT, OUT), BigIntError> {
897 self.div_rem_inner::<RHS, OUT>(rhs)
898 .map(|(q, r): (OUT::Denormal, OUT::Denormal)| (q.unwrap(), r.unwrap()))
899 }
900
901 /// Exponentiate the big int by `rhs`.
902 /// Returns the result as a denormalized number.
903 ///
904 /// ### Errors:
905 /// * `NegativeExponentiation` if `rhs` is negative.
906 ///
907 /// ```
908 /// use big_int::prelude::*;
909 ///
910 /// let a: Loose<10> = 10.into();
911 /// let b: Loose<10> = a.exp::<Loose<10>, Loose<10>>(3.into()).unwrap();
912 /// assert_eq!(b, 1000.into());
913 /// ```
914 fn exp_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
915 self,
916 mut rhs: RHS,
917 ) -> Result<OUT::Denormal, BigIntError> {
918 if rhs < RHS::zero() {
919 return Err(BigIntError::NegativeExponentiation);
920 }
921 let mut mullands = self.mullands().memo();
922 let mut addends = RHS::from(1).addends().memo();
923 let mut power = 0;
924 let mut result: OUT = 1.into();
925 while rhs.cmp_inner(addends.get(power).unwrap()).is_ge() {
926 rhs -= addends.get(power).unwrap().clone();
927 unsafe {
928 result.mul_assign_inner(mullands.get(power).unwrap().clone());
929 }
930 power += 1;
931 }
932 for mulland_index in (0..power).rev() {
933 let comparison = rhs.cmp_inner(addends.get(mulland_index).unwrap());
934 if comparison.is_ge() {
935 rhs -= addends.get(mulland_index).unwrap().clone();
936 unsafe {
937 result.mul_assign_inner(mullands.get(mulland_index).unwrap().clone());
938 }
939 if comparison.is_eq() {
940 break;
941 }
942 }
943 }
944 Ok(result.into())
945 }
946
947 /// Exponentiate the big int by `rhs`.
948 ///
949 /// ### Errors:
950 /// * `NegativeExponentiation` if `rhs` is negative.
951 ///
952 /// ```
953 /// use big_int::prelude::*;
954 ///
955 /// let a: Loose<10> = 10.into();
956 /// let b: Loose<10> = a.exp::<Loose<10>, Loose<10>>(3.into()).unwrap();
957 /// assert_eq!(b, 1000.into());
958 /// ```
959 fn exp<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
960 self,
961 rhs: RHS,
962 ) -> Result<OUT, BigIntError> {
963 self.exp_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
964 }
965
966 /// Compute the logarithm of the big int with the base `rhs`.
967 /// Returns the result as a denormalized number.
968 ///
969 /// ### Errors:
970 /// * `NonPositiveLogarithm` if the number is less than 1.
971 /// * `LogOfSmallBase` if `rhs` is less than 2.
972 ///
973 /// ```
974 /// use big_int::prelude::*;
975 ///
976 /// let a: Loose<10> = 1000.into();
977 /// let b: Loose<10> = a.log::<Loose<10>, Loose<10>>(10.into()).unwrap();
978 /// assert_eq!(b, 3.into());
979 /// ```
980 fn log_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
981 self,
982 rhs: RHS,
983 ) -> Result<OUT::Denormal, BigIntError> {
984 if self <= Self::zero() {
985 return Err(BigIntError::NonPositiveLogarithm);
986 }
987 if rhs <= 1.into() {
988 return Err(BigIntError::LogOfSmallBase);
989 }
990 let mut mullands = rhs.mullands().memo();
991 let mut addends = OUT::from(1).addends().memo();
992 let mut power = 0;
993 let mut base: Self = 1.into();
994 let mut exp = OUT::zero();
995 let result = 'outer: {
996 loop {
997 let next_base: Self = unsafe {
998 base.clone()
999 .mul_inner::<RHS, Self>(mullands.get(power).unwrap().clone())
1000 .unsafe_into()
1001 };
1002 let comparison = next_base.cmp_inner(&self);
1003 if comparison.is_le() {
1004 exp += addends.get(power).unwrap().clone();
1005 base = next_base;
1006 power += 1;
1007 }
1008 if comparison.is_ge() {
1009 break;
1010 }
1011 }
1012 for mulland_index in (0..power).rev() {
1013 let next_base: Self = unsafe {
1014 base.clone()
1015 .mul_inner::<RHS, Self>(mullands.get(mulland_index).unwrap().clone())
1016 .unsafe_into()
1017 };
1018 let comparison = next_base.cmp_inner(&self);
1019 if comparison.is_le() {
1020 exp += addends.get(mulland_index).unwrap().clone();
1021 if comparison.is_eq() {
1022 break 'outer exp;
1023 }
1024 base = next_base;
1025 }
1026 }
1027 exp
1028 };
1029 Ok(result.into())
1030 }
1031
1032 /// Compute the logarithm of the big int with the base `rhs`.
1033 ///
1034 /// ### Errors:
1035 /// * `NonPositiveLogarithm` if the number is less than 1.
1036 /// * `LogOfSmallBase` if `rhs` is less than 2.
1037 ///
1038 /// ```
1039 /// use big_int::prelude::*;
1040 ///
1041 /// let a: Loose<10> = 1000.into();
1042 /// let b: Loose<10> = a.log::<Loose<10>, Loose<10>>(10.into()).unwrap();
1043 /// assert_eq!(b, 3.into());
1044 /// ```
1045 fn log<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
1046 self,
1047 rhs: RHS,
1048 ) -> Result<OUT, BigIntError> {
1049 self.log_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
1050 }
1051
1052
1053 // these are actually slower than the generalized function...
1054
1055 // /// Compute the square root of the big int.
1056 // /// Returns the result as a denormalized number.
1057 // ///
1058 // /// ### Errors:
1059 // /// * `NegativeRoot` if the number is negative.
1060 // ///
1061 // /// ```
1062 // /// use big_int::prelude::*;
1063 // ///
1064 // /// let a: Loose<10> = 100.into();
1065 // /// assert_eq!(a.sqrt::<Loose<10>>().unwrap(), 10.into());
1066 // /// ```
1067 // fn sqrt_inner<OUT: BigInt<{ BASE }>>(self) -> Result<OUT::Denormal, BigIntError> {
1068 // if self < Self::zero() {
1069 // return Err(BigIntError::NegativeRoot);
1070 // }
1071 // if self.is_zero() {
1072 // return Ok(OUT::Denormal::zero());
1073 // }
1074 // let mut sq_addends = OUT::from(1).n_addends(4.into()).memo();
1075 // let mut base_addends = OUT::from(1).addends().memo();
1076 // let mut index = 0;
1077 // loop {
1078 // let comparison = sq_addends.get(index + 1).unwrap().cmp_inner(&self);
1079 // if comparison.is_le() {
1080 // index += 1;
1081 // if comparison.is_eq() {
1082 // return Ok(base_addends.get(index).unwrap().clone().into());
1083 // }
1084 // } else {
1085 // break;
1086 // }
1087 // }
1088 // let mut square = sq_addends.get(index).unwrap().clone();
1089 // let mut base = base_addends.get(index).unwrap().clone();
1090 // for i in (0..index).rev() {
1091 // let base_addition = base_addends.get(i).unwrap().clone();
1092 // let sq_addition = sq_addends.get(i).unwrap().clone();
1093 // let mut middle_part = base.clone() * base_addition.clone();
1094 // middle_part += middle_part.clone();
1095 // let new_square = square.clone() + middle_part + sq_addition;
1096 // let comparison = new_square.cmp_inner(&self);
1097 // if comparison.is_le() {
1098 // base += base_addition;
1099 // if comparison.is_eq() {
1100 // break;
1101 // }
1102 // square = new_square;
1103 // }
1104 // }
1105 // Ok(base.into())
1106 // }
1107
1108 // /// Compute the square root of the big int.
1109 // ///
1110 // /// ### Errors:
1111 // /// * `NegativeRoot` if the number is negative.
1112 // ///
1113 // /// ```
1114 // /// use big_int::prelude::*;
1115 // ///
1116 // /// let a: Loose<10> = 100.into();
1117 // /// assert_eq!(a.sqrt::<Loose<10>>().unwrap(), 10.into());
1118 // /// ```
1119 // fn sqrt<OUT: BigInt<{ BASE }>>(self) -> Result<OUT, BigIntError> {
1120 // self.sqrt_inner::<OUT>().map(|x| x.unwrap())
1121 // }
1122
1123 // /// Compute the cube root of the big int.
1124 // /// Returns the result as a denormalized number.
1125 // ///
1126 // /// ### Errors:
1127 // /// * `NegativeRoot` if the number is negative.
1128 // ///
1129 // /// ```
1130 // /// use big_int::prelude::*;
1131 // ///
1132 // /// let a: Loose<10> = 1000.into();
1133 // /// assert_eq!(a.cbrt::<Loose<10>>().unwrap(), 10.into());
1134 // /// ```
1135 // fn cbrt_inner<OUT: BigInt<{ BASE }>>(self) -> Result<OUT::Denormal, BigIntError> {
1136 // if self < Self::zero() {
1137 // return Err(BigIntError::NegativeRoot);
1138 // }
1139 // if self.is_zero() {
1140 // return Ok(OUT::Denormal::zero());
1141 // }
1142 // let mut cb_addends = OUT::from(1).n_addends(8.into()).memo();
1143 // let mut base_addends = OUT::from(1).addends().memo();
1144 // let mut index = 0;
1145 // loop {
1146 // let comparison = cb_addends.get(index + 1).unwrap().cmp_inner(&self);
1147 // if comparison.is_le() {
1148 // index += 1;
1149 // if comparison.is_eq() {
1150 // return Ok(base_addends.get(index).unwrap().clone().into());
1151 // }
1152 // } else {
1153 // break;
1154 // }
1155 // }
1156 // let mut cube = cb_addends.get(index).unwrap().clone();
1157 // let mut base = base_addends.get(index).unwrap().clone();
1158 // for i in (0..index).rev() {
1159 // let base_addition = base_addends.get(i).unwrap().clone();
1160 // let base_sq = base.clone() * base.clone();
1161 // let base_addition_sq = base_addition.clone() * base_addition.clone();
1162 // let cb_addition = cb_addends.get(i).unwrap().clone();
1163 // let new_cube = cube.clone() + (base_sq * base_addition.clone() * 3.into()) + (base.clone() * base_addition_sq * 3.into()) + cb_addition;
1164 // let comparison = new_cube.cmp_inner(&self);
1165 // if comparison.is_le() {
1166 // base += base_addition;
1167 // if comparison.is_eq() {
1168 // break;
1169 // }
1170 // cube = new_cube;
1171 // }
1172 // }
1173 // Ok(base.into())
1174 // }
1175
1176 // /// Compute the cube root of the big int.
1177 // ///
1178 // /// ### Errors:
1179 // /// * `NegativeRoot` if the number is negative.
1180 // ///
1181 // /// ```
1182 // /// use big_int::prelude::*;
1183 // ///
1184 // /// let a: Loose<10> = 1000.into();
1185 // /// assert_eq!(a.cbrt::<Loose<10>>().unwrap(), 10.into());
1186 // /// ```
1187 // fn cbrt<OUT: BigInt<{ BASE }>>(self) -> Result<OUT, BigIntError> {
1188 // self.cbrt_inner::<OUT>().map(|x| x.unwrap())
1189 // }
1190
1191 /// Compute the nth root of the big int, with root `rhs`.
1192 /// Returns the result as a denormalized number.
1193 ///
1194 /// ### Errors:
1195 /// * `NegativeRoot` if the number is negative.
1196 /// * `SmallRoot` if `rhs` is less than 2.
1197 ///
1198 /// ```
1199 /// use big_int::prelude::*;
1200 ///
1201 /// let a: Loose<10> = 27.into();
1202 /// assert_eq!(a.root::<Loose<10>, Loose<10>>(3.into()).unwrap(), 3.into());
1203 /// ```
1204 fn root_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
1205 self,
1206 rhs: RHS,
1207 ) -> Result<OUT::Denormal, BigIntError> {
1208 if self < Self::zero() {
1209 return Err(BigIntError::NegativeRoot);
1210 }
1211 if self.is_zero() {
1212 return Ok(OUT::Denormal::zero());
1213 }
1214 if rhs <= 1.into() {
1215 return Err(BigIntError::SmallRoot);
1216 }
1217 let result_digits = (self.len() / Into::<usize>::into(rhs.clone())).max(1);
1218 let mut result = OUT::from(1).shl_inner(result_digits);
1219 result.set_digit(0, 0);
1220
1221 'outer: for i in 0..result.len() {
1222 let mut digit_value = 0;
1223 for index in (0..Self::BITS_PER_DIGIT).rev() {
1224 let power = 1 << index;
1225 result.set_digit(i, digit_value + power);
1226 let new_exp: Self = result.clone().exp(rhs.clone()).unwrap();
1227 let comparison = new_exp.cmp_inner(&self);
1228 if comparison.is_le() {
1229 digit_value += power;
1230 if comparison.is_eq() {
1231 break 'outer;
1232 }
1233 }
1234 }
1235 result.set_digit(i, digit_value);
1236 }
1237 Ok(result.into())
1238 }
1239
1240 /// Compute the nth root of the big int, with root `rhs`.
1241 ///
1242 /// ### Errors:
1243 /// * `NegativeRoot` if the number is negative.
1244 /// * `SmallRoot` if `rhs` is less than 2.
1245 ///
1246 /// ```
1247 /// use big_int::prelude::*;
1248 ///
1249 /// let a: Loose<10> = 27.into();
1250 /// assert_eq!(a.root::<Loose<10>, Loose<10>>(3.into()).unwrap(), 3.into());
1251 /// ```
1252 fn root<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
1253 self,
1254 rhs: RHS,
1255 ) -> Result<OUT, BigIntError> {
1256 self.root_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
1257 }
1258
1259 /// Check if the number is even.
1260 ///
1261 /// O(1) for numbers with even bases, and O(log(n)) for numbers
1262 /// with odd bases.
1263 ///
1264 /// ```
1265 /// use big_int::prelude::*;
1266 ///
1267 /// let mut n: Tight<10> = 16.into();
1268 /// assert!(n.is_even());
1269 /// n += 1.into();
1270 /// assert!(!n.is_even());
1271 /// ```
1272 fn is_even(&self) -> bool {
1273 if BASE % 2 == 0 {
1274 self.get_digit(self.len() - 1)
1275 .map(|d| d % 2 == 0)
1276 .unwrap_or(true)
1277 } else {
1278 self.iter().filter(|d| d % 2 == 1).count() % 2 == 0
1279 }
1280 }
1281
1282 /// Iterate over the digits of the int.
1283 ///
1284 /// implements `DoubleEndedIterator`, so digits can be iterated over forward or in reverse.
1285 ///
1286 /// ```
1287 /// use big_int::prelude::*;
1288 ///
1289 /// let a: Tight<10> = 12345.into();
1290 /// assert_eq!(a.iter().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);
1291 /// assert_eq!(a.iter().rev().collect::<Vec<_>>(), vec![5, 4, 3, 2, 1]);
1292 /// ```
1293 fn iter<'a>(&'a self) -> BigIntIter<'a, BASE, Self> {
1294 BigIntIter {
1295 index: 0,
1296 back_index: self.len(),
1297 int: self,
1298 }
1299 }
1300
1301 /// Return a normalized version of the int. A normalized int:
1302 /// * has no trailing zeros
1303 /// * has at least one digit
1304 /// * is not negative zero
1305 ///
1306 /// Additionally, `Tight` ints will be aligned to the beginning of their data segment
1307 /// when normalized.
1308 ///
1309 /// Defined in terms of `normalize`; at least one of `normalize` or `normalized`
1310 /// must be defined by the implementer.
1311 ///
1312 /// ```
1313 /// use big_int::prelude::*;
1314 ///
1315 /// let n = unsafe { Loose::<10>::from_raw_parts(vec![0, 0, 8, 3]) };
1316 /// assert_eq!(n.normalized(), 83.into());
1317 /// ```
1318 fn normalized(mut self) -> Self {
1319 self.normalize();
1320 self
1321 }
1322
1323 /// Normalize a big int in place. A normalized int:
1324 /// * has no trailing zeros
1325 /// * has at least one digit
1326 /// * is not negative zero
1327 ///
1328 /// Additionally, `Tight` ints will be aligned to the beginning of their data segment
1329 /// when normalized.
1330 ///
1331 /// Defined in terms of `normalized`; at least one of `normalize` or `normalized`
1332 /// must be defined by the implementer.
1333 ///
1334 /// ```
1335 /// use big_int::prelude::*;
1336 ///
1337 /// let mut n = unsafe { Loose::<10>::from_raw_parts(vec![0, 0, 8, 3]) };
1338 /// n.normalize();
1339 /// assert_eq!(n, 83.into());
1340 /// ```
1341 fn normalize(&mut self) {
1342 *self = self.clone().normalized();
1343 }
1344
1345 /// Convert a big int to a printable string using the provided alphabet `alphabet`.
1346 /// `Display` uses this method with the default alphabet `STANDARD_ALPHABET`.
1347 ///
1348 /// ### Errors:
1349 /// * `BaseTooHigh` if a digit in the number is too large to be displayed with
1350 /// the chosen character alphabet.
1351 ///
1352 /// ```
1353 /// use big_int::prelude::*;
1354 ///
1355 /// assert_eq!(
1356 /// Loose::<10>::from(6012).display(STANDARD_ALPHABET).unwrap(),
1357 /// "6012".to_string()
1358 /// );
1359 /// ```
1360 fn display(&self, alphabet: &str) -> Result<String, BigIntError> {
1361 let digits = self
1362 .iter()
1363 .map(|digit| {
1364 alphabet
1365 .chars()
1366 .nth(digit as usize)
1367 .ok_or(BigIntError::BaseTooHigh(BASE, alphabet.len()))
1368 })
1369 .collect::<Result<String, _>>()?;
1370 if self.sign() == Negative {
1371 Ok(format!("-{digits}"))
1372 } else {
1373 Ok(digits)
1374 }
1375 }
1376
1377 /// Parse a big int from a `value: &str`, referencing the provided `alphabet`
1378 /// to determine what characters represent which digits. `FromStr` uses this method
1379 /// with the default alphabet `STANDARD_ALPHABET`.
1380 ///
1381 /// ### Errors:
1382 /// * `NotEnoughCharacters` if there are no digit characters in the string.
1383 /// * `UnrecognizedCharacter` if there is a character present which is neither a `-` sign
1384 /// nor a character present in the passed alphabet.
1385 /// * `DigitTooLarge` if a character decodes to a digit value which is larger than the base
1386 /// of the number being parsed can represent.
1387 ///
1388 /// ```
1389 /// use big_int::prelude::*;
1390 ///
1391 /// assert_eq!(Loose::parse("125", STANDARD_ALPHABET), Ok(DenormalLoose::<10>::from(125)));
1392 /// ```
1393 fn parse(value: &str, alphabet: &str) -> Result<Self::Denormal, ParseError> {
1394 let mut builder = Self::Builder::new();
1395 let (sign, chars) = match value.chars().next() {
1396 Some('-') => (Negative, value.chars().skip(1)),
1397 Some(_) => (Positive, value.chars().skip(0)),
1398 None => return Err(ParseError::NotEnoughCharacters),
1399 };
1400 for char in chars {
1401 match alphabet.chars().position(|c| c == char) {
1402 Some(pos) => {
1403 if pos >= BASE {
1404 return Err(ParseError::DigitTooLarge(char, pos, BASE));
1405 } else {
1406 builder.push_back(pos as Digit);
1407 }
1408 }
1409 None => return Err(ParseError::UnrecognizedCharacter(char)),
1410 }
1411 }
1412 if builder.is_empty() {
1413 Err(ParseError::NotEnoughCharacters)
1414 } else {
1415 Ok(builder.with_sign(sign).into())
1416 }
1417 }
1418
1419 /// Convert an int from its own base to another target base,
1420 /// to another `BigInt` type, or both at once. Returns the result as
1421 /// a denormalized number.
1422 ///
1423 /// ```
1424 /// use big_int::prelude::*;
1425 ///
1426 /// let a: DenormalTight<16> = Loose::<10>::from(99825).convert_inner::<16, Tight<16>>();
1427 /// assert_eq!(a, DenormalTight::<16>::from(99825));
1428 /// ```
1429 fn convert_inner<const TO: usize, OUT: BigInt<{ TO }>>(mut self) -> OUT::Denormal {
1430 let to = TO as Digit;
1431 let base = BASE as Digit;
1432 let sign = self.sign();
1433 let mut result = OUT::Builder::new();
1434
1435 // bases are the same; just move the digits from one representation
1436 // into the other
1437 if BASE == TO {
1438 for digit in self {
1439 result.push_back(digit);
1440 }
1441
1442 // current base is a power of the target base; perform a fast conversion
1443 // by converting each individual digit from the current number into
1444 // several contiguous digits of the target number
1445 } else if let Some(power) = is_power(BASE, TO) {
1446 for mut from_digit in self.into_iter().rev() {
1447 for _ in 0..power {
1448 result.push_front(from_digit % to);
1449 if from_digit >= to {
1450 from_digit /= to;
1451 } else {
1452 from_digit = 0;
1453 }
1454 }
1455 }
1456
1457 // target base is a power of the current base; perform a fast conversion
1458 // by creating a single digit of the target number from several contiguous digits
1459 // of the current number
1460 } else if let Some(power) = is_power(TO, BASE) {
1461 let mut iter = self.into_iter().rev();
1462 loop {
1463 let mut to_digit = 0;
1464 let mut done = false;
1465 let mut place = 1;
1466 for _ in 0..power {
1467 if let Some(from_digit) = iter.next() {
1468 to_digit += from_digit * place;
1469 place *= base;
1470 } else {
1471 done = true;
1472 break;
1473 }
1474 }
1475 result.push_front(to_digit);
1476 if done {
1477 break;
1478 }
1479 }
1480
1481 // no special conditions apply; just perform the conversion normally via
1482 // repeated divisons
1483 } else {
1484 self.set_sign(Positive);
1485 let to_base: Self = to.into();
1486 while self >= to_base {
1487 let (quot, rem) = self.div_rem_inner::<_, Self>(to_base.clone()).unwrap();
1488 self = unsafe { quot.unsafe_into() }.normalized();
1489 result.push_front(Into::<Digit>::into(rem));
1490 }
1491 result.push_front(Into::<Digit>::into(self));
1492 }
1493 result.with_sign(sign).into()
1494 }
1495
1496 /// Convert an int from its own base to another target base,
1497 /// to another `BigInt` type, or both at once.
1498 ///
1499 /// ```
1500 /// use big_int::prelude::*;
1501 ///
1502 /// let a: Tight<16> = Loose::<10>::from(99825).convert();
1503 /// assert_eq!(a, Tight::<16>::from(99825));
1504 /// ```
1505 fn convert<const TO: usize, OUT: BigInt<{ TO }>>(self) -> OUT {
1506 self.convert_inner::<TO, OUT>().unwrap()
1507 }
1508
1509 /// Compare the absolute magnitude of two big ints, ignoring their sign.
1510 ///
1511 /// ```
1512 /// use big_int::prelude::*;
1513 ///
1514 /// let a: Tight<10> = (-105).into();
1515 /// let b: Tight<10> = 15.into();
1516 /// assert!(a.cmp_magnitude(&b).is_gt());
1517 /// ```
1518 fn cmp_magnitude<RHS: BigInt<{ BASE }>>(&self, rhs: &RHS) -> Ordering {
1519 for i in (1..=self.len().max(rhs.len())).rev() {
1520 match (self.get_back(i), rhs.get_back(i)) {
1521 (Some(1..), None) => return Ordering::Greater,
1522 (None, Some(1..)) => return Ordering::Less,
1523 (self_digit, rhs_digit) => match self_digit
1524 .unwrap_or_default()
1525 .cmp(&rhs_digit.unwrap_or_default())
1526 {
1527 Ordering::Equal => {}
1528 ordering => return ordering,
1529 },
1530 }
1531 }
1532 Ordering::Equal
1533 }
1534
1535 /// Return the absolute value of the int.
1536 ///
1537 /// ```
1538 /// use big_int::prelude::*;
1539 ///
1540 /// let a: Loose<10> = (-13).into();
1541 /// assert_eq!(a.abs(), 13.into());
1542 /// ```
1543 fn abs(self) -> Self {
1544 self.with_sign(Positive)
1545 }
1546}
1547
1548/// Prepare a set of addends.
1549///
1550/// In an addend set, each element is 2x the element before it.
1551///
1552/// Used internally for efficient multiplication, division,
1553/// exponentiation, and logarithm algorithms.
1554struct AddendSet<const BASE: usize, B: BigInt<{ BASE }>> {
1555 addend: B,
1556}
1557
1558/// Construct an addend set from a big int.
1559trait Addends<const BASE: usize, B: BigInt<{ BASE }>> {
1560 /// Construct an addend set from a big int.
1561 fn addends(self) -> AddendSet<BASE, B>;
1562}
1563
1564impl<const BASE: usize, B: BigInt<{ BASE }>> Addends<BASE, B> for B {
1565 fn addends(self) -> AddendSet<BASE, B> {
1566 AddendSet { addend: self }
1567 }
1568}
1569
1570impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for AddendSet<BASE, B> {
1571 type Item = B;
1572
1573 fn next(&mut self) -> Option<Self::Item> {
1574 let next_addend = self.addend.clone();
1575 self.addend += self.addend.clone();
1576 Some(next_addend)
1577 }
1578}
1579
1580/// Prepare a set of mullands.
1581///
1582/// In a mulland set, each element is the square of the element before it.
1583///
1584/// Used internally for efficient exponentiation & logarithm algorithms.
1585struct MullandSet<const BASE: usize, B: BigInt<{ BASE }>> {
1586 mulland: B,
1587}
1588
1589/// Construct a mulland set from a big int.
1590trait Mullands<const BASE: usize, B: BigInt<{ BASE }>> {
1591 /// Construct a mulland set from a big int.
1592 fn mullands(self) -> MullandSet<BASE, B>;
1593}
1594
1595impl<const BASE: usize, B: BigInt<{ BASE }>> Mullands<BASE, B> for B {
1596 fn mullands(self) -> MullandSet<BASE, B> {
1597 MullandSet { mulland: self }
1598 }
1599}
1600
1601impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for MullandSet<BASE, B> {
1602 type Item = B;
1603
1604 fn next(&mut self) -> Option<Self::Item> {
1605 let next_mulland = self.mulland.clone();
1606 self.mulland *= self.mulland.clone();
1607 Some(next_mulland)
1608 }
1609}
1610
1611/// Prepare a set of n-addends.
1612///
1613/// In an n-addend set, each element is `factor` * the element before it.
1614///
1615/// Used internally for the efficient square root algorithm.
1616struct NAddendSet<const BASE: usize, B: BigInt<{ BASE }>> {
1617 addend: B,
1618 factor: B,
1619}
1620
1621/// Construct an n-adddend set from a big int.
1622trait NAddends<const BASE: usize, B: BigInt<{ BASE }>> {
1623 /// Construct an n-adddend set from a big int.
1624 fn n_addends(self, factor: B) -> NAddendSet<BASE, B>;
1625}
1626
1627impl<const BASE: usize, B: BigInt<{ BASE }>> NAddends<BASE, B> for B {
1628 fn n_addends(self, factor: B) -> NAddendSet<BASE, B> {
1629 NAddendSet {
1630 addend: self,
1631 factor,
1632 }
1633 }
1634}
1635
1636impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for NAddendSet<BASE, B> {
1637 type Item = B;
1638
1639 fn next(&mut self) -> Option<Self::Item> {
1640 let next_mulland = self.addend.clone();
1641 self.addend *= self.factor.clone();
1642 Some(next_mulland)
1643 }
1644}
1645
1646/// A memoized iterator. Remembers elements that were yielded by the
1647/// underlying iterator, and allows fetching of them after the fact.
1648struct IterMemo<I: Iterator> {
1649 memo: Vec<I::Item>,
1650 iter: I,
1651 exhausted: bool,
1652}
1653
1654impl<I: Iterator> IterMemo<I> {
1655 /// Fetch a memoized item from the iterator, pulling new items from it
1656 /// as needed.
1657 fn get(&mut self, index: usize) -> Option<&I::Item> {
1658 while self.memo.len() <= index && !self.exhausted {
1659 self.store_next();
1660 }
1661 self.memo.get(index)
1662 }
1663
1664 /// Fetch a mutable reference to a memoized item from the iterator,
1665 /// pulling new items from it as needed.
1666 fn get_mut(&mut self, index: usize) -> Option<&mut I::Item> {
1667 while self.memo.len() <= index && !self.exhausted {
1668 self.store_next();
1669 }
1670 self.memo.get_mut(index)
1671 }
1672
1673 /// Store the next element from the iterator in the memo, growing
1674 /// it by one.
1675 fn store_next(&mut self) {
1676 if let Some(item) = self.iter.next() {
1677 self.memo.push(item);
1678 } else {
1679 self.exhausted = true;
1680 }
1681 }
1682}
1683
1684impl<I: Iterator> From<I> for IterMemo<I> {
1685 fn from(value: I) -> Self {
1686 IterMemo {
1687 memo: Vec::new(),
1688 iter: value,
1689 exhausted: false,
1690 }
1691 }
1692}
1693
1694/// Transitive trait to allow one to call `.memo()` on iterators
1695/// to make a memoizer from them
1696trait ToMemo: Iterator + Sized {
1697 /// Translate an iterator into a memoized iterator.
1698 fn memo(self) -> IterMemo<Self> {
1699 self.into()
1700 }
1701}
1702
1703impl<I: Iterator> ToMemo for I {}
1704
1705/// A builder for a big int. Use this to construct a big int one digit at a time,
1706/// then call .into() to construct the final int.
1707///
1708/// You're most likely better off using one of the `From` implementations
1709/// as opposed to directly building your int via a builder.
1710///
1711/// ```
1712/// use big_int::prelude::*;
1713///
1714/// let mut a = TightBuilder::<10>::new();
1715/// a.push_back(5);
1716/// a.push_back(3);
1717/// a.push_back(0);
1718/// a.push_back(4);
1719/// let a: Tight<10> = a.into();
1720/// assert_eq!(a, 5304.into());
1721/// ```
1722pub trait BigIntBuilder<const BASE: usize>
1723where
1724 Self: std::fmt::Debug,
1725{
1726 /// Create a new builder.
1727 ///
1728 /// ```
1729 /// use big_int::prelude::*;
1730 ///
1731 /// let mut a = TightBuilder::<10>::new();
1732 /// unsafe {
1733 /// a.push_back(5);
1734 /// }
1735 /// let a: Tight<10> = a.into();
1736 /// assert_eq!(a, 5.into());
1737 /// ```
1738 fn new() -> Self;
1739
1740 /// Push a new digit to the end of the int.
1741 ///
1742 /// ```
1743 /// use big_int::prelude::*;
1744 ///
1745 /// let mut a = TightBuilder::<10>::new();
1746 /// a.push_back(5);
1747 /// a.push_back(6);
1748 /// let a: Tight<10> = a.into();
1749 /// assert_eq!(a, 56.into());
1750 /// ```
1751 fn push_front(&mut self, digit: Digit);
1752
1753 /// Push a new digit to the beginning of the int.
1754 ///
1755 /// ```
1756 /// use big_int::prelude::*;
1757 ///
1758 /// let mut a = TightBuilder::<10>::new();
1759 /// a.push_front(5);
1760 /// a.push_front(6);
1761 /// let a: Tight<10> = a.into();
1762 /// assert_eq!(a, 65.into());
1763 /// ```
1764 fn push_back(&mut self, digit: Digit);
1765
1766 /// Check if the builder is empty.
1767 ///
1768 /// ```
1769 /// use big_int::prelude::*;
1770 ///
1771 /// let mut a = TightBuilder::<10>::new();
1772 /// assert!(a.is_empty());
1773 /// a.push_front(5);
1774 /// assert!(!a.is_empty());
1775 /// ```
1776 fn is_empty(&self) -> bool;
1777
1778 /// The builder with the given sign.
1779 ///
1780 /// ```
1781 /// use big_int::prelude::*;
1782 ///
1783 /// let mut a = TightBuilder::<10>::new();
1784 /// a.push_back(9);
1785 /// let a: Tight<10> = a.with_sign(Negative).into();
1786 /// assert_eq!(a, (-9).into());
1787 /// ```
1788 fn with_sign(self, sign: Sign) -> Self;
1789}
1790
1791/// A conversion that may only be performed unsafely.
1792///
1793/// ```
1794/// use big_int::prelude::*;
1795///
1796/// let a: Tight<10> = unsafe { Tight::<10>::from_u128_inner(532).unsafe_into() };
1797/// assert_eq!(a, 532.into());
1798/// ```
1799pub trait UnsafeInto<T> {
1800 unsafe fn unsafe_into(self) -> T;
1801}
1802
1803impl<T> UnsafeInto<T> for T {
1804 unsafe fn unsafe_into(self) -> T {
1805 self
1806 }
1807}
1808
1809/// A value that may be unwrapped.
1810///
1811/// ```
1812/// use big_int::prelude::*;
1813///
1814/// let a: Tight<10> = 120.into();
1815/// let b: Tight<10> = 5.into();
1816/// let b: DenormalTight<10> = a.div_inner::<_, Tight<10>>(b);
1817/// let c: Tight<10> = b.unwrap();
1818/// assert_eq!(c, 24.into());
1819/// ```
1820pub trait Unwrap<T> {
1821 fn unwrap(self) -> T;
1822}
1823
1824/// Represents the sign of a big int; either Positive or Negative.
1825///
1826/// ```
1827/// use big_int::prelude::*;
1828///
1829/// let mut a: Tight<10> = 18.into();
1830/// let s = a.sign();
1831/// assert_eq!(s, Positive);
1832/// a *= (-1).into();
1833/// let s = a.sign();
1834/// assert_eq!(s, Negative);
1835/// ```
1836#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1837pub enum Sign {
1838 Positive,
1839 Negative,
1840}
1841
1842impl Neg for Sign {
1843 type Output = Sign;
1844
1845 fn neg(self) -> Self::Output {
1846 match self {
1847 Positive => Negative,
1848 Negative => Positive,
1849 }
1850 }
1851}
1852
1853impl Mul for Sign {
1854 type Output = Sign;
1855
1856 fn mul(self, rhs: Self) -> Self::Output {
1857 if self == rhs {
1858 Positive
1859 } else {
1860 Negative
1861 }
1862 }
1863}
1864
1865/// A consuming iterator over the digits of a big int.
1866///
1867/// ```
1868/// use big_int::prelude::*;
1869/// use std::iter::Rev;
1870///
1871/// let a: Loose<10> = 12345.into();
1872/// let it = a.into_iter();
1873/// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);
1874/// ```
1875pub struct BigIntIntoIter<const BASE: usize, B: BigInt<{ BASE }>>(B);
1876
1877impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for BigIntIntoIter<BASE, B> {
1878 type Item = Digit;
1879
1880 fn next(&mut self) -> Option<Self::Item> {
1881 unsafe { self.0.pop_front() }
1882 }
1883}
1884
1885impl<const BASE: usize, B: BigInt<{ BASE }>> DoubleEndedIterator for BigIntIntoIter<BASE, B> {
1886 fn next_back(&mut self) -> Option<Self::Item> {
1887 unsafe { self.0.pop_back() }
1888 }
1889}
1890
1891/// An iterator over the digits of a big int.
1892///
1893/// ```
1894/// use big_int::prelude::*;
1895/// use std::iter::Rev;
1896///
1897/// let a: Loose<10> = 12345.into();
1898/// let it = a.iter();
1899/// let rev_it = a.iter().rev();
1900/// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);
1901/// assert_eq!(rev_it.collect::<Vec<_>>(), vec![5, 4, 3, 2, 1]);
1902/// ```
1903pub struct BigIntIter<'a, const BASE: usize, B: BigInt<{ BASE }>> {
1904 index: usize,
1905 back_index: usize,
1906 int: &'a B,
1907}
1908
1909impl<'a, const BASE: usize, B: BigInt<{ BASE }>> Iterator for BigIntIter<'_, BASE, B> {
1910 type Item = Digit;
1911
1912 fn next(&mut self) -> Option<Self::Item> {
1913 (self.index < self.back_index)
1914 .then_some(&mut self.index)
1915 .and_then(|index| {
1916 *index += 1;
1917 self.int.get_digit(*index - 1)
1918 })
1919 }
1920}
1921
1922impl<'a, const BASE: usize, B: BigInt<{ BASE }>> DoubleEndedIterator for BigIntIter<'_, BASE, B> {
1923 fn next_back(&mut self) -> Option<Self::Item> {
1924 (self.back_index > self.index)
1925 .then_some(&mut self.back_index)
1926 .and_then(|index| {
1927 *index -= 1;
1928 self.int.get_digit(*index)
1929 })
1930 }
1931}
1932
1933/// Check if a number is a power of another number.
1934///
1935/// If `x` is a power of `y`, return `Some(n)` such that
1936/// `x == y^n`. If not, return `None`.
1937pub(crate) fn is_power(mut x: usize, y: usize) -> Option<usize> {
1938 if x == 1 {
1939 Some(0)
1940 } else {
1941 let mut power = 1;
1942 loop {
1943 if x % y != 0 {
1944 return None;
1945 }
1946 match x.cmp(&y) {
1947 Ordering::Equal => return Some(power),
1948 Ordering::Less => return None,
1949 Ordering::Greater => {
1950 power += 1;
1951 x /= y;
1952 }
1953 }
1954 }
1955 }
1956}
1957
1958/// Calculate the minimum number of bits required to store a digit in a given base.
1959pub(crate) const fn bits_per_digit(base: usize) -> usize {
1960 let mut bits = 1;
1961 let mut max_base_of_bits = 2;
1962 while max_base_of_bits < base {
1963 bits += 1;
1964 max_base_of_bits <<= 1;
1965 }
1966 bits
1967}