decimal-scaled 0.2.3

Const-generic base-10 fixed-point decimals (D9/D18/D38/D76/D153/D307) with integer-only transcendentals correctly rounded to within 0.5 ULP — exact at the type's last representable place. Deterministic across every platform; no_std-friendly.
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
//! Macro-generated overflow-aware arithmetic variants for the decimal
//! widths that use a *uniform* mul/div pattern (D9, D18, and the wide
//! tier D76 / D153 / D307).
//!
//! Emits the four standard families (`checked_*`, `wrapping_*`,
//! `saturating_*`, `overflowing_*`) for `add`, `sub`, `neg`, `mul`,
//! `div`, `rem`. Behaviour mirrors the corresponding `i128::*` method
//! per the Rust standard library convention:
//!
//! - `checked_*` returns `Some(result)` on success or `None` on
//!   overflow / division-by-zero.
//! - `wrapping_*` returns the result modulo the storage's
//!   `MAX − MIN` range.
//! - `saturating_*` clamps to `Self::MIN` / `Self::MAX` on
//!   overflow.
//! - `overflowing_*` returns `(wrapping_result, overflowed_flag)`.
//!
//! Add / sub / neg / rem delegate to the storage type's `checked_*` /
//! `wrapping_*` / `saturating_*` / `overflowing_*` intrinsics, which
//! the wide integers expose with the same names and `const`-ness as the
//! primitive integers — so those families live in a shared `@common`
//! arm. Mul / div widen to `$Wider` for the intermediate; only the
//! widening *spelling* differs (native `as`-casts vs the `WideInt` cast),
//! so they are written inline per front-end arm.
//!
//! D38 is the exception: its overflow mul/div go through the
//! hand-rolled `mg_divide` path and are not generated here.

