1use std::cmp::Ordering;
24use std::fmt;
25
26pub const MAX_DIGITS: u16 = 38;
29
30#[derive(Debug, Clone, Copy)]
38pub struct Decimal {
39 unscaled: i128,
40 scale: u16,
41}
42
43#[derive(Debug, Clone, Copy)]
45enum Round {
46 Half,
49 Up,
51 Down,
53}
54
55impl Decimal {
56 pub fn new(unscaled: i128, scale: u16) -> Decimal {
62 Decimal { unscaled, scale }
63 }
64
65 pub fn unscaled(&self) -> i128 {
67 self.unscaled
68 }
69
70 pub fn scale(&self) -> u16 {
72 self.scale
73 }
74
75 pub fn is_zero(&self) -> bool {
78 self.unscaled == 0
79 }
80
81 pub fn digits(&self) -> u16 {
85 let mut left = self.unscaled.unsigned_abs();
86 let mut digits = 1;
87 while left >= 10 {
88 left /= 10;
89 digits += 1;
90 }
91 digits
92 }
93
94 pub fn rescale(&self, scale: u16) -> Option<Decimal> {
103 match scale.cmp(&self.scale) {
104 Ordering::Equal => Some(*self),
105 Ordering::Greater => {
106 let by = 10i128.checked_pow(u32::from(scale - self.scale))?;
107 Some(Decimal {
108 unscaled: self.unscaled.checked_mul(by)?,
109 scale,
110 })
111 }
112 Ordering::Less => {
113 let by = 10i128.checked_pow(u32::from(self.scale - scale))?;
114 match self.unscaled % by {
115 0 => Some(Decimal {
116 unscaled: self.unscaled / by,
117 scale,
118 }),
119 _ => None,
120 }
121 }
122 }
123 }
124
125 pub fn abs(&self) -> Option<Decimal> {
129 Some(Decimal {
130 unscaled: self.unscaled.checked_abs()?,
131 scale: self.scale,
132 })
133 }
134
135 pub fn signum(&self) -> i64 {
137 self.unscaled.signum() as i64
138 }
139
140 pub fn round(&self, digits: i64) -> Option<Decimal> {
149 self.quantize(digits, Round::Half)
150 }
151
152 pub fn ceil(&self, digits: i64) -> Option<Decimal> {
155 self.quantize(digits, Round::Up)
156 }
157
158 pub fn floor(&self, digits: i64) -> Option<Decimal> {
161 self.quantize(digits, Round::Down)
162 }
163
164 fn quantize(&self, digits: i64, mode: Round) -> Option<Decimal> {
169 let scale = u16::try_from(digits.max(0)).ok()?.min(MAX_DIGITS);
170 let drop = i64::from(self.scale) - digits;
171 if drop <= 0 {
172 return self.rescale(scale);
173 }
174 let by = 10i128.checked_pow(u32::try_from(drop).ok()?)?;
175 let (whole, rest) = (self.unscaled / by, self.unscaled % by);
176 let carried = match mode {
177 Round::Half if rest.checked_mul(2)?.abs() >= by => match self.unscaled.is_negative() {
178 true => whole.checked_sub(1)?,
179 false => whole.checked_add(1)?,
180 },
181 Round::Up if rest > 0 => whole.checked_add(1)?,
182 Round::Down if rest < 0 => whole.checked_sub(1)?,
183 _ => whole,
184 };
185 let back = 10i128.checked_pow(u32::try_from(i64::from(scale) - digits).ok()?)?;
188 Some(Decimal {
189 unscaled: carried.checked_mul(back)?,
190 scale,
191 })
192 }
193
194 pub fn truncate(&self) -> Option<i128> {
201 let by = 10i128.checked_pow(u32::from(self.scale))?;
202 Some(self.unscaled / by)
203 }
204
205 pub fn to_f64(&self) -> f64 {
215 self.unscaled as f64 / 10f64.powi(i32::from(self.scale))
216 }
217
218 pub fn parse(text: &str, scale: u16) -> Option<Decimal> {
229 let text = text.trim();
230 let (negative, rest) = match text.strip_prefix('-') {
231 Some(rest) => (true, rest),
232 None => (false, text.strip_prefix('+').unwrap_or(text)),
233 };
234 let (mantissa, exponent) = match rest.split_once(['e', 'E']) {
235 Some((m, e)) => (m, e.parse::<i32>().ok()?),
236 None => (rest, 0),
237 };
238 let (whole, fraction) = match mantissa.split_once('.') {
239 Some((w, f)) => (w, f),
240 None => (mantissa, ""),
241 };
242 if whole.is_empty() && fraction.is_empty() {
243 return None;
244 }
245 if !whole
246 .bytes()
247 .chain(fraction.bytes())
248 .all(|b| b.is_ascii_digit())
249 {
250 return None;
251 }
252 let mut digits: i128 = 0;
256 for byte in whole.bytes().chain(fraction.bytes()) {
257 digits = digits
258 .checked_mul(10)?
259 .checked_add(i128::from(byte - b'0'))?;
260 }
261 let written = i64::try_from(fraction.len())
262 .ok()?
263 .checked_sub(i64::from(exponent))?;
264 let unscaled = shift(digits, written, i64::from(scale))?;
265 Some(Decimal {
266 unscaled: match negative {
267 true => -unscaled,
268 false => unscaled,
269 },
270 scale,
271 })
272 }
273
274 pub fn add(&self, other: &Decimal) -> Option<Decimal> {
281 let (a, b) = align(self, other)?;
282 Some(Decimal {
283 unscaled: a.unscaled.checked_add(b.unscaled)?,
284 scale: a.scale,
285 })
286 }
287
288 pub fn sub(&self, other: &Decimal) -> Option<Decimal> {
290 let (a, b) = align(self, other)?;
291 Some(Decimal {
292 unscaled: a.unscaled.checked_sub(b.unscaled)?,
293 scale: a.scale,
294 })
295 }
296
297 pub fn mul(&self, other: &Decimal) -> Option<Decimal> {
300 let scale = self.scale.checked_add(other.scale)?;
301 if scale > MAX_DIGITS {
302 return None;
303 }
304 Some(Decimal {
305 unscaled: self.unscaled.checked_mul(other.unscaled)?,
306 scale,
307 })
308 }
309
310 pub fn div(&self, other: &Decimal) -> Option<Decimal> {
321 if other.unscaled == 0 {
322 return None;
323 }
324 let scale = self
325 .scale
326 .max(other.scale)
327 .saturating_add(6)
328 .min(MAX_DIGITS);
329 let up = i64::from(scale) + i64::from(other.scale) - i64::from(self.scale);
333 let numerator = shift(i128::try_from(self.unscaled.unsigned_abs()).ok()?, 0, up)?;
334 let divisor = i128::try_from(other.unscaled.unsigned_abs()).ok()?;
335 let quotient = numerator / divisor;
336 let unscaled = match (numerator % divisor).checked_mul(2) {
339 Some(twice) if twice >= divisor => quotient.checked_add(1)?,
340 _ => quotient,
341 };
342 Some(Decimal {
343 unscaled: match self.unscaled.is_negative() != other.unscaled.is_negative() {
344 true => -unscaled,
345 false => unscaled,
346 },
347 scale,
348 })
349 }
350
351 pub fn rem(&self, other: &Decimal) -> Option<Decimal> {
355 let (a, b) = align(self, other)?;
356 if b.unscaled == 0 {
357 return None;
358 }
359 Some(Decimal {
360 unscaled: a.unscaled.checked_rem(b.unscaled)?,
361 scale: a.scale,
362 })
363 }
364
365 pub fn negate(&self) -> Option<Decimal> {
367 Some(Decimal {
368 unscaled: self.unscaled.checked_neg()?,
369 scale: self.scale,
370 })
371 }
372}
373
374fn shift<T>(digits: T, from: i64, to: i64) -> Option<i128>
377where
378 i128: TryFrom<T>,
379{
380 let digits = i128::try_from(digits).ok()?;
381 match to.checked_sub(from)? {
382 0 => Some(digits),
383 by if by > 0 => digits.checked_mul(10i128.checked_pow(u32::try_from(by).ok()?)?),
384 by => {
385 let down = 10i128.checked_pow(u32::try_from(-by).ok()?)?;
386 let whole = digits / down;
387 match (digits % down).checked_mul(2) {
388 Some(twice) if twice.abs() >= down => match digits.is_negative() {
389 true => whole.checked_sub(1),
390 false => whole.checked_add(1),
391 },
392 _ => Some(whole),
393 }
394 }
395 }
396}
397
398fn align(a: &Decimal, b: &Decimal) -> Option<(Decimal, Decimal)> {
401 let scale = a.scale.max(b.scale);
402 Some((a.rescale(scale)?, b.rescale(scale)?))
403}
404
405impl PartialEq for Decimal {
413 fn eq(&self, other: &Decimal) -> bool {
414 self.cmp(other) == Ordering::Equal
415 }
416}
417
418impl Eq for Decimal {}
419
420impl Ord for Decimal {
427 fn cmp(&self, other: &Decimal) -> Ordering {
428 if let Some((a, b)) = align(self, other) {
429 return a.unscaled.cmp(&b.unscaled);
430 }
431 let sign = self.unscaled.signum().cmp(&other.unscaled.signum());
432 if sign != Ordering::Equal {
433 return sign;
434 }
435 let whole = |d: &Decimal| i32::from(d.digits()) - i32::from(d.scale);
436 let by_size = whole(self).cmp(&whole(other));
437 match self.unscaled.is_negative() {
438 true => by_size.reverse(),
439 false => by_size,
440 }
441 }
442}
443
444impl PartialOrd for Decimal {
445 fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
446 Some(self.cmp(other))
447 }
448}
449
450impl std::hash::Hash for Decimal {
451 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
458 let (mut unscaled, mut scale) = (self.unscaled, i64::from(self.scale));
459 while unscaled != 0 && unscaled % 10 == 0 {
460 unscaled /= 10;
461 scale -= 1;
462 }
463 unscaled.hash(state);
464 match unscaled {
465 0 => 0i64.hash(state),
466 _ => scale.hash(state),
467 }
468 }
469}
470
471impl fmt::Display for Decimal {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 if self.scale == 0 {
476 return write!(f, "{}", self.unscaled);
477 }
478 let digits = self.unscaled.unsigned_abs().to_string();
479 let places = usize::from(self.scale);
480 let sign = match self.unscaled.is_negative() {
481 true => "-",
482 false => "",
483 };
484 if digits.len() <= places {
488 let pad = "0".repeat(places - digits.len());
489 return write!(f, "{sign}0.{pad}{digits}");
490 }
491 let (whole, fraction) = digits.split_at(digits.len() - places);
492 write!(f, "{sign}{whole}.{fraction}")
493 }
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499
500 #[test]
501 fn a_decimal_prints_at_the_scale_it_was_written_with() {
502 assert_eq!(Decimal::new(120, 2).to_string(), "1.20");
503 assert_eq!(Decimal::new(12, 1).to_string(), "1.2");
504 assert_eq!(Decimal::new(12, 0).to_string(), "12");
505 assert_eq!(Decimal::new(-120, 2).to_string(), "-1.20");
506 assert_eq!(Decimal::new(5, 3).to_string(), "0.005");
509 assert_eq!(Decimal::new(-5, 3).to_string(), "-0.005");
510 assert_eq!(Decimal::new(0, 2).to_string(), "0.00");
511 }
512
513 #[test]
514 fn two_spellings_of_one_number_are_one_value() {
515 let (loose, tight) = (Decimal::new(12, 1), Decimal::new(120, 2));
516 assert_eq!(loose, tight);
517 assert_eq!(loose.cmp(&tight), Ordering::Equal);
518 let hash = |d: &Decimal| {
520 use std::hash::{Hash, Hasher};
521 let mut h = std::collections::hash_map::DefaultHasher::new();
522 d.hash(&mut h);
523 h.finish()
524 };
525 assert_eq!(hash(&loose), hash(&tight));
526 assert_eq!(hash(&Decimal::new(0, 0)), hash(&Decimal::new(0, 7)));
527 assert_ne!(loose.to_string(), tight.to_string());
530 }
531
532 #[test]
533 fn a_tenth_and_two_tenths_are_three_tenths() {
534 let (a, b) = (
535 Decimal::parse("0.1", 1).unwrap(),
536 Decimal::parse("0.2", 1).unwrap(),
537 );
538 assert_eq!(a.add(&b).unwrap().to_string(), "0.3");
539 assert_ne!(a.to_f64() + b.to_f64(), 0.3f64);
543 }
544
545 #[test]
546 fn arithmetic_answers_at_the_scale_the_units_give() {
547 let (a, b) = (Decimal::new(150, 2), Decimal::new(3, 1));
548 assert_eq!(a.add(&b).unwrap().to_string(), "1.80");
550 assert_eq!(a.sub(&b).unwrap().to_string(), "1.20");
551 assert_eq!(a.mul(&b).unwrap().to_string(), "0.450");
553 assert_eq!(a.rem(&b).unwrap().to_string(), "0.00");
554 assert_eq!(a.negate().unwrap().to_string(), "-1.50");
555 }
556
557 #[test]
558 fn a_quotient_is_carried_as_far_as_the_operands_knew() {
559 let third = Decimal::new(1, 0).div(&Decimal::new(3, 0)).unwrap();
560 assert_eq!(third.to_string(), "0.333333");
561 assert_eq!(
563 Decimal::new(2, 0)
564 .div(&Decimal::new(3, 0))
565 .unwrap()
566 .to_string(),
567 "0.666667"
568 );
569 assert_eq!(
570 Decimal::new(-2, 0)
571 .div(&Decimal::new(3, 0))
572 .unwrap()
573 .to_string(),
574 "-0.666667"
575 );
576 let each = Decimal::new(1000, 2).div(&Decimal::new(4, 0)).unwrap();
578 assert_eq!(each.rescale(2).unwrap().to_string(), "2.50");
579 assert_eq!(Decimal::new(1, 0).div(&Decimal::new(0, 0)), None);
580 }
581
582 #[test]
583 fn text_is_read_at_the_scale_it_is_wanted_at() {
584 assert_eq!(Decimal::parse("1.20", 2).unwrap(), Decimal::new(120, 2));
585 assert_eq!(
586 Decimal::parse(" -3.5 ", 3).unwrap(),
587 Decimal::new(-3500, 3)
588 );
589 assert_eq!(Decimal::parse("12", 2).unwrap(), Decimal::new(1200, 2));
590 assert_eq!(Decimal::parse(".5", 1).unwrap(), Decimal::new(5, 1));
591 assert_eq!(Decimal::parse("5.", 1).unwrap(), Decimal::new(50, 1));
592 assert_eq!(Decimal::parse("1E3", 0).unwrap(), Decimal::new(1000, 0));
594 assert_eq!(Decimal::parse("15e-2", 2).unwrap(), Decimal::new(15, 2));
595 assert_eq!(Decimal::parse("1.005", 2).unwrap(), Decimal::new(101, 2));
597 assert_eq!(Decimal::parse("-1.005", 2).unwrap(), Decimal::new(-101, 2));
598 assert_eq!(Decimal::parse("1.004", 2).unwrap(), Decimal::new(100, 2));
599 for not_a_number in ["", ".", "x", "1.2.3", "1,000", "1e", "0x10"] {
600 assert_eq!(Decimal::parse(not_a_number, 2), None, "{not_a_number}");
601 }
602 }
603
604 #[test]
605 fn a_rescale_that_would_not_be_exact_is_refused() {
606 let value = Decimal::new(125, 2);
607 assert_eq!(value.rescale(4).unwrap(), Decimal::new(12500, 4));
608 assert_eq!(value.rescale(2).unwrap(), value);
609 assert_eq!(value.rescale(1), None);
611 assert_eq!(
612 Decimal::new(120, 2).rescale(1).unwrap(),
613 Decimal::new(12, 1)
614 );
615 }
616
617 #[test]
618 fn rounding_stops_at_the_place_it_was_asked_for() {
619 let value = Decimal::parse("1.005", 3).unwrap();
620 assert_eq!(value.round(2).unwrap().to_string(), "1.01");
624 assert_eq!(value.round(0).unwrap().to_string(), "1");
625 assert_eq!(value.round(5).unwrap().to_string(), "1.00500");
626 }
627
628 #[test]
629 fn halves_go_away_from_nought_on_both_sides_of_it() {
630 assert_eq!(Decimal::new(25, 1).round(0).unwrap().to_string(), "3");
631 assert_eq!(Decimal::new(-25, 1).round(0).unwrap().to_string(), "-3");
632 assert_eq!(Decimal::new(35, 1).round(0).unwrap().to_string(), "4");
633 }
634
635 #[test]
636 fn a_negative_digit_count_rounds_to_the_left_of_the_point() {
637 assert_eq!(Decimal::new(1505, 1).round(-1).unwrap().to_string(), "150");
640 assert_eq!(Decimal::new(150, 0).round(-2).unwrap().to_string(), "200");
642 assert_eq!(Decimal::new(-150, 0).round(-2).unwrap().to_string(), "-200");
643 assert_eq!(Decimal::new(149, 0).round(-2).unwrap().to_string(), "100");
644 }
645
646 #[test]
647 fn a_ceiling_and_a_floor_lean_the_same_way_for_both_signs() {
648 let up = Decimal::new(15, 1);
649 let down = Decimal::new(-15, 1);
650 assert_eq!(up.ceil(0).unwrap().to_string(), "2");
651 assert_eq!(up.floor(0).unwrap().to_string(), "1");
652 assert_eq!(down.ceil(0).unwrap().to_string(), "-1");
655 assert_eq!(down.floor(0).unwrap().to_string(), "-2");
656 assert_eq!(Decimal::new(2, 0).ceil(0).unwrap().to_string(), "2");
658 }
659
660 #[test]
661 fn the_digit_count_is_of_the_number_and_not_of_the_declaration() {
662 assert_eq!(Decimal::new(0, 4).digits(), 1);
663 assert_eq!(Decimal::new(9, 0).digits(), 1);
664 assert_eq!(Decimal::new(10, 0).digits(), 2);
665 assert_eq!(Decimal::new(-999, 2).digits(), 3);
666 assert_eq!(Decimal::new(i128::MAX, 0).digits(), 39);
667 }
668
669 #[test]
670 fn ordering_holds_where_the_scales_cannot_be_aligned() {
671 let huge = Decimal::new(i128::MAX, 0);
674 let small = Decimal::new(1, MAX_DIGITS);
675 assert_eq!(huge.cmp(&small), Ordering::Greater);
676 assert_eq!(small.cmp(&huge), Ordering::Less);
677 assert_eq!(
678 huge.negate().unwrap().cmp(&small.negate().unwrap()),
679 Ordering::Less
680 );
681 assert_eq!(Decimal::new(0, 0).cmp(&small), Ordering::Less);
682 }
683}