nexus-decimal 1.0.3

Fixed-point decimal arithmetic with compile-time precision
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Checked, saturating, wrapping, and try arithmetic for `Decimal`.
//!
//! Add/Sub/Neg/Abs are shared via macro.
//! Mul/Div differ per backing type:
//! - i32: widen to i64, native division (LLVM magic multiply)
//! - i64: widen to i128, chunked magic division for SCALE < 2^32
//!   (3× u64 magic multiplies, ~14 cycles), native fallback otherwise
//! - i128: 192-bit wide arithmetic (manual limb math)

use crate::Decimal;
use crate::error::{DivError, OverflowError};

// ============================================================================
// Add / Sub / Neg / Abs — shared across all backing types
// ============================================================================

macro_rules! impl_decimal_arithmetic {
    ($backing:ty) => {
        impl<const D: u8> Decimal<$backing, D> {
            // ========================================================
            // Checked
            // ========================================================

            /// Checked addition. Returns `None` on overflow.
            #[inline(always)]
            pub const fn checked_add(self, rhs: Self) -> Option<Self> {
                match self.value.checked_add(rhs.value) {
                    Some(v) => Some(Self { value: v }),
                    None => None,
                }
            }

            /// Checked subtraction. Returns `None` on overflow.
            #[inline(always)]
            pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
                match self.value.checked_sub(rhs.value) {
                    Some(v) => Some(Self { value: v }),
                    None => None,
                }
            }

            /// Checked negation. Returns `None` if `self == MIN`.
            #[inline(always)]
            pub const fn checked_neg(self) -> Option<Self> {
                match self.value.checked_neg() {
                    Some(v) => Some(Self { value: v }),
                    None => None,
                }
            }

            /// Checked absolute value. Returns `None` if `self == MIN`.
            #[inline(always)]
            pub const fn checked_abs(self) -> Option<Self> {
                if self.value >= 0 {
                    Some(self)
                } else {
                    self.checked_neg()
                }
            }

            // ========================================================
            // Saturating
            // ========================================================

            /// Saturating addition. Clamps to `MIN`/`MAX` on overflow.
            #[inline(always)]
            pub const fn saturating_add(self, rhs: Self) -> Self {
                Self {
                    value: self.value.saturating_add(rhs.value),
                }
            }

            /// Saturating subtraction.
            #[inline(always)]
            pub const fn saturating_sub(self, rhs: Self) -> Self {
                Self {
                    value: self.value.saturating_sub(rhs.value),
                }
            }

            /// Saturating negation.
            #[inline(always)]
            pub const fn saturating_neg(self) -> Self {
                Self {
                    value: self.value.saturating_neg(),
                }
            }

            /// Saturating absolute value.
            #[inline(always)]
            pub const fn saturating_abs(self) -> Self {
                Self {
                    value: self.value.saturating_abs(),
                }
            }

            // ========================================================
            // Wrapping
            // ========================================================

            /// Wrapping addition.
            #[inline(always)]
            pub const fn wrapping_add(self, rhs: Self) -> Self {
                Self {
                    value: self.value.wrapping_add(rhs.value),
                }
            }

            /// Wrapping subtraction.
            #[inline(always)]
            pub const fn wrapping_sub(self, rhs: Self) -> Self {
                Self {
                    value: self.value.wrapping_sub(rhs.value),
                }
            }

            /// Wrapping negation.
            #[inline(always)]
            pub const fn wrapping_neg(self) -> Self {
                Self {
                    value: self.value.wrapping_neg(),
                }
            }

            /// Wrapping absolute value.
            #[inline(always)]
            pub const fn wrapping_abs(self) -> Self {
                Self {
                    value: self.value.wrapping_abs(),
                }
            }

            // ========================================================
            // Try (Result-returning) — add/sub/neg/abs
            // ========================================================

            /// Addition returning `Result`.
            #[inline(always)]
            pub const fn try_add(self, rhs: Self) -> Result<Self, OverflowError> {
                match self.checked_add(rhs) {
                    Some(v) => Ok(v),
                    None => Err(OverflowError),
                }
            }

            /// Subtraction returning `Result`.
            #[inline(always)]
            pub const fn try_sub(self, rhs: Self) -> Result<Self, OverflowError> {
                match self.checked_sub(rhs) {
                    Some(v) => Ok(v),
                    None => Err(OverflowError),
                }
            }

            /// Negation returning `Result`.
            #[inline(always)]
            pub const fn try_neg(self) -> Result<Self, OverflowError> {
                match self.checked_neg() {
                    Some(v) => Ok(v),
                    None => Err(OverflowError),
                }
            }

            /// Absolute value returning `Result`.
            #[inline(always)]
            pub const fn try_abs(self) -> Result<Self, OverflowError> {
                match self.checked_abs() {
                    Some(v) => Ok(v),
                    None => Err(OverflowError),
                }
            }
        }
    };
}

