use crate::bignum;
use crate::object::{box_, dec, is_scalar, new_header, unbox, Header, Obj, TAG_MPZ};
use std::cmp::Ordering;
pub const MAX_SMALL: usize = usize::MAX >> 1;
#[repr(C)]
struct Big {
header: Header,
negative: bool,
limbs: Vec<u64>,
}
pub(crate) fn alloc_big(limbs: Vec<u64>, negative: bool) -> Obj {
crate::object::count_object(1);
let big = Box::new(Big { header: new_header(TAG_MPZ, 0, 0), negative, limbs });
Obj::from_header(Box::into_raw(big).cast())
}
pub(crate) unsafe fn big_parts<'a>(o: Obj) -> (bool, &'a [u64]) {
let big = &*o.header().cast::<Big>();
(big.negative, &big.limbs)
}
pub(crate) unsafe fn free_big(o: Obj) {
crate::object::count_object(-1);
drop(Box::from_raw(o.header().cast::<Big>()));
}
unsafe fn limbs<'a>(o: Obj, small: &'a mut [u64; 1]) -> &'a [u64] {
if is_scalar(o) {
small[0] = unbox(o) as u64;
if small[0] == 0 {
&[]
} else {
small
}
} else {
&(*o.header().cast::<Big>()).limbs
}
}
fn from_limbs(mut limbs: Vec<u64>) -> Obj {
while limbs.last() == Some(&0) {
limbs.pop();
}
match limbs.as_slice() {
[] => box_(0),
[single] if *single <= MAX_SMALL as u64 => box_(*single as usize),
_ => alloc_big(limbs, false),
}
}
fn from_u64(value: u64) -> Obj {
from_limbs(if value == 0 { Vec::new() } else { vec![value] })
}
fn from_u128(value: u128) -> Obj {
let mut limbs = vec![value as u64, (value >> 64) as u64];
while limbs.last() == Some(&0) {
limbs.pop();
}
from_limbs(limbs)
}
unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> Vec<u64>) -> Obj {
let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
from_limbs(op(limbs(a, &mut sa), limbs(b, &mut sb)))
}
unsafe fn compare(a: Obj, b: Obj) -> Ordering {
if is_scalar(a) && is_scalar(b) {
return unbox(a).cmp(&unbox(b));
}
let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
bignum::compare(limbs(a, &mut sa), limbs(b, &mut sb))
}
unsafe fn small(o: Obj) -> Option<usize> {
is_scalar(o).then(|| unbox(o))
}
pub fn usize_to_nat(n: usize) -> Obj {
from_u64(n as u64)
}
pub fn unsigned_to_nat(n: u32) -> Obj {
from_u64(n as u64)
}
pub fn uint64_to_nat(n: u64) -> Obj {
from_u64(n)
}
pub fn uint8_to_nat(n: u8) -> Obj {
box_(n as usize)
}
pub fn uint16_to_nat(n: u16) -> Obj {
box_(n as usize)
}
pub fn uint32_to_nat(n: u32) -> Obj {
from_u64(n as u64)
}
pub fn cstr_to_nat(digits: &str) -> Obj {
from_limbs(bignum::from_decimal(digits).expect("inlean: malformed Nat literal"))
}
unsafe fn low_bits(o: Obj) -> u64 {
let mut scratch = [0u64; 1];
limbs(o, &mut scratch).first().copied().unwrap_or(0)
}
macro_rules! of_nat {
($($name:ident $mk:ident $ty:ty),*) => {$(
pub unsafe fn $name(a: Obj) -> $ty {
low_bits(a) as $ty
}
pub unsafe fn $mk(a: Obj) -> $ty {
let result = low_bits(a) as $ty;
dec(a);
result
}
)*};
}
of_nat!(
uint8_of_nat uint8_of_nat_mk u8,
uint16_of_nat uint16_of_nat_mk u16,
uint32_of_nat uint32_of_nat_mk u32,
uint64_of_nat uint64_of_nat_mk u64,
usize_of_nat usize_of_nat_mk usize
);
pub unsafe fn int8_of_nat(a: Obj) -> u8 {
low_bits(a) as u8
}
pub unsafe fn int16_of_nat(a: Obj) -> u16 {
low_bits(a) as u16
}
pub unsafe fn int32_of_nat(a: Obj) -> u32 {
low_bits(a) as u32
}
pub unsafe fn int64_of_nat(a: Obj) -> u64 {
low_bits(a)
}
pub unsafe fn isize_of_nat(a: Obj) -> usize {
low_bits(a) as usize
}
pub unsafe fn nat_succ(a: Obj) -> Obj {
nat_add(a, box_(1))
}
pub unsafe fn nat_add(a: Obj, b: Obj) -> Obj {
if is_scalar(a) && is_scalar(b) {
return from_u64(unbox(a) as u64 + unbox(b) as u64);
}
binary(a, b, bignum::add)
}
pub unsafe fn nat_sub(a: Obj, b: Obj) -> Obj {
if is_scalar(a) && is_scalar(b) {
return box_(unbox(a).saturating_sub(unbox(b)));
}
if compare(a, b) == Ordering::Less {
return box_(0);
}
binary(a, b, bignum::sub)
}
pub unsafe fn nat_pred(a: Obj) -> Obj {
nat_sub(a, box_(1))
}
pub unsafe fn nat_mul(a: Obj, b: Obj) -> Obj {
if is_scalar(a) && is_scalar(b) {
return from_u128(unbox(a) as u128 * unbox(b) as u128);
}
binary(a, b, bignum::mul)
}
pub unsafe fn nat_div(a: Obj, b: Obj) -> Obj {
if is_scalar(a) && is_scalar(b) {
return box_(unbox(a).checked_div(unbox(b)).unwrap_or(0));
}
if b == box_(0) {
return box_(0);
}
binary(a, b, |x, y| bignum::divrem(x, y).0)
}
pub unsafe fn nat_div_exact(a: Obj, b: Obj) -> Obj {
nat_div(a, b)
}
pub unsafe fn nat_mod(a: Obj, b: Obj) -> Obj {
if is_scalar(a) && is_scalar(b) {
return box_(unbox(a).checked_rem(unbox(b)).unwrap_or(unbox(a)));
}
if b == box_(0) {
return binary(a, b, |x, _| x.to_vec());
}
binary(a, b, |x, y| bignum::divrem(x, y).1)
}
pub unsafe fn nat_dec_eq(a: Obj, b: Obj) -> u8 {
(compare(a, b) == Ordering::Equal) as u8
}
pub unsafe fn nat_dec_lt(a: Obj, b: Obj) -> u8 {
(compare(a, b) == Ordering::Less) as u8
}
pub unsafe fn nat_dec_le(a: Obj, b: Obj) -> u8 {
(compare(a, b) != Ordering::Greater) as u8
}
pub unsafe fn nat_land(a: Obj, b: Obj) -> Obj {
binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p & q))
}
pub unsafe fn nat_lor(a: Obj, b: Obj) -> Obj {
binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p | q))
}
pub unsafe fn nat_lxor(a: Obj, b: Obj) -> Obj {
binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p ^ q))
}
fn too_large(what: &str) -> ! {
panic!("inlean: out of memory: {what} is too large")
}
pub unsafe fn nat_shiftl(a: Obj, b: Obj) -> Obj {
if a == box_(0) {
return a;
}
let bits = small(b).unwrap_or_else(|| too_large("the shift amount"));
binary(a, b, |x, _| bignum::shl(x, bits))
}
pub unsafe fn nat_shiftr(a: Obj, b: Obj) -> Obj {
match small(b) {
Some(bits) => binary(a, b, |x, _| bignum::shr(x, bits)),
None => box_(0),
}
}
pub unsafe fn nat_pow(a: Obj, b: Obj) -> Obj {
if a == box_(0) || a == box_(1) {
return if b == box_(0) { box_(1) } else { a };
}
let exponent = small(b).unwrap_or_else(|| too_large("the exponent"));
binary(a, b, |x, _| bignum::pow(x, exponent))
}
pub unsafe fn nat_gcd(a: Obj, b: Obj) -> Obj {
binary(a, b, bignum::gcd)
}
pub unsafe fn nat_log2(a: Obj) -> Obj {
let mut scratch = [0u64; 1];
box_(bignum::bit_length(limbs(a, &mut scratch)).saturating_sub(1))
}
pub unsafe fn nat_powmod(base: Obj, exponent: Obj, modulus: Obj) -> Obj {
let (mut sb, mut se, mut sm) = ([0u64; 1], [0u64; 1], [0u64; 1]);
let (base, exponent, modulus) = (limbs(base, &mut sb), limbs(exponent, &mut se), limbs(modulus, &mut sm));
if modulus.is_empty() {
let exponent = match exponent {
[] => 0,
[single] if *single <= MAX_SMALL as u64 => *single as usize,
_ => too_large("the exponent"),
};
return from_limbs(bignum::pow(base, exponent));
}
let reduce = |x: &[u64]| bignum::divrem(x, modulus).1;
let mut result = reduce(&[1]);
let mut square = reduce(base);
for bit in 0..bignum::bit_length(exponent) {
if exponent[bit / 64] >> (bit % 64) & 1 == 1 {
result = reduce(&bignum::mul(&result, &square));
}
square = reduce(&bignum::mul(&square, &square));
}
from_limbs(result)
}
pub unsafe fn float_of_nat(a: Obj) -> f64 {
let mut scratch = [0u64; 1];
let limbs = limbs(a, &mut scratch);
match limbs {
[] => 0.0,
[single] => *single as f64,
_ => {
let bits = bignum::bit_length(limbs);
let shift = bits - 64;
let mut top = bignum::shr(limbs, shift)[0];
if bignum::shl(&[top], shift) != limbs {
top |= 1;
}
(top as f64) * 2f64.powi(shift as i32)
}
}
}
pub unsafe fn to_decimal(a: Obj) -> String {
let mut scratch = [0u64; 1];
bignum::to_decimal(limbs(a, &mut scratch))
}
pub unsafe fn to_u128(a: Obj) -> Option<u128> {
let mut scratch = [0u64; 1];
match limbs(a, &mut scratch) {
[] => Some(0),
[low] => Some(*low as u128),
[low, high] => Some((*high as u128) << 64 | *low as u128),
_ => None,
}
}
pub fn of_u128(value: u128) -> Obj {
from_u128(value)
}
pub unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
compare(a, b)
}
pub(crate) fn of_limbs(limbs: Vec<u64>) -> Obj {
from_limbs(limbs)
}
pub(crate) const OPS: &[&str] = &[
"usize_to_nat", "uint64_to_nat", "uint8_to_nat", "uint16_to_nat", "uint32_to_nat",
"uint8_of_nat", "uint16_of_nat", "uint32_of_nat", "uint64_of_nat", "usize_of_nat",
"uint8_of_nat_mk", "uint16_of_nat_mk", "uint32_of_nat_mk", "uint64_of_nat_mk", "usize_of_nat_mk",
"int8_of_nat", "int16_of_nat", "int32_of_nat", "int64_of_nat", "isize_of_nat",
"nat_succ", "nat_add", "nat_sub", "nat_pred", "nat_mul", "nat_div", "nat_div_exact", "nat_mod",
"nat_dec_eq", "nat_dec_lt", "nat_dec_le", "nat_land", "nat_lor", "nat_lxor", "nat_shiftl",
"nat_shiftr", "nat_pow", "nat_gcd", "nat_log2", "nat_powmod", "float_of_nat",
];