/// Emits overflow variants for a decimal type.
///
/// - `decl_decimal_overflow_variants!(D9, i32, i64)` — *native*
/// storage; `$Wider` is a primitive integer.
/// - `decl_decimal_overflow_variants!(wide D76, I256, I512)` — *wide*
/// storage; `$Wider` is the next size up.
macro_rules! decl_decimal_overflow_variants {
    // Wide storage.
    (wide $Type:ident, $Storage:ty, $Wider:ty) => {
        $crate::macros::overflow::decl_decimal_overflow_variants!(@common $Type, $Storage);

        impl<const SCALE: u32> $Type<SCALE> {
            // ----- mul (uses widening) ------------------------------

            /// Checked multiplication. Computes `self * rhs` rounded
            /// toward zero, returning `None` if the result doesn't fit
            /// in `Self`. The intermediate product is computed in
            /// `$Wider` so widening overflow is detected before the
            /// final narrowing.
            #[inline]
            #[must_use]
            pub fn checked_mul(self, rhs: Self) -> Option<Self> {
                let a: $Wider = self.0.resize::<$Wider>();
                let b: $Wider = rhs.0.resize::<$Wider>();
                let m: $Wider = $Type::<SCALE>::multiplier().resize::<$Wider>();
                let prod = a.checked_mul(b)?;
                let scaled = prod / m;
                let storage_max: $Wider = <$Storage>::MAX.resize::<$Wider>();
                let storage_min: $Wider = <$Storage>::MIN.resize::<$Wider>();
                if scaled > storage_max || scaled < storage_min {
                    None
                } else {
                    Some(Self(scaled.resize::<$Storage>()))
                }
            }

            /// Wrapping multiplication. Computes `self * rhs` modulo
            /// the storage type's `MAX − MIN` range. The intermediate
            /// product still widens to `$Wider`; only the *narrowing*
            /// step wraps.
            #[inline]
            #[must_use]
            pub fn wrapping_mul(self, rhs: Self) -> Self {
                let a: $Wider = self.0.resize::<$Wider>();
                let b: $Wider = rhs.0.resize::<$Wider>();
                let m: $Wider = $Type::<SCALE>::multiplier().resize::<$Wider>();
                let prod = a.wrapping_mul(b);
                let scaled = prod / m;
                Self(scaled.resize::<$Storage>())
            }

            /// Saturating multiplication. Computes `self * rhs`,
            /// clamping to [`Self::MIN`] / [`Self::MAX`] on overflow.
            /// Sign of the saturated bound matches the sign of the
            /// exact mathematical product.
            #[inline]
            #[must_use]
            pub fn saturating_mul(self, rhs: Self) -> Self {
                match self.checked_mul(rhs) {
                    Some(v) => v,
                    None => {
                        let neg_result =
                            self.0.is_negative() ^ rhs.0.is_negative();
                        if neg_result { Self::MIN } else { Self::MAX }
                    }
                }
            }

            /// Overflowing multiplication. Returns the wrapped result
            /// together with a boolean flag — `true` if the
            /// mathematical product was out of range.
            #[inline]
            #[must_use]
            pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
                match self.checked_mul(rhs) {
                    Some(v) => (v, false),
                    None => (self.wrapping_mul(rhs), true),
                }
            }

            // ----- div ----------------------------------------------

            /// Checked division. Returns `None` if `rhs` is zero or
            /// the result would overflow [`Self`]. Rounded toward
            /// zero. The numerator is pre-multiplied by `10^SCALE`
            /// in `$Wider` so the intermediate carries the scale-up
            /// step without losing precision.
            #[inline]
            #[must_use]
            pub fn checked_div(self, rhs: Self) -> Option<Self> {
                if rhs == Self::ZERO {
                    return None;
                }
                let a: $Wider = self.0.resize::<$Wider>();
                let b: $Wider = rhs.0.resize::<$Wider>();
                let m: $Wider = $Type::<SCALE>::multiplier().resize::<$Wider>();
                let scaled_numer = a.checked_mul(m)?;
                let result = scaled_numer / b;
                let storage_max: $Wider = <$Storage>::MAX.resize::<$Wider>();
                let storage_min: $Wider = <$Storage>::MIN.resize::<$Wider>();
                if result > storage_max || result < storage_min {
                    None
                } else {
                    Some(Self(result.resize::<$Storage>()))
                }
            }

            /// Wrapping division. Computes `self / rhs` with the
            /// scale-up step done modulo `$Wider`'s range and the
            /// final narrowing wrapping. **Panics** on divide-by-zero
            /// (matches `i128::wrapping_div` semantics).
            #[inline]
            #[must_use]
            pub fn wrapping_div(self, rhs: Self) -> Self {
                let a: $Wider = self.0.resize::<$Wider>();
                let b: $Wider = rhs.0.resize::<$Wider>();
                let m: $Wider = $Type::<SCALE>::multiplier().resize::<$Wider>();
                let scaled_numer = a.wrapping_mul(m);
                let result = scaled_numer / b;
                Self(result.resize::<$Storage>())
            }

            /// Saturating division. Computes `self / rhs`, clamping to
            /// [`Self::MIN`] / [`Self::MAX`] on overflow.
            /// Divide-by-zero saturates to the appropriate-sign bound.
            #[inline]
            #[must_use]
            pub fn saturating_div(self, rhs: Self) -> Self {
                match self.checked_div(rhs) {
                    Some(v) => v,
                    None => {
                        let neg_result =
                            self.0.is_negative() ^ rhs.0.is_negative();
                        if neg_result { Self::MIN } else { Self::MAX }
                    }
                }
            }

            /// Overflowing division. Returns the wrapped result
            /// together with a boolean flag — `true` if the exact
            /// quotient was out of range *or* `rhs` was zero.
            #[inline]
            #[must_use]
            pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
                match self.checked_div(rhs) {
                    Some(v) => (v, false),
                    None => (self.wrapping_div(rhs), true),
                }
            }
        }
    };

    // Native (primitive integer) storage.
    ($Type:ident, $Storage:ty, $Wider:ty) => {
        $crate::macros::overflow::decl_decimal_overflow_variants!(@common $Type, $Storage);

        impl<const SCALE: u32> $Type<SCALE> {
            // ----- mul (uses widening) ------------------------------

            /// Checked multiplication. Computes `self * rhs` rounded
            /// toward zero, returning `None` if the result doesn't fit
            /// in `Self`. The intermediate product widens to `$Wider`
            /// so widening overflow is detected before the narrowing
            /// step.
            #[inline]
            #[must_use]
            pub fn checked_mul(self, rhs: Self) -> Option<Self> {
                let a = self.0 as $Wider;
                let b = rhs.0 as $Wider;
                let m = (10 as $Wider).pow(SCALE);
                let prod = a.checked_mul(b)?;
                let scaled = prod / m;
                if scaled > <$Storage>::MAX as $Wider || scaled < <$Storage>::MIN as $Wider {
                    None
                } else {
                    Some(Self(scaled as $Storage))
                }
            }

            /// Wrapping multiplication. Computes `self * rhs` modulo
            /// the storage type's `MAX − MIN` range.
            #[inline]
            #[must_use]
            pub fn wrapping_mul(self, rhs: Self) -> Self {
                let a = self.0 as $Wider;
                let b = rhs.0 as $Wider;
                let m = (10 as $Wider).pow(SCALE);
                let prod = a.wrapping_mul(b);
                let scaled = prod / m;
                Self(scaled as $Storage)
            }

            /// Saturating multiplication. Clamps to [`Self::MIN`] /
            /// [`Self::MAX`] on overflow, matching the sign of the
            /// exact mathematical product.
            #[inline]
            #[must_use]
            pub fn saturating_mul(self, rhs: Self) -> Self {
                match self.checked_mul(rhs) {
                    Some(v) => v,
                    None => {
                        // Sign of (a * b) is sign(a) XOR sign(b).
                        let neg_result = (self.0 < 0) ^ (rhs.0 < 0);
                        if neg_result { Self::MIN } else { Self::MAX }
                    }
                }
            }

            /// Overflowing multiplication. Returns the wrapped result
            /// together with a boolean — `true` if the exact product
            /// would be out of `Self`'s range.
            #[inline]
            #[must_use]
            pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
                match self.checked_mul(rhs) {
                    Some(v) => (v, false),
                    None => (self.wrapping_mul(rhs), true),
                }
            }

            // ----- div ----------------------------------------------

            /// Checked division. Returns `None` if `rhs` is zero or
            /// the quotient would overflow `Self`. Rounded toward
            /// zero. The numerator is pre-multiplied by `10^SCALE`
            /// in `$Wider`.
            #[inline]
            #[must_use]
            pub fn checked_div(self, rhs: Self) -> Option<Self> {
                if rhs.0 == 0 {
                    return None;
                }
                let a = self.0 as $Wider;
                let b = rhs.0 as $Wider;
                let m = (10 as $Wider).pow(SCALE);
                let scaled_numer = a.checked_mul(m)?;
                let result = scaled_numer / b;
                if result > <$Storage>::MAX as $Wider || result < <$Storage>::MIN as $Wider {
                    None
                } else {
                    Some(Self(result as $Storage))
                }
            }

            /// Wrapping division. **Panics** on divide-by-zero
            /// (matches `i128::wrapping_div` semantics).
            #[inline]
            #[must_use]
            pub fn wrapping_div(self, rhs: Self) -> Self {
                let a = self.0 as $Wider;
                let b = rhs.0 as $Wider;
                let m = (10 as $Wider).pow(SCALE);
                let scaled_numer = a.wrapping_mul(m);
                let result = scaled_numer / b;
                Self(result as $Storage)
            }

            /// Saturating division. Clamps to [`Self::MIN`] /
            /// [`Self::MAX`] on overflow. Divide-by-zero saturates to
            /// the appropriate-sign bound.
            #[inline]
            #[must_use]
            pub fn saturating_div(self, rhs: Self) -> Self {
                match self.checked_div(rhs) {
                    Some(v) => v,
                    None => {
                        // Sign of (a / b) is sign(a) XOR sign(b).
                        let neg_result = (self.0 < 0) ^ (rhs.0 < 0);
                        if neg_result { Self::MIN } else { Self::MAX }
                    }
                }
            }

            /// Overflowing division. Returns the wrapped result with
            /// a boolean — `true` if the exact quotient was out of
            /// range *or* `rhs` was zero.
            #[inline]
            #[must_use]
            pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
                match self.checked_div(rhs) {
                    Some(v) => (v, false),
                    None => (self.wrapping_div(rhs), true),
                }
            }
        }
    };

    // Shared: add / sub / neg / rem and their overflow families.
    // the wide integers expose these intrinsics with the same names and
    // `const`-ness as the primitive integers.
    (@common $Type:ident, $Storage:ty) => {
        impl<const SCALE: u32> $Type<SCALE> {
            // ----- add ----------------------------------------------

            /// Checked addition. `Some(self + rhs)`, or `None` if the
            /// sum would overflow [`Self`].
            #[inline]
            #[must_use]
            pub const fn checked_add(self, rhs: Self) -> Option<Self> {
                match self.0.checked_add(rhs.0) {
                    Some(v) => Some(Self(v)),
                    None => None,
                }
            }

            /// Wrapping addition. `self + rhs` modulo the storage
            /// type's `MAX − MIN` range.
            #[inline]
            #[must_use]
            pub const fn wrapping_add(self, rhs: Self) -> Self {
                Self(self.0.wrapping_add(rhs.0))
            }

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

            /// Overflowing addition. Returns `(self.wrapping_add(rhs),
            /// overflowed)`.
            #[inline]
            #[must_use]
            pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
                let (v, of) = self.0.overflowing_add(rhs.0);
                (Self(v), of)
            }

            // ----- sub ----------------------------------------------

            /// Checked subtraction. `Some(self - rhs)`, or `None` if
            /// the difference would overflow [`Self`].
            #[inline]
            #[must_use]
            pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
                match self.0.checked_sub(rhs.0) {
                    Some(v) => Some(Self(v)),
                    None => None,
                }
            }

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

            /// Saturating subtraction. Clamps to [`Self::MIN`] /
            /// [`Self::MAX`] on overflow.
            #[inline]
            #[must_use]
            pub const fn saturating_sub(self, rhs: Self) -> Self {
                Self(self.0.saturating_sub(rhs.0))
            }

            /// Overflowing subtraction. Returns
            /// `(self.wrapping_sub(rhs), overflowed)`.
            #[inline]
            #[must_use]
            pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
                let (v, of) = self.0.overflowing_sub(rhs.0);
                (Self(v), of)
            }

            // ----- neg ----------------------------------------------

            /// Checked negation. `Some(-self)`, or `None` when
            /// `self == Self::MIN` (whose negation is unrepresentable
            /// in two's-complement).
            #[inline]
            #[must_use]
            pub const fn checked_neg(self) -> Option<Self> {
                match self.0.checked_neg() {
                    Some(v) => Some(Self(v)),
                    None => None,
                }
            }

            /// Wrapping negation. `Self::MIN.wrapping_neg() == Self::MIN`
            /// (same as `i128::wrapping_neg`).
            #[inline]
            #[must_use]
            pub const fn wrapping_neg(self) -> Self {
                Self(self.0.wrapping_neg())
            }

            /// Saturating negation. `Self::MIN.saturating_neg() ==
            /// Self::MAX`.
            #[inline]
            #[must_use]
            pub const fn saturating_neg(self) -> Self {
                Self(self.0.saturating_neg())
            }

            /// Overflowing negation. Returns
            /// `(self.wrapping_neg(), overflowed)`; `overflowed` is
            /// `true` only when `self == Self::MIN`.
            #[inline]
            #[must_use]
            pub const fn overflowing_neg(self) -> (Self, bool) {
                let (v, of) = self.0.overflowing_neg();
                (Self(v), of)
            }

            // ----- rem ----------------------------------------------

            /// Checked remainder. `Some(self % rhs)`, or `None` if
            /// `rhs == 0` *or* the operation would overflow (the
            /// pathological case `Self::MIN % -ONE`).
            #[inline]
            #[must_use]
            pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
                match self.0.checked_rem(rhs.0) {
                    Some(v) => Some(Self(v)),
                    None => None,
                }
            }

            /// Wrapping remainder. **Panics** on divide-by-zero
            /// (matches `i128::wrapping_rem`).
            #[inline]
            #[must_use]
            pub const fn wrapping_rem(self, rhs: Self) -> Self {
                Self(self.0.wrapping_rem(rhs.0))
            }

            /// Overflowing remainder. Returns
            /// `(self.wrapping_rem(rhs), overflowed)`; `overflowed`
            /// is `true` only at the `Self::MIN % -ONE` boundary.
            #[inline]
            #[must_use]
            pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
                let (v, of) = self.0.overflowing_rem(rhs.0);
                (Self(v), of)
            }
        }
    };
}

pub(crate) use decl_decimal_overflow_variants;