Skip to main content

flow_value/
int.rs

1//! `Int`: every whole number (`data.md`, *Int*).
2
3use std::fmt;
4
5use num_bigint::{BigInt, Sign};
6use num_integer::Integer;
7use num_traits::{Signed, ToPrimitive, Zero};
8
9use crate::error::Fault;
10
11/// An integer, with no bound.
12///
13/// Addition, subtraction, multiplication and negation are exact and never
14/// fault. Integer division rounds toward negative infinity and `%` is the
15/// matching remainder, so for every nonzero `b`,
16/// `a == a.div(b) * b + a.rem(b)` with the remainder zero or carrying `b`'s
17/// sign. A zero divisor is the one fault.
18///
19/// The derived order is the order of the numbers, which is `data.md`'s.
20#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
21pub struct Int(BigInt);
22
23impl Int {
24    /// Returns the nonnegative integer whose magnitude is `limbs`,
25    /// little-endian base 2^32: what a decoded literal holds, read in
26    /// O(limbs).
27    #[must_use]
28    pub fn from_limbs(limbs: &[u32]) -> Self {
29        Int(BigInt::from_slice(Sign::Plus, limbs))
30    }
31
32    /// Returns the integer ASCII decimal digits with an optional leading `-`
33    /// spell. `+`, separators, whitespace and other radixes are refused.
34    pub fn parse(digits: &str) -> Option<Self> {
35        let magnitude = digits.strip_prefix('-').unwrap_or(digits);
36        if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
37            return None;
38        }
39        BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
40    }
41
42    /// Returns `self + other`.
43    #[must_use]
44    pub fn add(&self, other: &Int) -> Int {
45        Int(&self.0 + &other.0)
46    }
47
48    /// Returns `self - other`.
49    #[must_use]
50    pub fn sub(&self, other: &Int) -> Int {
51        Int(&self.0 - &other.0)
52    }
53
54    /// Returns `self * other`.
55    #[must_use]
56    pub fn mul(&self, other: &Int) -> Int {
57        Int(&self.0 * &other.0)
58    }
59
60    /// Returns `-self`.
61    #[must_use]
62    pub fn neg(&self) -> Int {
63        Int(-&self.0)
64    }
65
66    /// Returns `self.div(divisor)`: the quotient rounded toward negative
67    /// infinity.
68    ///
69    /// # Errors
70    ///
71    /// [`Fault::DivisionByZero`] for a zero divisor.
72    pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
73        if divisor.0.is_zero() {
74            return Err(Fault::DivisionByZero);
75        }
76        Ok(Int(self.0.div_floor(&divisor.0)))
77    }
78
79    /// Returns `self % divisor`: the remainder matching [`Int::div`], zero or
80    /// carrying the divisor's sign.
81    ///
82    /// # Errors
83    ///
84    /// [`Fault::DivisionByZero`] for a zero divisor.
85    pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
86        if divisor.0.is_zero() {
87            return Err(Fault::DivisionByZero);
88        }
89        Ok(Int(self.0.mod_floor(&divisor.0)))
90    }
91
92    /// Returns whether this is zero.
93    pub fn is_zero(&self) -> bool {
94        self.0.is_zero()
95    }
96
97    /// Returns whether this is below zero.
98    pub fn is_negative(&self) -> bool {
99        self.0.is_negative()
100    }
101
102    /// Returns how many bits the magnitude takes, the sign excluded: `0` for
103    /// zero, `1` for `1` and `-1`, and `4096` for `2^4096 - 1`.
104    pub fn bits(&self) -> u64 {
105        self.0.bits()
106    }
107
108    /// Returns this as a zero-based position, or `None` for a negative one or
109    /// one no in-memory sequence could reach.
110    pub fn to_index(&self) -> Option<usize> {
111        self.0.to_usize()
112    }
113
114    /// Returns a count — a length or a position — as an integer.
115    pub fn from_count(count: usize) -> Int {
116        Int(BigInt::from(count))
117    }
118
119    /// Returns an unsigned 64-bit number as an integer.
120    pub fn from_u64(value: u64) -> Int {
121        Int(BigInt::from(value))
122    }
123
124    /// Returns the number, for an encoder that writes it.
125    pub fn as_bigint(&self) -> &BigInt {
126        &self.0
127    }
128
129    pub(crate) fn into_bigint(self) -> BigInt {
130        self.0
131    }
132}
133
134impl From<BigInt> for Int {
135    fn from(value: BigInt) -> Self {
136        Int(value)
137    }
138}
139
140impl From<i64> for Int {
141    fn from(value: i64) -> Self {
142        Int(BigInt::from(value))
143    }
144}
145
146/// The text form: decimal digits, `-` before a negative number, no leading
147/// zero (`data.md`, *Int*).
148impl fmt::Display for Int {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        fmt::Display::fmt(&self.0, f)
151    }
152}
153
154impl fmt::Debug for Int {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        fmt::Display::fmt(&self.0, f)
157    }
158}