inlean-runtime 0.1.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Arithmetic on natural numbers of any size.
//!
//! A number is a slice of 64-bit limbs, least significant first, without leading zero
//! limbs; zero is the empty slice. The algorithms are the schoolbook ones: simple, and fast
//! enough for numbers of a few hundred digits.

use std::cmp::Ordering;

fn trim(mut limbs: Vec<u64>) -> Vec<u64> {
    while limbs.last() == Some(&0) {
        limbs.pop();
    }
    limbs
}

pub fn compare(a: &[u64], b: &[u64]) -> Ordering {
    a.len().cmp(&b.len()).then_with(|| a.iter().rev().cmp(b.iter().rev()))
}

pub fn add(a: &[u64], b: &[u64]) -> Vec<u64> {
    let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
    let mut out = Vec::with_capacity(long.len() + 1);
    let mut carry = false;
    for (i, &x) in long.iter().enumerate() {
        let (sum, c1) = x.overflowing_add(short.get(i).copied().unwrap_or(0));
        let (sum, c2) = sum.overflowing_add(carry as u64);
        carry = c1 || c2;
        out.push(sum);
    }
    if carry {
        out.push(1);
    }
    out
}

/// `a - b`, for `a >= b`.
pub fn sub(a: &[u64], b: &[u64]) -> Vec<u64> {
    let mut out = Vec::with_capacity(a.len());
    let mut borrow = false;
    for (i, &x) in a.iter().enumerate() {
        let (diff, b1) = x.overflowing_sub(b.get(i).copied().unwrap_or(0));
        let (diff, b2) = diff.overflowing_sub(borrow as u64);
        borrow = b1 || b2;
        out.push(diff);
    }
    trim(out)
}

pub fn mul(a: &[u64], b: &[u64]) -> Vec<u64> {
    if a.is_empty() || b.is_empty() {
        return Vec::new();
    }
    let mut out = vec![0u64; a.len() + b.len()];
    for (i, &x) in a.iter().enumerate() {
        let mut carry = 0u128;
        for (j, &y) in b.iter().enumerate() {
            let t = x as u128 * y as u128 + out[i + j] as u128 + carry;
            out[i + j] = t as u64;
            carry = t >> 64;
        }
        out[i + b.len()] = carry as u64;
    }
    trim(out)
}

/// Quotient and remainder by one nonzero limb.
pub fn divrem_small(a: &[u64], b: u64) -> (Vec<u64>, u64) {
    let mut quotient = vec![0u64; a.len()];
    let mut remainder = 0u128;
    for i in (0..a.len()).rev() {
        let current = (remainder << 64) | a[i] as u128;
        quotient[i] = (current / b as u128) as u64;
        remainder = current % b as u128;
    }
    (trim(quotient), remainder as u64)
}

/// Quotient and remainder, for nonzero `b`. Knuth's algorithm D.
pub fn divrem(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
    if compare(a, b) == Ordering::Less {
        return (Vec::new(), a.to_vec());
    }
    if let [single] = b {
        let (quotient, remainder) = divrem_small(a, *single);
        return (quotient, if remainder == 0 { Vec::new() } else { vec![remainder] });
    }
    // Normalize so that the divisor's top bit is set; the quotient is unchanged.
    let shift = b[b.len() - 1].leading_zeros() as usize;
    let b = shl(b, shift);
    let mut a = shl(a, shift);
    a.resize(a.len().max(b.len()) + 1, 0);
    let n = b.len();
    let m = a.len() - n - 1;
    let mut quotient = vec![0u64; m + 1];
    for j in (0..=m).rev() {
        // Estimate the quotient digit from the top two limbs, then correct it.
        let top = ((a[j + n] as u128) << 64) | a[j + n - 1] as u128;
        let mut digit = top / b[n - 1] as u128;
        let mut rest = top % b[n - 1] as u128;
        while digit >> 64 != 0 || digit * b[n - 2] as u128 > ((rest << 64) | a[j + n - 2] as u128) {
            digit -= 1;
            rest += b[n - 1] as u128;
            if rest >> 64 != 0 {
                break;
            }
        }
        // a[j..=j+n] -= digit * b
        let mut carry = 0u128;
        let mut borrow = false;
        for i in 0..n {
            let product = digit * b[i] as u128 + carry;
            carry = product >> 64;
            let (diff, b1) = a[i + j].overflowing_sub(product as u64);
            let (diff, b2) = diff.overflowing_sub(borrow as u64);
            a[i + j] = diff;
            borrow = b1 || b2;
        }
        let (diff, b1) = a[j + n].overflowing_sub(carry as u64);
        let (diff, b2) = diff.overflowing_sub(borrow as u64);
        a[j + n] = diff;
        if b1 || b2 {
            // The estimate was one too large: add the divisor back.
            digit -= 1;
            let mut carry = false;
            for i in 0..n {
                let (sum, c1) = a[i + j].overflowing_add(b[i]);
                let (sum, c2) = sum.overflowing_add(carry as u64);
                a[i + j] = sum;
                carry = c1 || c2;
            }
            a[j + n] = a[j + n].wrapping_add(carry as u64);
        }
        quotient[j] = digit as u64;
    }
    a.truncate(n);
    (trim(quotient), shr(&a, shift))
}