impl_decimal_arithmetic!(i32);
impl_decimal_arithmetic!(i64);
impl_decimal_arithmetic!(i128);

// ============================================================================
// Mul / Div — i32 (widen to i64, native division)
// ============================================================================

impl<const D: u8> Decimal<i32, D> {
    /// Checked multiplication. Widens to i64, divides by SCALE.
    #[inline(always)]
    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
        // i32 * i32 always fits in i64 — no overflow possible
        let product = (self.value as i64) * (rhs.value as i64);
        let result = product / (Self::SCALE as i64);

        if result > i32::MAX as i64 || result < i32::MIN as i64 {
            None
        } else {
            Some(Self {
                value: result as i32,
            })
        }
    }

    /// Checked division. Returns `None` if `rhs` is zero or result overflows.
    #[inline(always)]
    pub const fn checked_div(self, rhs: Self) -> Option<Self> {
        if rhs.value == 0 {
            return None;
        }
        let a = self.value as i64;
        let b = rhs.value as i64;
        let result = (a * Self::SCALE as i64) / b;

        if result > i32::MAX as i64 || result < i32::MIN as i64 {
            None
        } else {
            Some(Self {
                value: result as i32,
            })
        }
    }

    /// Saturating multiplication.
    #[inline(always)]
    pub const fn saturating_mul(self, rhs: Self) -> Self {
        let product = (self.value as i64) * (rhs.value as i64);
        let result = product / (Self::SCALE as i64);

        if result > i32::MAX as i64 {
            Self::MAX
        } else if result < i32::MIN as i64 {
            Self::MIN
        } else {
            Self {
                value: result as i32,
            }
        }
    }

    /// Wrapping multiplication.
    #[inline(always)]
    pub const fn wrapping_mul(self, rhs: Self) -> Self {
        let product = (self.value as i64) * (rhs.value as i64);
        Self {
            value: (product / (Self::SCALE as i64)) as i32,
        }
    }

    /// Saturating division.
    #[inline(always)]
    pub const fn saturating_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");
        match self.checked_div(rhs) {
            Some(v) => v,
            None => {
                if (self.value > 0) == (rhs.value > 0) {
                    Self::MAX
                } else {
                    Self::MIN
                }
            }
        }
    }

    /// Wrapping division.
    #[inline(always)]
    pub const fn wrapping_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");
        let a = self.value as i64;
        let b = rhs.value as i64;
        Self {
            value: ((a * Self::SCALE as i64) / b) as i32,
        }
    }

    /// Multiply by a plain integer (no rescaling).
    #[inline(always)]
    pub const fn mul_int(self, rhs: i32) -> Option<Self> {
        match self.value.checked_mul(rhs) {
            Some(v) => Some(Self { value: v }),
            None => None,
        }
    }

    /// Fused multiply-add: `(self * mul) + add` with single rescaling.
    #[inline(always)]
    pub const fn mul_add(self, mul: Self, add: Self) -> Option<Self> {
        let product = (self.value as i64) * (mul.value as i64);
        let rescaled = product / (Self::SCALE as i64);
        let result = rescaled + (add.value as i64);

        if result > i32::MAX as i64 || result < i32::MIN as i64 {
            None
        } else {
            Some(Self {
                value: result as i32,
            })
        }
    }

    /// Multiplication returning `Result`.
    #[inline(always)]
    pub const fn try_mul(self, rhs: Self) -> Result<Self, OverflowError> {
        match self.checked_mul(rhs) {
            Some(v) => Ok(v),
            None => Err(OverflowError),
        }
    }

    /// Division returning `Result` with specific error.
    #[inline(always)]
    pub const fn try_div(self, rhs: Self) -> Result<Self, DivError> {
        if rhs.value == 0 {
            return Err(DivError::DivisionByZero);
        }
        match self.checked_div(rhs) {
            Some(v) => Ok(v),
            None => Err(DivError::Overflow),
        }
    }
}

