use crate::common::impl_fixed19;
use crate::consts::ONE_RAW;
use crate::{Dec19, OutOfRange, Round};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[must_use]
#[repr(transparent)]
pub struct UDec19(u128);
impl_fixed19! {
type = UDec19,
raw = u128,
int = u64,
mac = "udec",
max_ascii_len = 40,
sub_overflow = "UDec19 subtraction would be negative",
}
impl UDec19 {
const KEY_FLIP: u128 = 0;
const LITERAL_RANGE_ERROR: &'static str =
"udec! literal out of range (0 to about 3.4e19)";
#[inline]
pub(crate) const fn to_parts(self) -> (bool, u128) {
(false, self.0)
}
#[inline]
pub(crate) const fn raw_from_parts(
negative: bool,
magnitude: u128,
) -> Option<u128> {
if negative && magnitude != 0 {
None
} else {
Some(magnitude)
}
}
#[inline]
pub(crate) const fn from_parts(
negative: bool,
magnitude: u128,
) -> Option<Self> {
match Self::raw_from_parts(negative, magnitude) {
Some(raw) => Some(Self(raw)),
None => None,
}
}
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
Self(self.0.abs_diff(other.0))
}
#[inline]
#[track_caller]
pub fn signed_sub(self, other: Self) -> Dec19 {
self
.checked_signed_sub(other)
.expect("UDec19::signed_sub result out of Dec19 range")
}
#[must_use]
#[inline]
pub fn checked_signed_sub(self, other: Self) -> Option<Dec19> {
let negative = self.0 < other.0;
Dec19::from_parts(negative, self.0.abs_diff(other.0))
}
#[track_caller]
#[inline]
pub fn mul(self, rhs: Self, mode: Round) -> Self {
self
.checked_mul(rhs, mode)
.expect("UDec19 overflow in multiplication")
}
#[must_use]
#[inline]
pub fn checked_mul(self, rhs: Self, mode: Round) -> Option<Self> {
crate::kernel::mul::mul_parts(self.0, rhs.0, false, mode).map(Self)
}
#[inline]
pub fn saturating_mul(self, rhs: Self, mode: Round) -> Self {
self.checked_mul(rhs, mode).unwrap_or(Self::MAX)
}
#[track_caller]
#[inline]
pub fn div(self, rhs: Self, mode: Round) -> Self {
self
.checked_div(rhs, mode)
.expect("UDec19 division by zero or overflow")
}
#[must_use]
#[inline]
pub fn checked_div(self, rhs: Self, mode: Round) -> Option<Self> {
crate::kernel::div::div_parts(self.0, rhs.0, false, mode).map(Self)
}
}
macro_rules! from_int {
($($t:ty),*) => {$(
impl From<$t> for UDec19 {
#[inline]
fn from(n: $t) -> Self {
Self(n as u128 * ONE_RAW)
}
}
)*};
}
from_int!(u8, u16, u32, u64);
macro_rules! try_from_int {
($($t:ty),*) => {$(
impl TryFrom<$t> for UDec19 {
type Error = OutOfRange;
#[inline]
fn try_from(n: $t) -> Result<Self, OutOfRange> {
u128::try_from(n)
.ok()
.and_then(|n| n.checked_mul(ONE_RAW))
.map(Self)
.ok_or(OutOfRange)
}
}
)*};
}
try_from_int!(i8, i16, i32, i64, i128, u128);
impl TryFrom<Dec19> for UDec19 {
type Error = OutOfRange;
#[inline]
fn try_from(v: Dec19) -> Result<Self, OutOfRange> {
u128::try_from(v.to_raw()).map(Self).map_err(|_| OutOfRange)
}
}