use std::{
cmp::Ordering,
fmt,
hash::{Hash, Hasher},
};
static FACTORS10: [i128; 39] = {
let mut factors = [1_i128; 39];
let mut i = 1;
while i < factors.len() {
factors[i] = factors[i - 1] * 10;
i += 1;
}
factors
};
const MAX_PRECISION: u8 = 38;
pub trait Base {
fn scale(self, scale: i64) -> i64;
}
pub trait InternalResult {
fn get(underlying: i64) -> Self;
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum NoBits {
N32,
N64,
N128,
}
#[derive(Clone)]
pub struct Decimal {
underlying: [u8; 16],
pub(crate) nobits: NoBits, pub(crate) precision: u8,
pub(crate) scale: u8,
}
impl Default for Decimal {
fn default() -> Self {
Decimal::from_raw(0, 9, 4, NoBits::N32)
}
}
impl Hash for Decimal {
fn hash<H: Hasher>(&self, state: &mut H) {
let mut value = self.internal128();
let mut scale = self.scale;
while scale > 0 && value % 10 == 0 {
value /= 10;
scale -= 1;
}
value.hash(state);
scale.hash(state);
}
}
macro_rules! base_for {
( $( $t:ty: $cast:expr ),* ) => {
$(
impl Base for $t {
fn scale(self, scale: i64) -> i64 {
$cast(self * (scale as $t)) as i64
}
}
)*
};
}
base_for! {
f32: std::convert::identity,
f64: std::convert::identity,
i8: i64::from,
i16: i64::from,
i32: i64::from,
i64: std::convert::identity,
u8: i64::from,
u16: i64::from,
u32: i64::from,
u64 : std::convert::identity
}
impl InternalResult for i32 {
#[inline(always)]
fn get(underlying: i64) -> Self {
underlying as Self
}
}
impl InternalResult for i64 {
#[inline(always)]
fn get(underlying: i64) -> Self {
underlying
}
}
impl NoBits {
pub(crate) fn from_precision(precision: u8) -> Option<NoBits> {
if precision <= 9 {
Some(NoBits::N32)
} else if precision <= 18 {
Some(NoBits::N64)
} else if precision <= MAX_PRECISION {
Some(NoBits::N128)
} else {
None
}
}
pub(crate) fn holds(self, value: i128) -> bool {
match self {
NoBits::N32 => i32::try_from(value).is_ok(),
NoBits::N64 => i64::try_from(value).is_ok(),
NoBits::N128 => true,
}
}
}
impl PartialEq for Decimal {
fn eq(&self, other: &Self) -> bool {
let (fine, coarse) = match self.scale.cmp(&other.scale) {
Ordering::Equal => return self.underlying == other.underlying,
Ordering::Less => (other, self),
Ordering::Greater => (self, other),
};
let delta = fine.scale() - coarse.scale();
coarse
.internal128()
.checked_mul(FACTORS10[delta])
.is_some_and(|scaled| scaled == fine.internal128())
}
}
fn decimal2str(decimal: &Decimal) -> String {
let underlying = decimal.internal128();
let mut r = underlying.unsigned_abs().to_string();
while r.len() <= decimal.scale() {
r.insert(0, '0');
}
if decimal.scale() > 0 {
let pos = r.len() - decimal.scale();
r.insert(pos, '.');
}
if underlying < 0 {
r.insert(0, '-');
}
r
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", decimal2str(self))
}
}
impl fmt::Debug for Decimal {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", decimal2str(self))
}
}
impl From<Decimal> for f32 {
fn from(value: Decimal) -> Self {
value.internal128() as f32 / FACTORS10[value.scale()] as f32
}
}
impl From<Decimal> for f64 {
fn from(value: Decimal) -> Self {
value.internal128() as f64 / FACTORS10[value.scale()] as f64
}
}
impl Decimal {
#[inline(always)]
pub(crate) fn from_raw(underlying: i128, precision: u8, scale: u8, nobits: NoBits) -> Self {
Decimal {
underlying: underlying.to_ne_bytes(),
nobits,
precision,
scale,
}
}
pub fn new(underlying: i64, scale: u8) -> Decimal {
let precision = 18;
if scale > precision {
panic!("scale can't be greater than 18");
}
Decimal::from_raw(i128::from(underlying), precision, scale, NoBits::N64)
}
pub fn new128(underlying: i128, scale: u8) -> Decimal {
if scale > MAX_PRECISION {
panic!("scale can't be greater than {MAX_PRECISION}");
}
let limit = FACTORS10[usize::from(MAX_PRECISION)];
if underlying.unsigned_abs() >= limit.unsigned_abs() {
panic!("{underlying} has more than {MAX_PRECISION} digits");
}
Decimal::from_raw(underlying, MAX_PRECISION, scale, NoBits::N128)
}
pub fn of<B: Base>(source: B, scale: u8) -> Decimal {
let precision = 18;
if scale > precision {
panic!("scale can't be greater than 18");
}
let underlying = i128::from(source.scale(FACTORS10[scale as usize] as i64));
if underlying > FACTORS10[precision as usize] {
panic!("{} > {}", underlying, FACTORS10[precision as usize]);
}
Decimal::from_raw(underlying, precision, scale, NoBits::N64)
}
#[inline(always)]
pub fn internal<I: InternalResult>(&self) -> I {
InternalResult::get(self.internal128() as i64)
}
#[inline(always)]
pub fn internal128(&self) -> i128 {
i128::from_ne_bytes(self.underlying)
}
pub fn scale(&self) -> usize {
self.scale as usize
}
pub(crate) fn rescaled(&self, scale: u8) -> Option<i128> {
match scale.cmp(&self.scale) {
Ordering::Less => {
Some(self.internal128() / *FACTORS10.get(self.scale() - scale as usize)?)
}
Ordering::Equal => Some(self.internal128()),
Ordering::Greater => self
.internal128()
.checked_mul(*FACTORS10.get(scale as usize - self.scale())?),
}
}
pub(crate) fn rescaled_within(&self, precision: u8, scale: u8) -> Option<i128> {
let value = self.rescaled(scale)?;
let limit = *FACTORS10.get(usize::from(precision))?;
(value.unsigned_abs() < limit.unsigned_abs()).then_some(value)
}
pub(crate) fn set_scale(self, scale: u8) -> Self {
let underlying = match scale.cmp(&self.scale) {
Ordering::Less => {
let delta = self.scale() - scale as usize;
self.internal128() / FACTORS10[delta]
}
Ordering::Equal => return self,
Ordering::Greater => {
let delta = scale as usize - self.scale();
self.internal128() * FACTORS10[delta]
}
};
Decimal::from_raw(underlying, self.precision, scale, self.nobits)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_new() {
assert_eq!(Decimal::new(2, 1), Decimal::of(0.2_f64, 1));
assert_eq!(Decimal::new(2, 5), Decimal::of(0.00002_f64, 5));
}
#[test]
fn test_display() {
assert_eq!(format!("{}", Decimal::of(2.1_f32, 4)), "2.1000");
assert_eq!(format!("{}", Decimal::of(0.2_f64, 4)), "0.2000");
assert_eq!(format!("{}", Decimal::of(2, 4)), "2.0000");
assert_eq!(format!("{:?}", Decimal::of(2, 4)), "2.0000");
}
#[test]
fn test_eq() {
assert_eq!(Decimal::of(2.0_f64, 4), Decimal::of(2.0_f64, 4));
assert_ne!(Decimal::of(3.0_f64, 4), Decimal::of(2.0_f64, 4));
assert_eq!(Decimal::of(2.0_f64, 4), Decimal::of(2.0_f64, 2));
assert_ne!(Decimal::of(2.0_f64, 4), Decimal::of(3.0_f64, 2));
assert_eq!(Decimal::of(2.0_f64, 2), Decimal::of(2.0_f64, 4));
assert_ne!(Decimal::of(3.0_f64, 2), Decimal::of(2.0_f64, 4));
}
#[test]
fn test_decimal128() {
let largest = FACTORS10[38] - 1;
let big = Decimal::new128(-largest, 10);
assert_eq!(big.to_string(), "-9999999999999999999999999999.9999999999");
assert_eq!(big.internal128(), -largest);
assert_eq!(Decimal::new128(-5, 2).to_string(), "-0.05");
assert_eq!(Decimal::new128(7, 0).to_string(), "7");
assert_eq!(Decimal::new128(2, 1), Decimal::of(0.2_f64, 1));
let raw_max = Decimal::from_raw(i128::MAX, 38, 0, NoBits::N128);
assert_eq!(raw_max.to_string(), i128::MAX.to_string());
assert_ne!(raw_max, Decimal::new128(1, 1));
}
#[test]
#[should_panic(expected = "more than 38 digits")]
fn test_new128_rejects_39_digits() {
Decimal::new128(FACTORS10[38], 0);
}
#[test]
fn test_rescaled() {
let d = Decimal::new(12345, 2); assert_eq!(d.rescaled(4), Some(1_234_500));
assert_eq!(d.rescaled(1), Some(1234));
assert_eq!(Decimal::new128(FACTORS10[37], 0).rescaled(2), None);
assert_eq!(d.rescaled(255), None);
assert_eq!(
Decimal::from_raw(1, 38, 255, NoBits::N128).rescaled(0),
None
);
assert_eq!(d.rescaled_within(9, 4), Some(1_234_500));
assert_eq!(d.rescaled_within(4, 1), Some(1234));
assert_eq!(d.rescaled_within(3, 1), None);
assert_eq!(Decimal::new(999, 0).rescaled_within(3, 0), Some(999));
assert_eq!(Decimal::new(-1000, 0).rescaled_within(3, 0), None);
assert_eq!(Decimal::new(-5, 0).rescaled_within(9, 9), None);
let wide = Decimal::new128(1 << 64, 0);
assert_eq!(wide.rescaled_within(18, 0), None);
assert_eq!(wide.rescaled_within(38, 0), Some(1 << 64));
assert_eq!(
Decimal::new128(FACTORS10[36], 0).rescaled_within(38, 2),
None
);
assert_eq!(
Decimal::new128(FACTORS10[36] - 1, 0).rescaled_within(38, 2),
Some((FACTORS10[36] - 1) * 100)
);
}
#[test]
fn test_holds() {
assert!(NoBits::N32.holds(i128::from(i32::MIN)));
assert!(!NoBits::N32.holds(i128::from(i32::MAX) + 1));
assert!(NoBits::N64.holds(i128::from(i64::MAX)));
assert!(!NoBits::N64.holds(1 << 64));
assert!(NoBits::N128.holds(i128::MIN));
}
#[test]
fn test_negative_display() {
assert_eq!(Decimal::new(-5, 2).to_string(), "-0.05");
assert_eq!(Decimal::new(-1234, 2).to_string(), "-12.34");
assert_eq!(Decimal::new(0, 3).to_string(), "0.000");
}
#[test]
fn test_internal32() {
let internal: i32 = Decimal::of(2, 4).internal();
assert_eq!(internal, 20000_i32);
}
#[test]
fn test_internal64() {
let internal: i64 = Decimal::of(2, 4).internal();
assert_eq!(internal, 20000_i64);
}
#[test]
fn test_scale() {
assert_eq!(Decimal::of(2, 4).scale(), 4);
}
#[test]
fn test_from_f32() {
let value: f32 = Decimal::of(2, 4).into();
assert!((value - 2.0_f32).abs() <= f32::EPSILON);
}
#[test]
fn test_from_f64() {
let value: f64 = Decimal::of(2, 4).into();
assert!((value - 2.0_f64).abs() < f64::EPSILON);
}
#[test]
fn set_scale1() {
let a = Decimal::of(12, 3);
let b = a.set_scale(2);
assert_eq!(2, b.scale);
assert_eq!(1200, b.internal128());
}
#[test]
fn set_scale2() {
let a = Decimal::of(12, 3);
let b = a.set_scale(4);
assert_eq!(4, b.scale);
assert_eq!(120_000, b.internal128());
}
#[test]
fn test_decimal2str() {
let d = Decimal::of(0.00001, 5);
let actual = decimal2str(&d);
assert_eq!(actual, "0.00001".to_string());
}
}