1use std::fmt;
5use std::str::FromStr;
6
7use bigdecimal::num_bigint::{BigInt, Sign};
8use bigdecimal::{BigDecimal, One, ToPrimitive, Zero};
9use serde::{Serialize, Serializer};
10
11#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20pub struct Decimal(pub BigDecimal);
21
22impl Decimal {
23 pub fn new(value: BigDecimal) -> Self {
24 Self(value)
25 }
26
27 pub fn to_f64(&self) -> f64 {
28 self.0.to_f64().unwrap_or(0.0)
29 }
30
31 pub fn is_zero(&self) -> bool {
32 self.0.is_zero()
33 }
34}
35
36impl fmt::Display for Decimal {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 let (digits, scale) = normalized(&self.0);
42 let negative = digits.sign() == Sign::Minus;
43 let text = digits.magnitude().to_string();
44 let (int, frac) = if scale <= 0 {
45 let zeros = "0".repeat(usize::try_from(-scale).unwrap_or(0));
46 (format!("{text}{zeros}"), String::from("0"))
47 } else {
48 let scale = usize::try_from(scale).unwrap_or(0);
49 let padded = format!("{text:0>width$}", width = scale + 1);
50 let (int, frac) = padded.split_at(padded.len() - scale);
51 (int.to_owned(), frac.to_owned())
52 };
53 let sign = if negative { "-" } else { "" };
54 write!(f, "{sign}{int}.{frac}")
55 }
56}
57
58impl FromStr for Decimal {
59 type Err = bigdecimal::ParseBigDecimalError;
60
61 fn from_str(text: &str) -> Result<Self, Self::Err> {
62 BigDecimal::from_str(text.trim()).map(Decimal)
63 }
64}
65
66impl From<BigDecimal> for Decimal {
67 fn from(value: BigDecimal) -> Self {
68 Decimal(value)
69 }
70}
71
72impl From<i64> for Decimal {
73 fn from(value: i64) -> Self {
74 Decimal(value.into())
75 }
76}
77
78impl From<i32> for Decimal {
79 fn from(value: i32) -> Self {
80 Decimal(value.into())
81 }
82}
83
84macro_rules! exact_ops {
85 ($($trait:ident $method:ident),*) => {$(
86 impl std::ops::$trait for Decimal {
87 type Output = Decimal;
88
89 fn $method(self, other: Decimal) -> Decimal {
90 Decimal(std::ops::$trait::$method(self.0, other.0))
91 }
92 }
93
94 impl std::ops::$trait<&Decimal> for &Decimal {
95 type Output = Decimal;
96
97 fn $method(self, other: &Decimal) -> Decimal {
98 Decimal(std::ops::$trait::$method(&self.0, &other.0))
99 }
100 }
101 )*};
102}
103
104exact_ops!(Add add, Sub sub, Mul mul);
105
106impl std::ops::Div for Decimal {
117 type Output = Decimal;
118
119 fn div(self, other: Decimal) -> Decimal {
120 &self / &other
121 }
122}
123
124impl std::ops::Div<&Decimal> for &Decimal {
125 type Output = Decimal;
126
127 fn div(self, other: &Decimal) -> Decimal {
128 Decimal(ruby_div(&self.0, &other.0))
129 }
130}
131
132impl std::iter::Sum for Decimal {
133 fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
134 iter.fold(Decimal::default(), |total, d| total + d)
135 }
136}
137
138impl<'a> std::iter::Sum<&'a Decimal> for Decimal {
139 fn sum<I: Iterator<Item = &'a Decimal>>(iter: I) -> Decimal {
140 iter.fold(Decimal::default(), |total, d| &total + d)
141 }
142}
143
144impl Serialize for Decimal {
145 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
146 s.collect_str(self)
147 }
148}
149
150fn normalized(value: &BigDecimal) -> (BigInt, i64) {
152 if value.is_zero() {
153 return (BigInt::zero(), 0);
154 }
155 let (mut digits, mut scale) = value.as_bigint_and_exponent();
156 let ten = BigInt::from(10);
157 while (&digits % &ten).is_zero() {
158 digits /= &ten;
159 scale -= 1;
160 }
161 (digits, scale)
162}
163
164#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
166fn rails_form(value: &BigDecimal) -> BigDecimal {
167 let (digits, scale) = normalized(value);
168 if scale >= 1 {
169 BigDecimal::new(digits, scale)
170 } else {
171 BigDecimal::new(digits * pow10(1 - scale), 1)
172 }
173}
174
175fn digit_count(n: &BigInt) -> i64 {
176 i64::try_from(n.magnitude().to_string().len()).unwrap_or(i64::MAX)
177}
178
179fn pow10(exponent: i64) -> BigInt {
180 BigInt::from(10).pow(u32::try_from(exponent).expect("a power of ten"))
181}
182
183fn precision(value: &BigDecimal) -> i64 {
188 let (digits, scale) = normalized(value);
189 if digits.is_zero() {
190 return 0;
191 }
192 let digits = BigInt::from(digits.magnitude().clone());
193 let ex = word_exponent(&digits, scale);
194 let k = (-scale).div_euclid(9);
196 let n = ex - k;
197 let first = leading_word(&digits, scale);
198 let last = (&digits * pow10(-scale - 9 * k) % BigInt::from(1_000_000_000))
199 .to_u64()
200 .unwrap_or(0);
201 let nlz = 9 - i64::try_from(first.to_string().len()).unwrap_or(9);
202 let mut ntz = 0;
203 let mut x = last;
204 while x > 0 && x.is_multiple_of(10) {
205 ntz += 1;
206 x /= 10;
207 }
208 let mut head = 9;
209 let mut ex = ex;
210 if ex < 0 {
211 head += -ex * 9;
212 ex = 0;
213 } else if ex > 0 {
214 head -= nlz;
215 }
216 if ex > n {
217 head + (ex - 1) * 9
218 } else {
219 head + (n - 1) * 9 - if ex < n { ntz } else { 0 }
220 }
221}
222
223fn word_exponent(digits: &BigInt, scale: i64) -> i64 {
225 (digit_count(digits) - scale + 8).div_euclid(9)
226}
227
228fn leading_word(digits: &BigInt, scale: i64) -> u64 {
230 let magnitude = BigInt::from(digits.magnitude().clone());
231 let shift = -scale - 9 * (word_exponent(digits, scale) - 1);
233 let word = if shift >= 0 {
234 magnitude * pow10(shift)
235 } else {
236 magnitude / pow10(-shift)
237 };
238 word.to_u64().unwrap_or(0)
239}
240
241fn ruby_div(a: &BigDecimal, b: &BigDecimal) -> BigDecimal {
242 assert!(!b.is_zero(), "division by zero");
243 if a.is_zero() {
244 return BigDecimal::zero();
245 }
246 if b.is_one() {
247 return a.clone();
248 }
249 let (na, sa) = normalized(a);
250 let (nb, sb) = normalized(b);
251 let negative = (na.sign() == Sign::Minus) != (nb.sign() == Sign::Minus);
252 let na = BigInt::from(na.magnitude().clone());
253 let nb = BigInt::from(nb.magnitude().clone());
254
255 let mx = (precision(a).max(precision(b)) * 2).max(32);
257 let word_c = (mx + 18 + 8) / 9;
258 let lowest = word_exponent(&na, sa) - word_exponent(&nb, sb) + 2 - word_c;
260
261 let t = sb - sa - 9 * lowest;
263 let (numerator, denominator) = if t >= 0 {
264 (&na * pow10(t), nb.clone())
265 } else {
266 (na.clone(), &nb * pow10(-t))
267 };
268 let mut q = &numerator / &denominator;
269 let remainder = &numerator - &q * &denominator;
270
271 if !remainder.is_zero() {
274 let r_scale = sa + t.max(0);
276 let r0 = leading_word(&remainder, r_scale);
277 let b0 = leading_word(&nb, sb);
278 #[allow(clippy::cast_possible_truncation)]
279 let v = ((1_000_000_000u64 * r0) / b0.max(1)) as u32;
280 if v != 0 && v / 100_000_000 >= 5 {
281 q += 1;
282 }
283 }
284 if negative {
285 q = -q;
286 }
287 BigDecimal::new(q, -9 * lowest)
288}
289
290#[cfg(feature = "postgres")]
291mod postgres {
292 use bigdecimal::BigDecimal;
293 use sqlx::encode::IsNull;
294 use sqlx::error::BoxDynError;
295 use sqlx::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres};
296 use sqlx::{Decode, Encode, Type};
297
298 use super::Decimal;
299
300 impl Type<Postgres> for Decimal {
301 fn type_info() -> PgTypeInfo {
302 <BigDecimal as Type<Postgres>>::type_info()
303 }
304 }
305
306 impl<'r> Decode<'r, Postgres> for Decimal {
307 fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
308 <BigDecimal as Decode<Postgres>>::decode(value).map(Decimal)
309 }
310 }
311
312 impl Encode<'_, Postgres> for Decimal {
315 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
316 <BigDecimal as Encode<Postgres>>::encode_by_ref(&super::rails_form(&self.0), buf)
317 }
318 }
319}
320
321#[cfg(feature = "sqlite")]
322mod sqlite {
323 use std::str::FromStr;
324
325 use bigdecimal::BigDecimal;
326 use sqlx::encode::IsNull;
327 use sqlx::error::BoxDynError;
328 use sqlx::sqlite::{Sqlite, SqliteArgumentsBuffer, SqliteTypeInfo, SqliteValueRef};
329 use sqlx::{Decode, Encode, Type};
330
331 use super::Decimal;
332
333 impl Type<Sqlite> for Decimal {
334 fn type_info() -> SqliteTypeInfo {
335 <f64 as Type<Sqlite>>::type_info()
336 }
337
338 fn compatible(_: &SqliteTypeInfo) -> bool {
340 true
341 }
342 }
343
344 impl<'r> Decode<'r, Sqlite> for Decimal {
345 fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
346 let float = <f64 as Decode<Sqlite>>::decode(value)?;
347 BigDecimal::from_str(&float.to_string())
349 .map(Decimal)
350 .map_err(|_| format!("{float} is not a decimal").into())
351 }
352 }
353
354 impl Encode<'_, Sqlite> for Decimal {
355 fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result<IsNull, BoxDynError> {
356 <f64 as Encode<Sqlite>>::encode_by_ref(&self.to_f64(), buf)
357 }
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 fn d(text: &str) -> Decimal {
366 Decimal::from_str(text).unwrap()
367 }
368
369 #[test]
370 fn writes_as_rails_does() {
371 let s = |text: &str| d(text).to_string();
372 assert_eq!(s("50"), "50.0");
373 assert_eq!(s("50.00"), "50.0");
374 assert_eq!(s("50.250"), "50.25");
375 assert_eq!(s("-0.5"), "-0.5");
376 assert_eq!(s("1e20"), "100000000000000000000.0");
377 assert_eq!(s("0.000123"), "0.000123");
378 assert_eq!(
379 serde_json::to_string(&Decimal::from(3)).unwrap(),
380 r#""3.0""#
381 );
382 }
383
384 #[test]
385 fn divides_as_ruby_does() {
386 let cases = [
388 ("1", "3", "0.333333333333333333333333333333333333"),
389 ("2", "3", "0.666666666666666666666666666666666667"),
390 ("200", "3", "66.666666666666666666666666666666666667"),
391 (
392 "12345.6789",
393 "7",
394 "1763.668414285714285714285714285714285714",
395 ),
396 (
397 "1.23456789012345678901234567890",
398 "3",
399 "0.4115226300411522630041152263",
400 ),
401 ("100", "8", "12.5"),
402 ("1", "7", "0.142857142857142857142857142857142857"),
403 (
404 "0.001",
405 "3",
406 "0.000333333333333333333333333333333333333333333",
407 ),
408 ("9", "7", "1.285714285714285714285714285714285714"),
409 ("1", "300", "0.003333333333333333333333333333333333"),
410 ("50.5", "3", "16.833333333333333333333333333333333333"),
411 ("-2", "3", "-0.666666666666666666666666666666666667"),
412 ("7", "1", "7.0"),
413 (
415 "0.00000000000264238891865",
416 "3",
417 "0.000000000000880796306216666666666666666666666666666666666666666666666667",
418 ),
419 (
420 "-0.000004",
421 "0.0000000000570914868260565052558237894069",
422 "-70062.985260604624091141219373855968543852591860891222131187381483034565983886",
423 ),
424 ];
425 for (a, b, expected) in cases {
426 assert_eq!((d(a) / d(b)).to_string(), expected, "{a} / {b}");
427 }
428 }
429}