pub fn shl(a: &[u64], bits: usize) -> Vec<u64> {
    if a.is_empty() {
        return Vec::new();
    }
    let (limbs, bits) = (bits / 64, bits % 64);
    let mut out = vec![0u64; limbs];
    if bits == 0 {
        out.extend_from_slice(a);
    } else {
        let mut carry = 0u64;
        for &x in a {
            out.push((x << bits) | carry);
            carry = x >> (64 - bits);
        }
        out.push(carry);
    }
    trim(out)
}

pub fn shr(a: &[u64], bits: usize) -> Vec<u64> {
    let (limbs, bits) = (bits / 64, bits % 64);
    if limbs >= a.len() {
        return Vec::new();
    }
    let a = &a[limbs..];
    if bits == 0 {
        return trim(a.to_vec());
    }
    let mut out = Vec::with_capacity(a.len());
    for (i, &x) in a.iter().enumerate() {
        let high = a.get(i + 1).copied().unwrap_or(0);
        out.push((x >> bits) | (high << (64 - bits)));
    }
    trim(out)
}

pub fn bitwise(a: &[u64], b: &[u64], op: fn(u64, u64) -> u64) -> Vec<u64> {
    let len = a.len().max(b.len());
    trim((0..len).map(|i| op(a.get(i).copied().unwrap_or(0), b.get(i).copied().unwrap_or(0))).collect())
}

/// The number of bits in the binary representation; zero for zero.
pub fn bit_length(a: &[u64]) -> usize {
    match a.last() {
        Some(top) => a.len() * 64 - top.leading_zeros() as usize,
        None => 0,
    }
}

pub fn pow(base: &[u64], mut exponent: usize) -> Vec<u64> {
    let mut result = vec![1u64];
    let mut square = base.to_vec();
    while exponent != 0 {
        if exponent & 1 == 1 {
            result = mul(&result, &square);
        }
        exponent >>= 1;
        if exponent != 0 {
            square = mul(&square, &square);
        }
    }
    result
}

pub fn gcd(a: &[u64], b: &[u64]) -> Vec<u64> {
    let (mut a, mut b) = (a.to_vec(), b.to_vec());
    while !b.is_empty() {
        let (_, remainder) = divrem(&a, &b);
        a = b;
        b = remainder;
    }
    a
}

/// 10^19, the largest power of ten in one limb.
const CHUNK: u64 = 10_000_000_000_000_000_000;
const CHUNK_DIGITS: usize = 19;

pub fn to_decimal(a: &[u64]) -> String {
    if a.is_empty() {
        return "0".to_owned();
    }
    let mut chunks = Vec::new();
    let mut rest = a.to_vec();
    while !rest.is_empty() {
        let (quotient, remainder) = divrem_small(&rest, CHUNK);
        chunks.push(remainder);
        rest = quotient;
    }
    let mut out = chunks.pop().unwrap_or(0).to_string();
    for chunk in chunks.iter().rev() {
        out.push_str(&format!("{chunk:019}"));
    }
    out
}

/// Parses a nonempty string of decimal digits.
pub fn from_decimal(digits: &str) -> Option<Vec<u64>> {
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let mut out: Vec<u64> = Vec::new();
    let bytes = digits.as_bytes();
    let mut start = 0;
    while start < bytes.len() {
        // The first chunk takes the odd digits so that every later chunk is full.
        let len = match (bytes.len() - start) % CHUNK_DIGITS {
            0 => CHUNK_DIGITS,
            partial => partial,
        };
        let chunk: u64 = digits[start..start + len].parse().ok()?;
        out = add(&mul(&out, &[10u64.pow(len as u32)]), &[chunk]);
        start += len;
    }
    Some(trim(out))
}