flow-lang-value 0.1.0

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
//! `Int`: every whole number (`data.md`, *Int*).

use std::fmt;

use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{Signed, ToPrimitive, Zero};

use crate::error::Fault;

/// An integer, with no bound.
///
/// Addition, subtraction, multiplication and negation are exact and never
/// fault. Integer division rounds toward negative infinity and `%` is the
/// matching remainder, so for every nonzero `b`,
/// `a == a.div(b) * b + a.rem(b)` with the remainder zero or carrying `b`'s
/// sign. A zero divisor is the one fault.
///
/// The derived order is the order of the numbers, which is `data.md`'s.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Int(BigInt);

impl Int {
    /// Returns the integer a decoded literal spells: ASCII decimal digits with
    /// an optional leading `-`.
    ///
    /// This reads what `flow-ir` writes for an integer literal and nothing
    /// else, so `+`, separators, whitespace and other radixes are refused.
    pub fn parse(digits: &str) -> Option<Self> {
        let magnitude = digits.strip_prefix('-').unwrap_or(digits);
        if magnitude.is_empty() || !magnitude.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }
        BigInt::parse_bytes(digits.as_bytes(), 10).map(Int)
    }

    /// Returns `self + other`.
    #[must_use]
    pub fn add(&self, other: &Int) -> Int {
        Int(&self.0 + &other.0)
    }

    /// Returns `self - other`.
    #[must_use]
    pub fn sub(&self, other: &Int) -> Int {
        Int(&self.0 - &other.0)
    }

    /// Returns `self * other`.
    #[must_use]
    pub fn mul(&self, other: &Int) -> Int {
        Int(&self.0 * &other.0)
    }

    /// Returns `-self`.
    #[must_use]
    pub fn neg(&self) -> Int {
        Int(-&self.0)
    }

    /// Returns `self.div(divisor)`: the quotient rounded toward negative
    /// infinity.
    pub fn div(&self, divisor: &Int) -> Result<Int, Fault> {
        if divisor.0.is_zero() {
            return Err(Fault::DivisionByZero);
        }
        Ok(Int(self.0.div_floor(&divisor.0)))
    }

    /// Returns `self % divisor`: the remainder matching [`Int::div`], zero or
    /// carrying the divisor's sign.
    pub fn rem(&self, divisor: &Int) -> Result<Int, Fault> {
        if divisor.0.is_zero() {
            return Err(Fault::DivisionByZero);
        }
        Ok(Int(self.0.mod_floor(&divisor.0)))
    }

    /// Returns whether this is zero.
    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }

    /// Returns whether this is below zero.
    pub fn is_negative(&self) -> bool {
        self.0.is_negative()
    }

    /// Returns how many bits the magnitude takes, the sign excluded: `0` for
    /// zero, `1` for `1` and `-1`, and `4096` for `2^4096 - 1`.
    pub fn bits(&self) -> u64 {
        self.0.bits()
    }

    /// Returns this as a zero-based position, or `None` for a negative one or
    /// one no in-memory sequence could reach.
    pub fn to_index(&self) -> Option<usize> {
        self.0.to_usize()
    }

    /// Returns a count — a length or a position — as an integer.
    pub fn from_count(count: usize) -> Int {
        Int(BigInt::from(count))
    }

    /// Returns the number, for an encoder that writes it.
    pub fn as_bigint(&self) -> &BigInt {
        &self.0
    }

    pub(crate) fn into_bigint(self) -> BigInt {
        self.0
    }
}

impl From<BigInt> for Int {
    fn from(value: BigInt) -> Self {
        Int(value)
    }
}

impl From<i64> for Int {
    fn from(value: i64) -> Self {
        Int(BigInt::from(value))
    }
}

/// The text form: decimal digits, `-` before a negative number, no leading
/// zero (`data.md`, *Int*).
impl fmt::Display for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl fmt::Debug for Int {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}