// ============================================================================
// Mul / Div — i64 (widen to i128, chunked magic division when SCALE < 2^32)
// ============================================================================
//
// When SCALE < 2^32 (covers Decimal<i64, 1..=9>), uses chunked
// u64 division (~14 cycles, 3 magic multiplies). Otherwise falls back to
// native i128 division (__divti3 ~25 cycles). The const branch is
// eliminated by LLVM — zero runtime cost for type selection.

use crate::div_by_scale;

impl<const D: u8> Decimal<i64, D> {
    /// Whether this (i64, D) combination qualifies for chunked fast path.
    const USE_CHUNKED: bool = (Self::SCALE as u64) < div_by_scale::CHUNK_THRESHOLD;

    /// Divide an i128 product by SCALE, using the fast path when available.
    #[inline(always)]
    const fn div_product_by_scale(product: i128) -> Option<i64> {
        div_by_scale::div_i128_by_scale(
            product,
            Self::SCALE as i128,
            Self::SCALE as u64,
            Self::USE_CHUNKED,
        )
    }

    /// Wrapping version of SCALE division.
    #[inline(always)]
    const fn div_product_by_scale_wrapping(product: i128) -> i64 {
        div_by_scale::div_i128_by_scale_wrapping(
            product,
            Self::SCALE as i128,
            Self::SCALE as u64,
            Self::USE_CHUNKED,
        )
    }

    /// Checked multiplication. Widens to i128, divides by SCALE.
    #[inline(always)]
    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
        let a = self.value as i128;
        let b = rhs.value as i128;

        let Some(product) = a.checked_mul(b) else {
            return None;
        };

