1use std::{
2 cmp::Ordering,
3 fmt::{Debug, Display, Write},
4 str::FromStr,
5};
6
7use smallstr::SmallString;
8
9use crate::{
10 checked_pow10, debug_decimal, display_decimal, parse_decimal, pow10, u256::I256, Fixed,
11 OutOfRange, ParseDecimalError,
12};
13
14#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
41#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
42#[cfg_attr(
43 feature = "rkyv",
44 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, rkyv::CheckBytes)
45)]
46pub struct DynamicDecimal {
47 sig: i128,
49
50 exponent: u8,
52}
53
54impl DynamicDecimal {
55 pub const MAX: Self = DynamicDecimal::new(i128::MAX, 0);
57
58 pub const MIN: Self = DynamicDecimal::new(i128::MIN, 0);
60
61 pub const ZERO: Self = DynamicDecimal::new(0, 0);
63
64 pub const ONE: Self = DynamicDecimal::new(1, 0);
66
67 pub const fn new(sig: i128, exponent: u8) -> Self {
69 if exponent == 0 {
70 Self { sig, exponent }
71 } else if sig == 0 {
72 Self { sig, exponent: 0 }
73 } else {
74 const fn reduce<const D: u8>(mut sig: i128, mut exponent: u8) -> (i128, u8) {
77 let scale = pow10(D as usize);
79
80 while exponent >= D
84 && sig.unsigned_abs() >= scale.cast_unsigned()
85 && (sig & ((1 << D) - 1)) == 0
86 && sig % scale == 0
87 {
88 sig /= scale;
89 exponent -= D;
90 }
91 (sig, exponent)
92 }
93
94 let (sig, exponent) = reduce::<8>(sig, exponent);
98 let (sig, exponent) = reduce::<4>(sig, exponent);
99 let (sig, exponent) = reduce::<1>(sig, exponent);
100 debug_assert!(sig % 10 != 0 || exponent == 0);
101 Self { sig, exponent }
102 }
103 }
104
105 pub const fn significand(&self) -> i128 {
107 self.sig
108 }
109
110 pub const fn scale(&self) -> u8 {
112 self.exponent
113 }
114}
115
116impl<const P: usize, const S: usize> From<Fixed<P, S>> for DynamicDecimal {
117 fn from(value: Fixed<P, S>) -> Self {
120 Self::new(value.0, S as u8)
121 }
122}
123
124impl<const P: usize, const S: usize> TryFrom<DynamicDecimal> for Fixed<P, S> {
125 type Error = OutOfRange;
126
127 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
132 Self::try_new_with_exponent(value.sig, S as i32 - value.exponent as i32).ok_or(OutOfRange)
133 }
134}
135
136impl Debug for DynamicDecimal {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 debug_decimal(self.sig, self.exponent as usize, f)
139 }
140}
141
142impl Display for DynamicDecimal {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 display_decimal(self.sig, self.exponent as usize, f)
145 }
146}
147
148impl FromStr for DynamicDecimal {
149 type Err = ParseDecimalError;
150
151 fn from_str(s: &str) -> Result<Self, Self::Err> {
158 let (sig, exponent) = parse_decimal(s, 0)?;
159 match (sig, exponent) {
160 (0, _) => Ok(Self::ZERO),
161 (_, 1..) => {
162 let sig = checked_pow10(exponent.cast_unsigned())
163 .and_then(|m| m.checked_mul(sig))
164 .ok_or(ParseDecimalError::OutOfRange)?;
165 Ok(Self::new(sig, 0))
166 }
167 (_, 0) => Ok(Self { sig, exponent: 0 }),
168 (_, -255..0) => Ok(Self::new(sig, (-exponent) as u8)),
169 (_, ..-255) => {
170 Ok(Self::ZERO)
175 }
176 }
177 }
178}
179
180impl TryFrom<u128> for DynamicDecimal {
181 type Error = OutOfRange;
182
183 fn try_from(value: u128) -> Result<Self, Self::Error> {
184 Ok(Self::new(value.try_into().map_err(|_| OutOfRange)?, 0))
185 }
186}
187
188macro_rules! from_int {
189 ($type_name:ty) => {
190 impl From<$type_name> for DynamicDecimal {
191 fn from(value: $type_name) -> Self {
192 Self::new(value as i128, 0)
193 }
194 }
195 };
196}
197from_int!(i128);
198from_int!(i64);
199from_int!(i32);
200from_int!(i16);
201from_int!(i8);
202from_int!(isize);
203from_int!(u64);
204from_int!(u32);
205from_int!(u16);
206from_int!(u8);
207from_int!(usize);
208
209impl From<DynamicDecimal> for i128 {
210 fn from(value: DynamicDecimal) -> Self {
213 checked_pow10(value.exponent.into()).map_or(0, |divisor| value.sig / divisor)
214 }
215}
216
217macro_rules! try_to_signed_int {
218 ($type_name:ty) => {
219 impl TryFrom<DynamicDecimal> for $type_name {
220 type Error = OutOfRange;
221
222 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
225 match checked_pow10(value.exponent.into()) {
226 Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
227 None => Ok(0),
228 }
229 }
230 }
231 };
232}
233try_to_signed_int!(i64);
234try_to_signed_int!(i32);
235try_to_signed_int!(i16);
236try_to_signed_int!(i8);
237try_to_signed_int!(isize);
238
239macro_rules! try_to_unsigned_int {
242 ($type_name:ty) => {
243 impl TryFrom<DynamicDecimal> for $type_name {
244 type Error = OutOfRange;
245
246 fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
252 match checked_pow10(value.exponent.into()) {
253 Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
254 None => Ok(0),
255 }
256 }
257 }
258 };
259}
260try_to_unsigned_int!(u128);
261try_to_unsigned_int!(u64);
262try_to_unsigned_int!(u32);
263try_to_unsigned_int!(u16);
264try_to_unsigned_int!(u8);
265try_to_unsigned_int!(usize);
266
267impl TryFrom<f64> for DynamicDecimal {
268 type Error = OutOfRange;
269
270 fn try_from(value: f64) -> Result<Self, Self::Error> {
273 let mut buf = SmallString::<[u8; 64]>::new();
279 write!(&mut buf, "{value:.15e}").unwrap();
280 buf.parse().map_err(|_| OutOfRange)
281 }
282}
283
284impl PartialOrd for DynamicDecimal {
285 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
286 Some(self.cmp(other))
287 }
288}
289
290impl Ord for DynamicDecimal {
291 fn cmp(&self, other: &Self) -> Ordering {
292 match self.exponent.cmp(&other.exponent) {
293 Ordering::Less => {
294 if let Some(multiplier) =
295 checked_pow10(other.exponent as u32 - self.exponent as u32)
296 {
297 I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
298 } else {
299 match self.sig.cmp(&0) {
300 Ordering::Equal => 0.cmp(&other.sig),
301 ordering => ordering,
302 }
303 }
304 }
305 Ordering::Equal => self.sig.cmp(&other.sig),
306 Ordering::Greater => {
307 if let Some(multiplier) =
308 checked_pow10(self.exponent as u32 - other.exponent as u32)
309 {
310 I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
311 } else {
312 match other.sig.cmp(&0) {
313 Ordering::Equal => self.sig.cmp(&0),
314 ordering => ordering.reverse(),
315 }
316 }
317 }
318 }
319 }
320}
321
322#[cfg(test)]
323mod test {
324 use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
325
326 #[test]
327 fn eq() {
328 assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
329 assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
330 assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
331 assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
332 }
333
334 #[test]
335 fn compare() {
336 type DD = DynamicDecimal;
337 fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
338 assert_eq!(dx == dy, x == y);
339 assert_eq!(dx != dy, x != y);
340 assert_eq!(dx > dy, x > y);
341 assert_eq!(dx >= dy, x >= y);
342 assert_eq!(dx < dy, x < y);
343 assert_eq!(dx <= dy, x <= y);
344 }
345
346 for x in -999..=999 {
347 let fx = DD::new(x, 1);
348 for y in -999..=999 {
349 check_comparisons(fx, DD::new(y, 0), x, y * 10);
350 check_comparisons(fx, DD::new(y, 1), x, y);
351 check_comparisons(fx, DD::new(y, 2), x * 10, y);
352 }
353 }
354
355 check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
357 check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
358
359 check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
360 check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
361 check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
362 check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
363
364 check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
365 check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
366 check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
367 check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
368 }
369
370 #[test]
371 fn from_str() {
372 for (s, expect) in [
373 ("0", Ok("0")),
374 ("0.", Ok("0")),
375 (".0", Ok("0")),
376 ("-0", Ok("0")),
377 ("+0", Ok("0")),
378 ("--0", Err(ParseDecimalError::SyntaxError)),
379 ("-+0", Err(ParseDecimalError::SyntaxError)),
380 ("0x", Err(ParseDecimalError::SyntaxError)),
381 ("0e5x", Err(ParseDecimalError::SyntaxError)),
382 ("1.23", Ok("1.23")),
383 ("-1.23", Ok("-1.23")),
384 ("+1.23", Ok("1.23")),
385 ("99999999", Ok("99999999")),
386 ("999999999", Ok("999999999")),
387 ("999999999E-1", Ok("99999999.9")),
388 ("9999999999e-1", Ok("999999999.9")),
389 ("9999999999E-2", Ok("99999999.99")),
390 ("99999999999e-2", Ok("999999999.99")),
391 ("99999999999e-3", Ok("99999999.999")),
392 ("99999999991e-3", Ok("99999999.991")),
393 (
397 "111111111111111111111111111111111111111111e-34",
398 Ok("11111111.1111111111111111111111111111111"),
399 ),
400 (
404 "1.23456788901234567890123456789012345678890123456",
405 Ok("1.23456788901234567890123456789012345678"),
406 ),
407 ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
409 ("0e999999999999999", Ok("0")),
411 ("1e-999999999999999", Ok("0")),
413 (
417 "111111111111111111111111111111111111111111e2147483644",
418 Err(ParseDecimalError::OutOfRange),
419 ),
420 (
423 ".1111111111111111111111111111111111111111e-2147483648",
424 Ok("0"),
425 ),
426 ("123e5", Ok("12300000")),
427 ("123E4", Ok("1230000")),
428 ("123e3", Ok("123000")),
429 ("123e2", Ok("12300")),
430 ("123e1", Ok("1230")),
431 ("123e0", Ok("123")),
432 ("123e-1", Ok("12.3")),
433 ("123e-2", Ok("1.23")),
434 (".123", Ok("0.123")),
435 (".124", Ok("0.124")),
436 (".125", Ok("0.125")),
437 (".126", Ok("0.126")),
438 (".133", Ok("0.133")),
439 (".134", Ok("0.134")),
440 (".135", Ok("0.135")),
441 (".136", Ok("0.136")),
442 ("1e38", Ok("100000000000000000000000000000000000000")),
443 ("1e39", Err(ParseDecimalError::OutOfRange)),
444 ("1e-255", Ok("0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001")),
445 ("1e-256", Ok("0")),
446 ] {
447 println!("{s}: {:?}", s.parse::<DynamicDecimal>());
448 assert_eq!(
449 s.parse::<DynamicDecimal>().map(|d| d.to_string()),
450 expect.map(|d| d.to_string())
451 );
452 }
453 }
454
455 #[test]
456 fn to_integer() {
457 for x in -9999..=9999 {
458 let f = DynamicDecimal::new(x, 1);
459 assert_eq!(i128::from(f), x / 10);
460 assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
461 assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
462 assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
463 assert_eq!(
464 i8::try_from(f).ok(),
465 (-1289..=1279).contains(&x).then_some((x / 10) as i8)
466 );
467 assert_eq!(
468 u128::try_from(f).ok(),
469 (x > -10).then_some((x / 10) as u128)
470 );
471 assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
472 assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
473 assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
474 assert_eq!(
475 u8::try_from(f).ok(),
476 (-9..=2559).contains(&x).then_some((x / 10) as u8)
477 );
478 }
479
480 assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
481 assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
482 assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
483 assert_eq!(
484 i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
485 Err(OutOfRange)
486 );
487 assert_eq!(
488 i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
489 Err(OutOfRange)
490 );
491 }
492}