use std::fmt;
use std::str::FromStr;
use bigdecimal::num_bigint::{BigInt, Sign};
use bigdecimal::{BigDecimal, One, ToPrimitive, Zero};
use serde::{Serialize, Serializer};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Decimal(pub BigDecimal);
impl Decimal {
pub fn new(value: BigDecimal) -> Self {
Self(value)
}
pub fn to_f64(&self) -> f64 {
self.0.to_f64().unwrap_or(0.0)
}
pub fn is_zero(&self) -> bool {
self.0.is_zero()
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (digits, scale) = normalized(&self.0);
let negative = digits.sign() == Sign::Minus;
let text = digits.magnitude().to_string();
let (int, frac) = if scale <= 0 {
let zeros = "0".repeat(usize::try_from(-scale).unwrap_or(0));
(format!("{text}{zeros}"), String::from("0"))
} else {
let scale = usize::try_from(scale).unwrap_or(0);
let padded = format!("{text:0>width$}", width = scale + 1);
let (int, frac) = padded.split_at(padded.len() - scale);
(int.to_owned(), frac.to_owned())
};
let sign = if negative { "-" } else { "" };
write!(f, "{sign}{int}.{frac}")
}
}
impl FromStr for Decimal {
type Err = bigdecimal::ParseBigDecimalError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
BigDecimal::from_str(text.trim()).map(Decimal)
}
}
impl From<BigDecimal> for Decimal {
fn from(value: BigDecimal) -> Self {
Decimal(value)
}
}
impl From<i64> for Decimal {
fn from(value: i64) -> Self {
Decimal(value.into())
}
}
impl From<i32> for Decimal {
fn from(value: i32) -> Self {
Decimal(value.into())
}
}
macro_rules! exact_ops {
($($trait:ident $method:ident),*) => {$(
impl std::ops::$trait for Decimal {
type Output = Decimal;
fn $method(self, other: Decimal) -> Decimal {
Decimal(std::ops::$trait::$method(self.0, other.0))
}
}
impl std::ops::$trait<&Decimal> for &Decimal {
type Output = Decimal;
fn $method(self, other: &Decimal) -> Decimal {
Decimal(std::ops::$trait::$method(&self.0, &other.0))
}
}
)*};
}
exact_ops!(Add add, Sub sub, Mul mul);
impl std::ops::Div for Decimal {
type Output = Decimal;
fn div(self, other: Decimal) -> Decimal {
&self / &other
}
}
impl std::ops::Div<&Decimal> for &Decimal {
type Output = Decimal;
fn div(self, other: &Decimal) -> Decimal {
Decimal(ruby_div(&self.0, &other.0))
}
}
impl std::iter::Sum for Decimal {
fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
iter.fold(Decimal::default(), |total, d| total + d)
}
}
impl<'a> std::iter::Sum<&'a Decimal> for Decimal {
fn sum<I: Iterator<Item = &'a Decimal>>(iter: I) -> Decimal {
iter.fold(Decimal::default(), |total, d| &total + d)
}
}
impl Serialize for Decimal {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
fn normalized(value: &BigDecimal) -> (BigInt, i64) {
if value.is_zero() {
return (BigInt::zero(), 0);
}
let (mut digits, mut scale) = value.as_bigint_and_exponent();
let ten = BigInt::from(10);
while (&digits % &ten).is_zero() {
digits /= &ten;
scale -= 1;
}
(digits, scale)
}
#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
fn rails_form(value: &BigDecimal) -> BigDecimal {
let (digits, scale) = normalized(value);
if scale >= 1 {
BigDecimal::new(digits, scale)
} else {
BigDecimal::new(digits * pow10(1 - scale), 1)
}
}
fn digit_count(n: &BigInt) -> i64 {
i64::try_from(n.magnitude().to_string().len()).unwrap_or(i64::MAX)
}
fn pow10(exponent: i64) -> BigInt {
BigInt::from(10).pow(u32::try_from(exponent).expect("a power of ten"))
}
fn precision(value: &BigDecimal) -> i64 {
let (digits, scale) = normalized(value);
if digits.is_zero() {
return 0;
}
let digits = BigInt::from(digits.magnitude().clone());
let ex = word_exponent(&digits, scale);
let k = (-scale).div_euclid(9);
let n = ex - k;
let first = leading_word(&digits, scale);
let last = (&digits * pow10(-scale - 9 * k) % BigInt::from(1_000_000_000))
.to_u64()
.unwrap_or(0);
let nlz = 9 - i64::try_from(first.to_string().len()).unwrap_or(9);
let mut ntz = 0;
let mut x = last;
while x > 0 && x.is_multiple_of(10) {
ntz += 1;
x /= 10;
}
let mut head = 9;
let mut ex = ex;
if ex < 0 {
head += -ex * 9;
ex = 0;
} else if ex > 0 {
head -= nlz;
}
if ex > n {
head + (ex - 1) * 9
} else {
head + (n - 1) * 9 - if ex < n { ntz } else { 0 }
}
}
fn word_exponent(digits: &BigInt, scale: i64) -> i64 {
(digit_count(digits) - scale + 8).div_euclid(9)
}
fn leading_word(digits: &BigInt, scale: i64) -> u64 {
let magnitude = BigInt::from(digits.magnitude().clone());
let shift = -scale - 9 * (word_exponent(digits, scale) - 1);
let word = if shift >= 0 {
magnitude * pow10(shift)
} else {
magnitude / pow10(-shift)
};
word.to_u64().unwrap_or(0)
}
fn ruby_div(a: &BigDecimal, b: &BigDecimal) -> BigDecimal {
assert!(!b.is_zero(), "division by zero");
if a.is_zero() {
return BigDecimal::zero();
}
if b.is_one() {
return a.clone();
}
let (na, sa) = normalized(a);
let (nb, sb) = normalized(b);
let negative = (na.sign() == Sign::Minus) != (nb.sign() == Sign::Minus);
let na = BigInt::from(na.magnitude().clone());
let nb = BigInt::from(nb.magnitude().clone());
let mx = (precision(a).max(precision(b)) * 2).max(32);
let word_c = (mx + 18 + 8) / 9;
let lowest = word_exponent(&na, sa) - word_exponent(&nb, sb) + 2 - word_c;
let t = sb - sa - 9 * lowest;
let (numerator, denominator) = if t >= 0 {
(&na * pow10(t), nb.clone())
} else {
(na.clone(), &nb * pow10(-t))
};
let mut q = &numerator / &denominator;
let remainder = &numerator - &q * &denominator;
if !remainder.is_zero() {
let r_scale = sa + t.max(0);
let r0 = leading_word(&remainder, r_scale);
let b0 = leading_word(&nb, sb);
#[allow(clippy::cast_possible_truncation)]
let v = ((1_000_000_000u64 * r0) / b0.max(1)) as u32;
if v != 0 && v / 100_000_000 >= 5 {
q += 1;
}
}
if negative {
q = -q;
}
BigDecimal::new(q, -9 * lowest)
}
#[cfg(feature = "postgres")]
mod postgres {
use bigdecimal::BigDecimal;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres};
use sqlx::{Decode, Encode, Type};
use super::Decimal;
impl Type<Postgres> for Decimal {
fn type_info() -> PgTypeInfo {
<BigDecimal as Type<Postgres>>::type_info()
}
}
impl<'r> Decode<'r, Postgres> for Decimal {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
<BigDecimal as Decode<Postgres>>::decode(value).map(Decimal)
}
}
impl Encode<'_, Postgres> for Decimal {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
<BigDecimal as Encode<Postgres>>::encode_by_ref(&super::rails_form(&self.0), buf)
}
}
}
#[cfg(feature = "sqlite")]
mod sqlite {
use std::str::FromStr;
use bigdecimal::BigDecimal;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::sqlite::{Sqlite, SqliteArgumentsBuffer, SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Type};
use super::Decimal;
impl Type<Sqlite> for Decimal {
fn type_info() -> SqliteTypeInfo {
<f64 as Type<Sqlite>>::type_info()
}
fn compatible(_: &SqliteTypeInfo) -> bool {
true
}
}
impl<'r> Decode<'r, Sqlite> for Decimal {
fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
let float = <f64 as Decode<Sqlite>>::decode(value)?;
BigDecimal::from_str(&float.to_string())
.map(Decimal)
.map_err(|_| format!("{float} is not a decimal").into())
}
}
impl Encode<'_, Sqlite> for Decimal {
fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result<IsNull, BoxDynError> {
<f64 as Encode<Sqlite>>::encode_by_ref(&self.to_f64(), buf)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn d(text: &str) -> Decimal {
Decimal::from_str(text).unwrap()
}
#[test]
fn writes_as_rails_does() {
let s = |text: &str| d(text).to_string();
assert_eq!(s("50"), "50.0");
assert_eq!(s("50.00"), "50.0");
assert_eq!(s("50.250"), "50.25");
assert_eq!(s("-0.5"), "-0.5");
assert_eq!(s("1e20"), "100000000000000000000.0");
assert_eq!(s("0.000123"), "0.000123");
assert_eq!(
serde_json::to_string(&Decimal::from(3)).unwrap(),
r#""3.0""#
);
}
#[test]
fn divides_as_ruby_does() {
let cases = [
("1", "3", "0.333333333333333333333333333333333333"),
("2", "3", "0.666666666666666666666666666666666667"),
("200", "3", "66.666666666666666666666666666666666667"),
(
"12345.6789",
"7",
"1763.668414285714285714285714285714285714",
),
(
"1.23456789012345678901234567890",
"3",
"0.4115226300411522630041152263",
),
("100", "8", "12.5"),
("1", "7", "0.142857142857142857142857142857142857"),
(
"0.001",
"3",
"0.000333333333333333333333333333333333333333333",
),
("9", "7", "1.285714285714285714285714285714285714"),
("1", "300", "0.003333333333333333333333333333333333"),
("50.5", "3", "16.833333333333333333333333333333333333"),
("-2", "3", "-0.666666666666666666666666666666666667"),
("7", "1", "7.0"),
(
"0.00000000000264238891865",
"3",
"0.000000000000880796306216666666666666666666666666666666666666666666666667",
),
(
"-0.000004",
"0.0000000000570914868260565052558237894069",
"-70062.985260604624091141219373855968543852591860891222131187381483034565983886",
),
];
for (a, b, expected) in cases {
assert_eq!((d(a) / d(b)).to_string(), expected, "{a} / {b}");
}
}
}