use crate::nat;
use crate::object::{box_, dec, Obj};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;
pub struct Nat(Obj);
unsafe impl Send for Nat {}
unsafe impl Sync for Nat {}
impl Nat {
#[doc(hidden)]
pub unsafe fn from_raw(raw: Obj) -> Nat {
Nat(raw)
}
#[doc(hidden)]
#[inline]
pub unsafe fn owning(raw: Obj) -> Nat {
Nat(nat::owned(raw))
}
#[doc(hidden)]
pub fn as_raw(&self) -> Obj {
self.0
}
#[doc(hidden)]
pub fn into_raw(self) -> Obj {
let raw = self.0;
std::mem::forget(self);
raw
}
}
impl Clone for Nat {
#[inline]
fn clone(&self) -> Nat {
Nat(unsafe { nat::unshared(self.0) })
}
}
impl Drop for Nat {
#[inline]
fn drop(&mut self) {
unsafe { dec(self.0) };
}
}
impl Default for Nat {
fn default() -> Nat {
Nat(box_(0))
}
}
impl From<&Nat> for Nat {
fn from(value: &Nat) -> Nat {
value.clone()
}
}
impl From<u128> for Nat {
fn from(value: u128) -> Nat {
Nat(nat::of_u128(value))
}
}
macro_rules! conversions {
($($ty:ty),*) => {$(
impl From<$ty> for Nat {
fn from(value: $ty) -> Nat {
Nat(nat::uint64_to_nat(value as u64))
}
}
impl TryFrom<&Nat> for $ty {
type Error = TooLarge;
fn try_from(value: &Nat) -> Result<$ty, TooLarge> {
u128::try_from(value)?.try_into().map_err(|_| TooLarge)
}
}
impl TryFrom<Nat> for $ty {
type Error = TooLarge;
fn try_from(value: Nat) -> Result<$ty, TooLarge> {
<$ty>::try_from(&value)
}
}
)*};
}
conversions!(u8, u16, u32, u64, usize);
impl TryFrom<&Nat> for u128 {
type Error = TooLarge;
fn try_from(value: &Nat) -> Result<u128, TooLarge> {
unsafe { nat::to_u128(value.0) }.ok_or(TooLarge)
}
}
impl TryFrom<Nat> for u128 {
type Error = TooLarge;
fn try_from(value: Nat) -> Result<u128, TooLarge> {
u128::try_from(&value)
}
}
impl Nat {
pub fn from_limbs(limbs: &[u64]) -> Nat {
Nat(nat::of_limbs(limbs))
}
pub fn to_limbs(&self) -> Vec<u64> {
unsafe { nat::with_limbs(self.0, <[u64]>::to_vec) }
}
}
impl<const N: usize> From<[u64; N]> for Nat {
fn from(limbs: [u64; N]) -> Nat {
Nat::from_limbs(&limbs)
}
}
impl<const N: usize> TryFrom<&Nat> for [u64; N] {
type Error = TooLarge;
fn try_from(value: &Nat) -> Result<[u64; N], TooLarge> {
unsafe { nat::with_limbs(value.0, crate::codec::fixed_limbs) }.ok_or(TooLarge)
}
}
impl<const N: usize> TryFrom<Nat> for [u64; N] {
type Error = TooLarge;
fn try_from(value: Nat) -> Result<[u64; N], TooLarge> {
<[u64; N]>::try_from(&value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TooLarge;
impl fmt::Display for TooLarge {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the natural number does not fit the integer type")
}
}
impl std::error::Error for TooLarge {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseNatError;
impl fmt::Display for ParseNatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("expected a natural number in decimal digits")
}
}
impl std::error::Error for ParseNatError {}
impl FromStr for Nat {
type Err = ParseNatError;
fn from_str(text: &str) -> Result<Nat, ParseNatError> {
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
return Err(ParseNatError);
}
Ok(Nat(nat::cstr_to_nat(text)))
}
}
impl fmt::Display for Nat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(true, "", &unsafe { nat::to_decimal(self.0) })
}
}
impl fmt::Debug for Nat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl PartialEq for Nat {
fn eq(&self, other: &Nat) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Nat {}
impl PartialOrd for Nat {
fn partial_cmp(&self, other: &Nat) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Nat {
fn cmp(&self, other: &Nat) -> Ordering {
unsafe { nat::ordering(self.0, other.0) }
}
}
impl std::hash::Hash for Nat {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
unsafe { nat::with_limbs(self.0, |limbs| limbs.hash(state)) }
}
}
pub struct Int(Obj);
unsafe impl Send for Int {}
unsafe impl Sync for Int {}
impl Int {
#[doc(hidden)]
pub unsafe fn from_raw(raw: Obj) -> Int {
Int(raw)
}
#[doc(hidden)]
#[inline]
pub unsafe fn owning(raw: Obj) -> Int {
Int(nat::owned(raw))
}
#[doc(hidden)]
pub fn as_raw(&self) -> Obj {
self.0
}
#[doc(hidden)]
pub fn into_raw(self) -> Obj {
let raw = self.0;
std::mem::forget(self);
raw
}
}
impl Clone for Int {
#[inline]
fn clone(&self) -> Int {
Int(unsafe { nat::unshared(self.0) })
}
}
impl Drop for Int {
#[inline]
fn drop(&mut self) {
unsafe { dec(self.0) };
}
}
impl Default for Int {
fn default() -> Int {
Int(box_(0))
}
}
impl From<&Int> for Int {
fn from(value: &Int) -> Int {
value.clone()
}
}
impl From<i128> for Int {
fn from(value: i128) -> Int {
Int(crate::int::of_i128(value))
}
}
impl From<Nat> for Int {
fn from(value: Nat) -> Int {
Int(unsafe { crate::int::nat_to_int(value.into_raw()) })
}
}
macro_rules! int_conversions {
($($ty:ty),*) => {$(
impl From<$ty> for Int {
fn from(value: $ty) -> Int {
Int(crate::int::of_i128(value as i128))
}
}
impl TryFrom<&Int> for $ty {
type Error = TooLarge;
fn try_from(value: &Int) -> Result<$ty, TooLarge> {
i128::try_from(value)?.try_into().map_err(|_| TooLarge)
}
}
impl TryFrom<Int> for $ty {
type Error = TooLarge;
fn try_from(value: Int) -> Result<$ty, TooLarge> {
<$ty>::try_from(&value)
}
}
)*};
}
int_conversions!(i8, i16, i32, i64, isize);
impl TryFrom<&Int> for i128 {
type Error = TooLarge;
fn try_from(value: &Int) -> Result<i128, TooLarge> {
unsafe { crate::int::to_i128(value.0) }.ok_or(TooLarge)
}
}
impl TryFrom<Int> for i128 {
type Error = TooLarge;
fn try_from(value: Int) -> Result<i128, TooLarge> {
i128::try_from(&value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseIntError;
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("expected an integer in decimal digits")
}
}
impl std::error::Error for ParseIntError {}
impl FromStr for Int {
type Err = ParseIntError;
fn from_str(text: &str) -> Result<Int, ParseIntError> {
let (negative, digits) = match text.strip_prefix('-') {
Some(digits) => (true, digits),
None => (false, text),
};
crate::int::from_decimal(negative, digits).map(Int).ok_or(ParseIntError)
}
}
impl fmt::Display for Int {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = unsafe { crate::int::to_decimal(self.0) };
match text.strip_prefix('-') {
Some(digits) => f.pad_integral(false, "", digits),
None => f.pad_integral(true, "", &text),
}
}
}
impl fmt::Debug for Int {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl PartialEq for Int {
fn eq(&self, other: &Int) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Int {}
impl PartialOrd for Int {
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Int {
fn cmp(&self, other: &Int) -> Ordering {
unsafe { crate::int::ordering(self.0, other.0) }
}
}
impl std::hash::Hash for Int {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
unsafe { crate::int::hash(self.0, state) }
}
}
pub struct Generic<'a, const N: usize>(Obj, std::marker::PhantomData<&'a ()>);
impl<const N: usize> Generic<'_, N> {
#[doc(hidden)]
#[inline(always)]
pub unsafe fn from_raw(raw: Obj) -> Self {
Generic(raw, std::marker::PhantomData)
}
#[doc(hidden)]
#[inline(always)]
pub fn into_raw(self) -> Obj {
let raw = self.0;
std::mem::forget(self);
raw
}
}
impl<const N: usize> Clone for Generic<'_, N> {
#[inline]
fn clone(&self) -> Self {
unsafe { crate::object::inc(self.0) };
Generic(self.0, std::marker::PhantomData)
}
}
impl<const N: usize> Drop for Generic<'_, N> {
#[inline]
fn drop(&mut self) {
unsafe { dec(self.0) };
}
}