use std::cmp::Ordering;
use std::fmt;
pub const MAX_DIGITS: u16 = 38;
#[derive(Debug, Clone, Copy)]
pub struct Decimal {
unscaled: i128,
scale: u16,
}
#[derive(Debug, Clone, Copy)]
enum Round {
Half,
Up,
Down,
}
impl Decimal {
pub fn new(unscaled: i128, scale: u16) -> Decimal {
Decimal { unscaled, scale }
}
pub fn unscaled(&self) -> i128 {
self.unscaled
}
pub fn scale(&self) -> u16 {
self.scale
}
pub fn is_zero(&self) -> bool {
self.unscaled == 0
}
pub fn digits(&self) -> u16 {
let mut left = self.unscaled.unsigned_abs();
let mut digits = 1;
while left >= 10 {
left /= 10;
digits += 1;
}
digits
}
pub fn rescale(&self, scale: u16) -> Option<Decimal> {
match scale.cmp(&self.scale) {
Ordering::Equal => Some(*self),
Ordering::Greater => {
let by = 10i128.checked_pow(u32::from(scale - self.scale))?;
Some(Decimal {
unscaled: self.unscaled.checked_mul(by)?,
scale,
})
}
Ordering::Less => {
let by = 10i128.checked_pow(u32::from(self.scale - scale))?;
match self.unscaled % by {
0 => Some(Decimal {
unscaled: self.unscaled / by,
scale,
}),
_ => None,
}
}
}
}
pub fn abs(&self) -> Option<Decimal> {
Some(Decimal {
unscaled: self.unscaled.checked_abs()?,
scale: self.scale,
})
}
pub fn signum(&self) -> i64 {
self.unscaled.signum() as i64
}
pub fn round(&self, digits: i64) -> Option<Decimal> {
self.quantize(digits, Round::Half)
}
pub fn ceil(&self, digits: i64) -> Option<Decimal> {
self.quantize(digits, Round::Up)
}
pub fn floor(&self, digits: i64) -> Option<Decimal> {
self.quantize(digits, Round::Down)
}
fn quantize(&self, digits: i64, mode: Round) -> Option<Decimal> {
let scale = u16::try_from(digits.max(0)).ok()?.min(MAX_DIGITS);
let drop = i64::from(self.scale) - digits;
if drop <= 0 {
return self.rescale(scale);
}
let by = 10i128.checked_pow(u32::try_from(drop).ok()?)?;
let (whole, rest) = (self.unscaled / by, self.unscaled % by);
let carried = match mode {
Round::Half if rest.checked_mul(2)?.abs() >= by => match self.unscaled.is_negative() {
true => whole.checked_sub(1)?,
false => whole.checked_add(1)?,
},
Round::Up if rest > 0 => whole.checked_add(1)?,
Round::Down if rest < 0 => whole.checked_sub(1)?,
_ => whole,
};
let back = 10i128.checked_pow(u32::try_from(i64::from(scale) - digits).ok()?)?;
Some(Decimal {
unscaled: carried.checked_mul(back)?,
scale,
})
}
pub fn truncate(&self) -> Option<i128> {
let by = 10i128.checked_pow(u32::from(self.scale))?;
Some(self.unscaled / by)
}
pub fn to_f64(&self) -> f64 {
self.unscaled as f64 / 10f64.powi(i32::from(self.scale))
}
pub fn parse(text: &str, scale: u16) -> Option<Decimal> {
let text = text.trim();
let (negative, rest) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let (mantissa, exponent) = match rest.split_once(['e', 'E']) {
Some((m, e)) => (m, e.parse::<i32>().ok()?),
None => (rest, 0),
};
let (whole, fraction) = match mantissa.split_once('.') {
Some((w, f)) => (w, f),
None => (mantissa, ""),
};
if whole.is_empty() && fraction.is_empty() {
return None;
}
if !whole
.bytes()
.chain(fraction.bytes())
.all(|b| b.is_ascii_digit())
{
return None;
}
let mut digits: i128 = 0;
for byte in whole.bytes().chain(fraction.bytes()) {
digits = digits
.checked_mul(10)?
.checked_add(i128::from(byte - b'0'))?;
}
let written = i64::try_from(fraction.len())
.ok()?
.checked_sub(i64::from(exponent))?;
let unscaled = shift(digits, written, i64::from(scale))?;
Some(Decimal {
unscaled: match negative {
true => -unscaled,
false => unscaled,
},
scale,
})
}
pub fn add(&self, other: &Decimal) -> Option<Decimal> {
let (a, b) = align(self, other)?;
Some(Decimal {
unscaled: a.unscaled.checked_add(b.unscaled)?,
scale: a.scale,
})
}
pub fn sub(&self, other: &Decimal) -> Option<Decimal> {
let (a, b) = align(self, other)?;
Some(Decimal {
unscaled: a.unscaled.checked_sub(b.unscaled)?,
scale: a.scale,
})
}
pub fn mul(&self, other: &Decimal) -> Option<Decimal> {
let scale = self.scale.checked_add(other.scale)?;
if scale > MAX_DIGITS {
return None;
}
Some(Decimal {
unscaled: self.unscaled.checked_mul(other.unscaled)?,
scale,
})
}
pub fn div(&self, other: &Decimal) -> Option<Decimal> {
if other.unscaled == 0 {
return None;
}
let scale = self
.scale
.max(other.scale)
.saturating_add(6)
.min(MAX_DIGITS);
let up = i64::from(scale) + i64::from(other.scale) - i64::from(self.scale);
let numerator = shift(i128::try_from(self.unscaled.unsigned_abs()).ok()?, 0, up)?;
let divisor = i128::try_from(other.unscaled.unsigned_abs()).ok()?;
let quotient = numerator / divisor;
let unscaled = match (numerator % divisor).checked_mul(2) {
Some(twice) if twice >= divisor => quotient.checked_add(1)?,
_ => quotient,
};
Some(Decimal {
unscaled: match self.unscaled.is_negative() != other.unscaled.is_negative() {
true => -unscaled,
false => unscaled,
},
scale,
})
}
pub fn rem(&self, other: &Decimal) -> Option<Decimal> {
let (a, b) = align(self, other)?;
if b.unscaled == 0 {
return None;
}
Some(Decimal {
unscaled: a.unscaled.checked_rem(b.unscaled)?,
scale: a.scale,
})
}
pub fn negate(&self) -> Option<Decimal> {
Some(Decimal {
unscaled: self.unscaled.checked_neg()?,
scale: self.scale,
})
}
}
fn shift<T>(digits: T, from: i64, to: i64) -> Option<i128>
where
i128: TryFrom<T>,
{
let digits = i128::try_from(digits).ok()?;
match to.checked_sub(from)? {
0 => Some(digits),
by if by > 0 => digits.checked_mul(10i128.checked_pow(u32::try_from(by).ok()?)?),
by => {
let down = 10i128.checked_pow(u32::try_from(-by).ok()?)?;
let whole = digits / down;
match (digits % down).checked_mul(2) {
Some(twice) if twice.abs() >= down => match digits.is_negative() {
true => whole.checked_sub(1),
false => whole.checked_add(1),
},
_ => Some(whole),
}
}
}
}
fn align(a: &Decimal, b: &Decimal) -> Option<(Decimal, Decimal)> {
let scale = a.scale.max(b.scale);
Some((a.rescale(scale)?, b.rescale(scale)?))
}
impl PartialEq for Decimal {
fn eq(&self, other: &Decimal) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Decimal {}
impl Ord for Decimal {
fn cmp(&self, other: &Decimal) -> Ordering {
if let Some((a, b)) = align(self, other) {
return a.unscaled.cmp(&b.unscaled);
}
let sign = self.unscaled.signum().cmp(&other.unscaled.signum());
if sign != Ordering::Equal {
return sign;
}
let whole = |d: &Decimal| i32::from(d.digits()) - i32::from(d.scale);
let by_size = whole(self).cmp(&whole(other));
match self.unscaled.is_negative() {
true => by_size.reverse(),
false => by_size,
}
}
}
impl PartialOrd for Decimal {
fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl std::hash::Hash for Decimal {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let (mut unscaled, mut scale) = (self.unscaled, i64::from(self.scale));
while unscaled != 0 && unscaled % 10 == 0 {
unscaled /= 10;
scale -= 1;
}
unscaled.hash(state);
match unscaled {
0 => 0i64.hash(state),
_ => scale.hash(state),
}
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.scale == 0 {
return write!(f, "{}", self.unscaled);
}
let digits = self.unscaled.unsigned_abs().to_string();
let places = usize::from(self.scale);
let sign = match self.unscaled.is_negative() {
true => "-",
false => "",
};
if digits.len() <= places {
let pad = "0".repeat(places - digits.len());
return write!(f, "{sign}0.{pad}{digits}");
}
let (whole, fraction) = digits.split_at(digits.len() - places);
write!(f, "{sign}{whole}.{fraction}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_decimal_prints_at_the_scale_it_was_written_with() {
assert_eq!(Decimal::new(120, 2).to_string(), "1.20");
assert_eq!(Decimal::new(12, 1).to_string(), "1.2");
assert_eq!(Decimal::new(12, 0).to_string(), "12");
assert_eq!(Decimal::new(-120, 2).to_string(), "-1.20");
assert_eq!(Decimal::new(5, 3).to_string(), "0.005");
assert_eq!(Decimal::new(-5, 3).to_string(), "-0.005");
assert_eq!(Decimal::new(0, 2).to_string(), "0.00");
}
#[test]
fn two_spellings_of_one_number_are_one_value() {
let (loose, tight) = (Decimal::new(12, 1), Decimal::new(120, 2));
assert_eq!(loose, tight);
assert_eq!(loose.cmp(&tight), Ordering::Equal);
let hash = |d: &Decimal| {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
d.hash(&mut h);
h.finish()
};
assert_eq!(hash(&loose), hash(&tight));
assert_eq!(hash(&Decimal::new(0, 0)), hash(&Decimal::new(0, 7)));
assert_ne!(loose.to_string(), tight.to_string());
}
#[test]
fn a_tenth_and_two_tenths_are_three_tenths() {
let (a, b) = (
Decimal::parse("0.1", 1).unwrap(),
Decimal::parse("0.2", 1).unwrap(),
);
assert_eq!(a.add(&b).unwrap().to_string(), "0.3");
assert_ne!(a.to_f64() + b.to_f64(), 0.3f64);
}
#[test]
fn arithmetic_answers_at_the_scale_the_units_give() {
let (a, b) = (Decimal::new(150, 2), Decimal::new(3, 1));
assert_eq!(a.add(&b).unwrap().to_string(), "1.80");
assert_eq!(a.sub(&b).unwrap().to_string(), "1.20");
assert_eq!(a.mul(&b).unwrap().to_string(), "0.450");
assert_eq!(a.rem(&b).unwrap().to_string(), "0.00");
assert_eq!(a.negate().unwrap().to_string(), "-1.50");
}
#[test]
fn a_quotient_is_carried_as_far_as_the_operands_knew() {
let third = Decimal::new(1, 0).div(&Decimal::new(3, 0)).unwrap();
assert_eq!(third.to_string(), "0.333333");
assert_eq!(
Decimal::new(2, 0)
.div(&Decimal::new(3, 0))
.unwrap()
.to_string(),
"0.666667"
);
assert_eq!(
Decimal::new(-2, 0)
.div(&Decimal::new(3, 0))
.unwrap()
.to_string(),
"-0.666667"
);
let each = Decimal::new(1000, 2).div(&Decimal::new(4, 0)).unwrap();
assert_eq!(each.rescale(2).unwrap().to_string(), "2.50");
assert_eq!(Decimal::new(1, 0).div(&Decimal::new(0, 0)), None);
}
#[test]
fn text_is_read_at_the_scale_it_is_wanted_at() {
assert_eq!(Decimal::parse("1.20", 2).unwrap(), Decimal::new(120, 2));
assert_eq!(
Decimal::parse(" -3.5 ", 3).unwrap(),
Decimal::new(-3500, 3)
);
assert_eq!(Decimal::parse("12", 2).unwrap(), Decimal::new(1200, 2));
assert_eq!(Decimal::parse(".5", 1).unwrap(), Decimal::new(5, 1));
assert_eq!(Decimal::parse("5.", 1).unwrap(), Decimal::new(50, 1));
assert_eq!(Decimal::parse("1E3", 0).unwrap(), Decimal::new(1000, 0));
assert_eq!(Decimal::parse("15e-2", 2).unwrap(), Decimal::new(15, 2));
assert_eq!(Decimal::parse("1.005", 2).unwrap(), Decimal::new(101, 2));
assert_eq!(Decimal::parse("-1.005", 2).unwrap(), Decimal::new(-101, 2));
assert_eq!(Decimal::parse("1.004", 2).unwrap(), Decimal::new(100, 2));
for not_a_number in ["", ".", "x", "1.2.3", "1,000", "1e", "0x10"] {
assert_eq!(Decimal::parse(not_a_number, 2), None, "{not_a_number}");
}
}
#[test]
fn a_rescale_that_would_not_be_exact_is_refused() {
let value = Decimal::new(125, 2);
assert_eq!(value.rescale(4).unwrap(), Decimal::new(12500, 4));
assert_eq!(value.rescale(2).unwrap(), value);
assert_eq!(value.rescale(1), None);
assert_eq!(
Decimal::new(120, 2).rescale(1).unwrap(),
Decimal::new(12, 1)
);
}
#[test]
fn rounding_stops_at_the_place_it_was_asked_for() {
let value = Decimal::parse("1.005", 3).unwrap();
assert_eq!(value.round(2).unwrap().to_string(), "1.01");
assert_eq!(value.round(0).unwrap().to_string(), "1");
assert_eq!(value.round(5).unwrap().to_string(), "1.00500");
}
#[test]
fn halves_go_away_from_nought_on_both_sides_of_it() {
assert_eq!(Decimal::new(25, 1).round(0).unwrap().to_string(), "3");
assert_eq!(Decimal::new(-25, 1).round(0).unwrap().to_string(), "-3");
assert_eq!(Decimal::new(35, 1).round(0).unwrap().to_string(), "4");
}
#[test]
fn a_negative_digit_count_rounds_to_the_left_of_the_point() {
assert_eq!(Decimal::new(1505, 1).round(-1).unwrap().to_string(), "150");
assert_eq!(Decimal::new(150, 0).round(-2).unwrap().to_string(), "200");
assert_eq!(Decimal::new(-150, 0).round(-2).unwrap().to_string(), "-200");
assert_eq!(Decimal::new(149, 0).round(-2).unwrap().to_string(), "100");
}
#[test]
fn a_ceiling_and_a_floor_lean_the_same_way_for_both_signs() {
let up = Decimal::new(15, 1);
let down = Decimal::new(-15, 1);
assert_eq!(up.ceil(0).unwrap().to_string(), "2");
assert_eq!(up.floor(0).unwrap().to_string(), "1");
assert_eq!(down.ceil(0).unwrap().to_string(), "-1");
assert_eq!(down.floor(0).unwrap().to_string(), "-2");
assert_eq!(Decimal::new(2, 0).ceil(0).unwrap().to_string(), "2");
}
#[test]
fn the_digit_count_is_of_the_number_and_not_of_the_declaration() {
assert_eq!(Decimal::new(0, 4).digits(), 1);
assert_eq!(Decimal::new(9, 0).digits(), 1);
assert_eq!(Decimal::new(10, 0).digits(), 2);
assert_eq!(Decimal::new(-999, 2).digits(), 3);
assert_eq!(Decimal::new(i128::MAX, 0).digits(), 39);
}
#[test]
fn ordering_holds_where_the_scales_cannot_be_aligned() {
let huge = Decimal::new(i128::MAX, 0);
let small = Decimal::new(1, MAX_DIGITS);
assert_eq!(huge.cmp(&small), Ordering::Greater);
assert_eq!(small.cmp(&huge), Ordering::Less);
assert_eq!(
huge.negate().unwrap().cmp(&small.negate().unwrap()),
Ordering::Less
);
assert_eq!(Decimal::new(0, 0).cmp(&small), Ordering::Less);
}
}