        match Self::div_product_by_scale(product) {
            Some(result) => Some(Self { value: result }),
            None => None,
        }
    }

    /// Checked division. Returns `None` if `rhs` is zero or result overflows.
    ///
    /// Division by a runtime value cannot use the chunked path — the
    /// divisor isn't a compile-time constant. Uses native i128 division.
    #[inline(always)]
    pub const fn checked_div(self, rhs: Self) -> Option<Self> {
        if rhs.value == 0 {
            return None;
        }
        let a = self.value as i128;
        let b = rhs.value as i128;
        let result = (a * Self::SCALE as i128) / b;

        if result > i64::MAX as i128 || result < i64::MIN as i128 {
            None
        } else {
            Some(Self {
                value: result as i64,
            })
        }
    }

    /// Saturating multiplication.
    #[inline(always)]
    pub const fn saturating_mul(self, rhs: Self) -> Self {
        let product = (self.value as i128) * (rhs.value as i128);
        match Self::div_product_by_scale(product) {
            Some(result) => Self { value: result },
            None => {
                if product > 0 {
                    Self::MAX
                } else {
                    Self::MIN
                }
            }
        }
    }

    /// Wrapping multiplication.
    #[inline(always)]
    pub const fn wrapping_mul(self, rhs: Self) -> Self {
        let product = (self.value as i128).wrapping_mul(rhs.value as i128);
        Self {
            value: Self::div_product_by_scale_wrapping(product),
        }
    }

    /// Saturating division.
    #[inline(always)]
    pub const fn saturating_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");
        match self.checked_div(rhs) {
            Some(v) => v,
            None => {
                if (self.value > 0) == (rhs.value > 0) {
                    Self::MAX
                } else {
                    Self::MIN
                }
            }
        }
    }

    /// Wrapping division.
    #[inline(always)]
    pub const fn wrapping_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");
        let a = self.value as i128;
        let b = rhs.value as i128;
        Self {
            value: ((a * Self::SCALE as i128) / b) as i64,
        }
    }

    /// Multiply by a plain integer (no rescaling).
    #[inline(always)]
    pub const fn mul_int(self, rhs: i64) -> Option<Self> {
        match self.value.checked_mul(rhs) {
            Some(v) => Some(Self { value: v }),
            None => None,
        }
    }

    /// Fused multiply-add: `(self * mul) + add` with single rescaling.
    #[inline(always)]
    pub const fn mul_add(self, mul: Self, add: Self) -> Option<Self> {
        let a = self.value as i128;
        let b = mul.value as i128;

        let Some(product) = a.checked_mul(b) else {
            return None;
        };

        let Some(rescaled) = Self::div_product_by_scale(product) else {
            return None;
        };
        let rescaled = rescaled as i128;

        let Some(result) = rescaled.checked_add(add.value as i128) else {
            return None;
        };

        if result > i64::MAX as i128 || result < i64::MIN as i128 {
            None
        } else {
            Some(Self {
                value: result as i64,
            })
        }
    }

    /// Multiplication returning `Result`.
    #[inline(always)]
    pub const fn try_mul(self, rhs: Self) -> Result<Self, OverflowError> {
        match self.checked_mul(rhs) {
            Some(v) => Ok(v),
            None => Err(OverflowError),
        }
    }

    /// Division returning `Result` with specific error.
    #[inline(always)]
    pub const fn try_div(self, rhs: Self) -> Result<Self, DivError> {
        if rhs.value == 0 {
            return Err(DivError::DivisionByZero);
        }
        match self.checked_div(rhs) {
            Some(v) => Ok(v),
            None => Err(DivError::Overflow),
        }
    }
}

// ============================================================================
// Mul / Div — i128 (192-bit wide arithmetic, NOT const fn)
// ============================================================================

use crate::wide;

impl<const D: u8> Decimal<i128, D> {
    /// Threshold for fast-path multiplication (both operands < 2^64).
    const FAST_MUL_THRESHOLD: u128 = 1u128 << 64;

    /// Checked multiplication using 192-bit wide arithmetic.
    #[inline(always)]
    pub fn checked_mul(self, rhs: Self) -> Option<Self> {
        if self.value == 0 || rhs.value == 0 {
            return Some(Self::ZERO);
        }

        let result_negative = (self.value < 0) != (rhs.value < 0);
        let a = self.value.unsigned_abs();
        let b = rhs.value.unsigned_abs();

        // Fast path: both values fit in 64 bits → product fits in 128 bits
        if a < Self::FAST_MUL_THRESHOLD && b < Self::FAST_MUL_THRESHOLD {
            let product = a * b;
            let quotient = product / (Self::SCALE as u128);
            return Self::from_unsigned(quotient, result_negative);
        }

        // Slow path: 192-bit multiplication
        let (prod_low, prod_high) = wide::mul_wide(a, b);
        let quotient = wide::div_192_by_const(prod_low, prod_high, Self::SCALE as u128)?;
        Self::from_unsigned(quotient, result_negative)
    }

    /// Checked division using 192-bit wide arithmetic.
    #[inline(always)]
    pub fn checked_div(self, rhs: Self) -> Option<Self> {
        if rhs.value == 0 {
            return None;
        }
        if self.value == 0 {
            return Some(Self::ZERO);
        }

        let result_negative = (self.value < 0) != (rhs.value < 0);
        let a = self.value.unsigned_abs();
        let b = rhs.value.unsigned_abs();
        let scale = Self::SCALE as u128;

        // Widen: a * SCALE (can exceed 128 bits)
        let (prod_low, prod_high) = wide::mul_u128_by_small(a, scale);

        // Divide 192-bit by runtime divisor
        let quotient = wide::div_192_by_u128(prod_low, prod_high, b)?;
        Self::from_unsigned(quotient, result_negative)
    }

