1use std::cmp::Ordering;
5use std::fmt;
6
7use num_bigint::BigInt;
8use num_integer::Integer;
9use num_traits::{One, Pow, Signed, ToPrimitive, Zero};
10
11use crate::error::Fault;
12use crate::int::Int;
13
14pub const DIVISION_DIGITS: u32 = 34;
16
17#[derive(Clone, PartialEq, Eq, Hash)]
33pub struct Decimal {
34 coefficient: BigInt,
35 exponent: i64,
36}
37
38impl Decimal {
39 pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
49 if coefficient.is_zero() {
50 return Ok(Decimal {
51 coefficient,
52 exponent: 0,
53 });
54 }
55 let (coefficient, zeros) = strip_zeros(coefficient);
56 let raised = i64::try_from(zeros)
57 .ok()
58 .and_then(|zeros| exponent.checked_add(zeros))
59 .ok_or(Fault::Limit)?;
60 Ok(Decimal {
61 coefficient,
62 exponent: raised,
63 })
64 }
65
66 pub fn parse(spelling: &str) -> Option<Self> {
72 let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
73 Int::parse(whole)?;
74 if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
75 return None;
76 }
77 let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
78 let exponent = i64::try_from(fraction.len()).ok()?;
79 Decimal::new(coefficient, -exponent).ok()
80 }
81
82 pub fn coefficient(&self) -> &BigInt {
84 &self.coefficient
85 }
86
87 pub fn exponent(&self) -> i64 {
89 self.exponent
90 }
91
92 pub fn is_zero(&self) -> bool {
94 self.coefficient.is_zero()
95 }
96
97 pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
107 if self.is_zero() {
110 return Ok(other.clone());
111 }
112 if other.is_zero() {
113 return Ok(self.clone());
114 }
115 let exponent = self.exponent.min(other.exponent);
116 let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
117 let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
118 Decimal::new(left + right, exponent)
119 }
120
121 pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
127 self.add(&other.neg())
128 }
129
130 #[must_use]
132 pub fn neg(&self) -> Decimal {
133 Decimal {
134 coefficient: -&self.coefficient,
135 exponent: self.exponent,
136 }
137 }
138
139 pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
145 let exponent = self
146 .exponent
147 .checked_add(other.exponent)
148 .ok_or(Fault::Limit)?;
149 Decimal::new(&self.coefficient * &other.coefficient, exponent)
150 }
151
152 pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
165 if divisor.is_zero() {
166 return Err(Fault::DivisionByZero);
167 }
168 let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
169 let shared = self.coefficient.gcd(&divisor.coefficient);
170 let numerator = self.coefficient.abs() / &shared;
171 let denominator = divisor.coefficient.abs() / &shared;
172 let exponent = self
173 .exponent
174 .checked_sub(divisor.exponent)
175 .ok_or(Fault::Limit)?;
176
177 let (twos, fives, rest) = twos_and_fives(&denominator);
178 let (magnitude, exponent) = if rest.is_one() {
179 let k = twos.max(fives);
182 let factor = pow10(k) / &denominator;
183 let shifted = exponent
184 .checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
185 .ok_or(Fault::Limit)?;
186 (numerator * factor, shifted)
187 } else {
188 rounded_quotient(&numerator, &denominator, exponent)?
189 };
190 let signed = if negative { -magnitude } else { magnitude };
191 Decimal::new(signed, exponent)
192 }
193
194 pub fn floor(&self) -> Int {
196 if self.adjusted_exponent() <= 0 {
197 return Int::from(if self.coefficient.is_negative() {
201 BigInt::from(-1)
202 } else {
203 BigInt::zero()
204 });
205 }
206 let up = pow10(self.exponent.max(0).unsigned_abs());
207 let down = pow10(self.exponent.min(0).unsigned_abs());
208 Int::from((&self.coefficient * up).div_floor(&down))
209 }
210
211 pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
218 if self.adjusted_exponent() > i128::from(max_bits) {
219 return None;
220 }
221 let floor = self.floor();
222 (floor.bits() <= max_bits).then_some(floor)
223 }
224
225 pub fn text_len(&self) -> u128 {
228 let digits = u128::from(digit_count(&self.coefficient));
229 let places = u128::from(self.exponent.unsigned_abs());
230 let plain = if self.exponent >= 0 {
231 digits + places
232 } else if digits > places {
233 digits + 1
235 } else {
236 places + 2
238 };
239 plain + u128::from(self.coefficient.is_negative())
240 }
241
242 fn adjusted_exponent(&self) -> i128 {
244 i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
245 }
246}
247
248impl From<&Int> for Decimal {
249 fn from(value: &Int) -> Self {
250 Decimal::new(value.as_bigint().clone(), 0)
251 .expect("an integer has fewer trailing zeros than an exponent can count")
252 }
253}
254
255impl Ord for Decimal {
257 fn cmp(&self, other: &Self) -> Ordering {
258 let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
259 if by_sign != Ordering::Equal {
260 return by_sign;
261 }
262 let magnitude = self
269 .adjusted_exponent()
270 .cmp(&other.adjusted_exponent())
271 .then_with(|| {
272 let (left, right) = (self.coefficient.magnitude(), other.coefficient.magnitude());
273 let shift = pow10(self.exponent.abs_diff(other.exponent)).into_parts().1;
274 if self.exponent > other.exponent {
275 (left * shift).cmp(right)
276 } else {
277 left.cmp(&(right * shift))
278 }
279 });
280 if self.coefficient.is_negative() {
281 magnitude.reverse()
282 } else {
283 magnitude
284 }
285 }
286}
287
288impl PartialOrd for Decimal {
289 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
290 Some(self.cmp(other))
291 }
292}
293
294impl fmt::Display for Decimal {
298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299 let sign = if self.coefficient.is_negative() {
300 "-"
301 } else {
302 ""
303 };
304 let digits = self.coefficient.magnitude().to_string();
305 let Ok(places) = usize::try_from(-self.exponent) else {
306 let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
308 return write!(f, "{sign}{digits}{zeros}");
309 };
310 if places >= digits.len() {
311 let zeros = "0".repeat(places - digits.len());
312 write!(f, "{sign}0.{zeros}{digits}")
313 } else {
314 let (whole, fraction) = digits.split_at(digits.len() - places);
315 if fraction.is_empty() {
316 write!(f, "{sign}{whole}")
317 } else {
318 write!(f, "{sign}{whole}.{fraction}")
319 }
320 }
321 }
322}
323
324impl fmt::Debug for Decimal {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 fmt::Display::fmt(self, f)
327 }
328}
329
330fn pow10(places: u64) -> BigInt {
335 Pow::pow(BigInt::from(10), places)
336}
337
338fn digit_count(value: &BigInt) -> u64 {
344 let magnitude = value.magnitude();
345 if let Some(small) = magnitude.to_u64() {
346 return small
347 .checked_ilog10()
348 .map_or(1, |below| u64::from(below) + 1);
349 }
350 let bits = u128::from(magnitude.bits());
353 let estimate = (bits - 1) * 301_029_995_663_981 / 1_000_000_000_000_000;
354 let mut digits = u64::try_from(estimate).expect("a third of a bit count fits 64 bits") + 1;
355 let mut next = pow10(digits);
356 while magnitude >= next.magnitude() {
357 digits += 1;
358 next *= 10;
359 }
360 digits
361}
362
363fn strip_zeros(coefficient: BigInt) -> (BigInt, u64) {
367 let twos = coefficient.trailing_zeros().unwrap_or(0);
368 let mut rest = coefficient;
369 let mut zeros = 0;
370 for (step, power) in [(19, 10_000_000_000_000_000_000_u64), (1, 10)] {
372 while twos - zeros >= step {
373 let (quotient, remainder) = rest.div_rem(&BigInt::from(power));
374 if !remainder.is_zero() {
375 break;
376 }
377 rest = quotient;
378 zeros += step;
379 }
380 }
381 (rest, zeros)
382}
383
384fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
386 let mut rest = value.clone();
387 let twos = rest.trailing_zeros().unwrap_or(0);
388 rest >>= twos;
389 let five = BigInt::from(5);
390 let mut fives = 0;
391 for _ in 0..value.bits() {
394 let (quotient, remainder) = rest.div_rem(&five);
395 if !remainder.is_zero() {
396 break;
397 }
398 rest = quotient;
399 fives += 1;
400 }
401 (twos, fives, rest)
402}
403
404fn rounded_quotient(
409 numerator: &BigInt,
410 denominator: &BigInt,
411 exponent: i64,
412) -> Result<(BigInt, i64), Fault> {
413 let digits = i64::from(DIVISION_DIGITS);
414 let low = pow10(u64::from(DIVISION_DIGITS));
415 let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
419 let mut guarded = shifted_quotient(numerator, denominator, shift);
420 if guarded < low {
421 shift += 1;
422 guarded = shifted_quotient(numerator, denominator, shift);
423 }
424 let rounded = (guarded + 5) / 10;
428 let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
429 Ok((rounded, exponent))
430}
431
432fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
434 let places = shift.unsigned_abs();
435 if shift >= 0 {
436 (numerator * pow10(places)) / denominator
437 } else {
438 numerator / (denominator * pow10(places))
439 }
440}
441
442fn digits_i64(value: &BigInt) -> i64 {
443 i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
444}