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;
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 integer a decoded literal spells: ASCII decimal digits with
25    /// an optional leading `-`.
26    ///
27    /// This reads what `flow-ir` writes for an integer literal and nothing
28    /// else, so `+`, separators, whitespace and other radixes are refused.
29    pub fn parse(digits: &str) -> Option<Self> {
30        let magnitude = digits.strip_prefix('-').unwrap_or(digits);
31        if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
32            return None;
33        }
34        BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
35    }
36
37    /// Returns `self + other`.
38    #[must_use]
39    pub fn add(&self, other: &Int) -> Int {
40        Int(&self.0 + &other.0)
41    }
42
43    /// Returns `self - other`.
44    #[must_use]
45    pub fn sub(&self, other: &Int) -> Int {
46        Int(&self.0 - &other.0)
47    }
48
49    /// Returns `self * other`.
50    #[must_use]
51    pub fn mul(&self, other: &Int) -> Int {
52        Int(&self.0 * &other.0)
53    }
54
55    /// Returns `-self`.
56    #[must_use]
57    pub fn neg(&self) -> Int {
58        Int(-&self.0)
59    }
60
61    /// Returns `self.div(divisor)`: the quotient rounded toward negative
62    /// infinity.
63    pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
64        if divisor.0.is_zero() {
65            return Err(Fault::DivisionByZero);
66        }
67        Ok(Int(self.0.div_floor(&divisor.0)))
68    }
69
70    /// Returns `self % divisor`: the remainder matching [`Int::div`], zero or
71    /// carrying the divisor's sign.
72    pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
73        if divisor.0.is_zero() {
74            return Err(Fault::DivisionByZero);
75        }
76        Ok(Int(self.0.mod_floor(&divisor.0)))
77    }
78
79    /// Returns whether this is zero.
80    pub fn is_zero(&self) -> bool {
81        self.0.is_zero()
82    }
83
84    /// Returns whether this is below zero.
85    pub fn is_negative(&self) -> bool {
86        self.0.is_negative()
87    }
88
89    /// Returns how many bits the magnitude takes, the sign excluded: `0` for
90    /// zero, `1` for `1` and `-1`, and `4096` for `2^4096 - 1`.
91    pub fn bits(&self) -> u64 {
92        self.0.bits()
93    }
94
95    /// Returns this as a zero-based position, or `None` for a negative one or
96    /// one no in-memory sequence could reach.
97    pub fn to_index(&self) -> Option<usize> {
98        self.0.to_usize()
99    }
100
101    /// Returns a count — a length or a position — as an integer.
102    pub fn from_count(count: usize) -> Int {
103        Int(BigInt::from(count))
104    }
105
106    /// Returns the number, for an encoder that writes it.
107    pub fn as_bigint(&self) -> &BigInt {
108        &self.0
109    }
110
111    pub(crate) fn into_bigint(self) -> BigInt {
112        self.0
113    }
114}
115
116impl From<BigInt> for Int {
117    fn from(value: BigInt) -> Self {
118        Int(value)
119    }
120}
121
122impl From<i64> for Int {
123    fn from(value: i64) -> Self {
124        Int(BigInt::from(value))
125    }
126}
127
128/// The text form: decimal digits, `-` before a negative number, no leading
129/// zero (`data.md`, *Int*).
130impl fmt::Display for Int {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        fmt::Display::fmt(&self.0, f)
133    }
134}
135
136impl fmt::Debug for Int {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        fmt::Display::fmt(&self.0, f)
139    }
140}