    /// Saturating multiplication.
    #[inline(always)]
    pub fn saturating_mul(self, rhs: Self) -> Self {
        self.checked_mul(rhs).unwrap_or({
            if (self.value > 0) == (rhs.value > 0) {
                Self::MAX
            } else {
                Self::MIN
            }
        })
    }

    /// Wrapping multiplication.
    #[inline(always)]
    pub fn wrapping_mul(self, rhs: Self) -> Self {
        if self.value == 0 || rhs.value == 0 {
            return Self::ZERO;
        }

        let result_negative = (self.value < 0) != (rhs.value < 0);
        let a = self.value.unsigned_abs();
        let b = rhs.value.unsigned_abs();

        let (prod_low, prod_high) = wide::mul_wide(a, b);
        let quotient = wide::div_192_by_const_wrapping(prod_low, prod_high, Self::SCALE as u128);

        if result_negative {
            Self {
                value: (quotient as i128).wrapping_neg(),
            }
        } else {
            Self {
                value: quotient as i128,
            }
        }
    }

    /// Saturating division.
    #[inline(always)]
    pub fn saturating_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");
        self.checked_div(rhs).unwrap_or({
            if (self.value > 0) == (rhs.value > 0) {
                Self::MAX
            } else {
                Self::MIN
            }
        })
    }

    /// Wrapping division.
    #[inline(always)]
    pub fn wrapping_div(self, rhs: Self) -> Self {
        assert!(rhs.value != 0, "division by zero");

        let result_negative = (self.value < 0) != (rhs.value < 0);
        let a = self.value.unsigned_abs();
        let b = rhs.value.unsigned_abs();
        let scale = Self::SCALE as u128;

        let (prod_low, prod_high) = wide::mul_u128_by_small(a, scale);
        let quotient = wide::div_192_by_u128_wrapping(prod_low, prod_high, b);

        if result_negative {
            Self {
                value: (quotient as i128).wrapping_neg(),
            }
        } else {
            Self {
                value: quotient as i128,
            }
        }
    }

    /// Multiply by a plain integer (no rescaling).
    #[inline(always)]
    pub const fn mul_int(self, rhs: i128) -> Option<Self> {
        match self.value.checked_mul(rhs) {
            Some(v) => Some(Self { value: v }),
            None => None,
        }
    }

    /// Fused multiply-add: `(self * mul) + add` with single rescaling.
    #[inline(always)]
    pub fn mul_add(self, mul: Self, add: Self) -> Option<Self> {
        if self.value == 0 || mul.value == 0 {
            return Some(add);
        }

        let product = self.checked_mul(mul)?;
        product.checked_add(add)
    }

    /// Multiplication returning `Result`.
    #[inline(always)]
    pub fn try_mul(self, rhs: Self) -> Result<Self, OverflowError> {
        self.checked_mul(rhs).ok_or(OverflowError)
    }

    /// Division returning `Result` with specific error.
    #[inline(always)]
    pub fn try_div(self, rhs: Self) -> Result<Self, DivError> {
        if rhs.value == 0 {
            return Err(DivError::DivisionByZero);
        }
        self.checked_div(rhs).ok_or(DivError::Overflow)
    }

    /// Helper: convert unsigned quotient + sign to Decimal, with bounds check.
    #[inline(always)]
    fn from_unsigned(quotient: u128, negative: bool) -> Option<Self> {
        if negative {
            // i128::MIN.unsigned_abs() = i128::MAX + 1
            if quotient > (i128::MAX as u128) + 1 {
                return None;
            }
            Some(Self {
                value: (quotient as i128).wrapping_neg(),
            })
        } else {
            if quotient > i128::MAX as u128 {
                return None;
            }
            Some(Self {
                value: quotient as i128,
            })
        }
    }
}