qubit-datatype 0.15.2

Runtime data type descriptors and conversion utilities for Rust
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Borrowed numeric value representations used by comparison APIs.

use std::cmp::Ordering;

#[cfg(feature = "big-decimal")]
use bigdecimal::BigDecimal;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use num_bigint::BigInt;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use num_rational::BigRational;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use num_traits::Signed;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use num_traits::ToPrimitive;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use num_traits::Zero;

use super::NumericComparisonPolicy;
use super::internal::NumberRepr;
#[cfg(feature = "big-integer")]
use super::internal::compare_big_integer_float;
use super::internal::compare_magnitude;
#[cfg(feature = "big-decimal")]
use super::internal::decimal_rational;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use super::internal::f32_rational;
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
use super::internal::f64_rational;
use super::internal::finite_parts;

/// Compares an arbitrary-precision integer with a signed fixed-width value.
///
/// # Parameters
///
/// * `left` - Arbitrary-precision value on the left.
/// * `right` - Signed fixed-width value on the right.
///
/// # Returns
///
/// The exact mathematical ordering.
#[cfg(feature = "big-integer")]
#[must_use]
#[inline]
fn compare_big_integer_signed(left: &BigInt, right: i128) -> Ordering {
    match left.to_i128() {
        Some(left) => left.cmp(&right),
        None if left.is_negative() => Ordering::Less,
        None => Ordering::Greater,
    }
}

/// Compares an arbitrary-precision integer with an unsigned fixed-width value.
///
/// # Parameters
///
/// * `left` - Arbitrary-precision value on the left.
/// * `right` - Unsigned fixed-width value on the right.
///
/// # Returns
///
/// The exact mathematical ordering.
#[cfg(feature = "big-integer")]
#[must_use]
#[inline]
fn compare_big_integer_unsigned(left: &BigInt, right: u128) -> Ordering {
    if left.is_negative() {
        Ordering::Less
    } else {
        match left.to_u128() {
            Some(left) => left.cmp(&right),
            None => Ordering::Greater,
        }
    }
}

/// Compares an arbitrary-precision integer with a fixed-width representation.
///
/// # Parameters
///
/// * `left` - Arbitrary-precision integer on the left.
/// * `right` - Candidate fixed-width integer on the right.
///
/// # Returns
///
/// The ordering for a fixed-width integer, or `None` for any other numeric
/// representation.
#[cfg(feature = "big-integer")]
fn compare_big_integer_to_fixed(left: &BigInt, right: NumberRepr<'_>) -> Option<Ordering> {
    match right {
        NumberRepr::Int8(right) => Some(compare_big_integer_signed(left, i128::from(right))),
        NumberRepr::Int16(right) => Some(compare_big_integer_signed(left, i128::from(right))),
        NumberRepr::Int32(right) => Some(compare_big_integer_signed(left, i128::from(right))),
        NumberRepr::Int64(right) => Some(compare_big_integer_signed(left, i128::from(right))),
        NumberRepr::Int128(right) => Some(compare_big_integer_signed(left, right)),
        NumberRepr::UInt8(right) => Some(compare_big_integer_unsigned(left, u128::from(right))),
        NumberRepr::UInt16(right) => Some(compare_big_integer_unsigned(left, u128::from(right))),
        NumberRepr::UInt32(right) => Some(compare_big_integer_unsigned(left, u128::from(right))),
        NumberRepr::UInt64(right) => Some(compare_big_integer_unsigned(left, u128::from(right))),
        NumberRepr::UInt128(right) => Some(compare_big_integer_unsigned(left, right)),
        _ => None,
    }
}

/// Borrows or copies a numeric value without depending on a runtime value enum.
///
/// Values are constructed through [`From`] implementations. The internal
/// representation is intentionally private, so callers cannot create marker
/// or otherwise non-numeric states.
///
/// # Type Parameters
///
/// * `'a` - Lifetime of a borrowed arbitrary-precision numeric value.
///
/// # Examples
///
/// ```
/// use qubit_datatype::NumberRef;
///
/// let number = NumberRef::from(42_i64);
/// assert!(number.is_integer());
/// ```
///
/// ```
/// use std::cmp::Ordering;
/// use qubit_datatype::NumberRef;
/// use qubit_datatype::NumericComparisonPolicy;
///
/// let integer = NumberRef::from((1_u64 << 53) + 1);
/// let float = NumberRef::from((1_u64 << 53) as f64);
/// assert_eq!(integer.compare(float, NumericComparisonPolicy::Exact), Some(Ordering::Greater));
/// assert_eq!(integer.compare(float, NumericComparisonPolicy::Approximate), Some(Ordering::Equal));
/// assert_eq!(integer.compare(NumberRef::from(f64::NAN), NumericComparisonPolicy::Exact), None);
/// ```
///
/// ```compile_fail
/// use qubit_datatype::NumberRef;
///
/// let _ = NumberRef::Int8(1);
/// ```
#[must_use]
#[derive(Debug, Clone, Copy)]
pub struct NumberRef<'a> {
    /// Private numeric representation.
    inner: NumberRepr<'a>,
}

/// Implements copied fixed-width conversions into [`NumberRef`].
macro_rules! impl_from_copy {
    ($source:ty, $variant:ident) => {
        impl From<$source> for NumberRef<'_> {
            /// Creates a numeric view by copying a fixed-width value.
            ///
            /// # Parameters
            ///
            /// * `value` - Numeric value to copy.
            ///
            /// # Returns
            ///
            /// A numeric view owning the copied scalar representation.
            #[inline]
            fn from(value: $source) -> Self {
                Self {
                    inner: NumberRepr::$variant(value),
                }
            }
        }
    };
}

/// Implements borrowed arbitrary-precision conversions into [`NumberRef`].
#[cfg(any(feature = "big-integer", feature = "big-decimal"))]
macro_rules! impl_from_ref {
    ($source:ty, $variant:ident) => {
        impl<'a> From<&'a $source> for NumberRef<'a> {
            /// Creates a numeric view borrowing an arbitrary-precision value.
            ///
            /// # Parameters
            ///
            /// * `value` - Numeric value to borrow.
            ///
            /// # Returns
            ///
            /// A numeric view borrowing the source for its lifetime.
            #[inline]
            fn from(value: &'a $source) -> Self {
                Self {
                    inner: NumberRepr::$variant(value),
                }
            }
        }
    };
}

impl_from_copy!(i8, Int8);
impl_from_copy!(i16, Int16);
impl_from_copy!(i32, Int32);
impl_from_copy!(i64, Int64);
impl_from_copy!(i128, Int128);
impl_from_copy!(u8, UInt8);
impl_from_copy!(u16, UInt16);
impl_from_copy!(u32, UInt32);
impl_from_copy!(u64, UInt64);
impl_from_copy!(u128, UInt128);
impl_from_copy!(f32, Float32);
impl_from_copy!(f64, Float64);
#[cfg(feature = "big-integer")]
impl_from_ref!(BigInt, BigInteger);
#[cfg(feature = "big-decimal")]
impl_from_ref!(BigDecimal, BigDecimal);

impl<'a> NumberRef<'a> {
    /// Reports whether this value is an integer representation.
    ///
    /// # Returns
    ///
    /// `true` for fixed-width integer values.
    #[inline]
    #[must_use]
    pub fn is_integer(self) -> bool {
        matches!(
            self.inner,
            NumberRepr::Int8(_)
                | NumberRepr::Int16(_)
                | NumberRepr::Int32(_)
                | NumberRepr::Int64(_)
                | NumberRepr::Int128(_)
                | NumberRepr::UInt8(_)
                | NumberRepr::UInt16(_)
                | NumberRepr::UInt32(_)
                | NumberRepr::UInt64(_)
                | NumberRepr::UInt128(_)
        )
    }

    /// Reports whether this value is a primitive floating-point value.
    ///
    /// # Returns
    ///
    /// `true` for `f32` and `f64` values.
    #[inline]
    #[must_use]
    pub fn is_float(self) -> bool {
        matches!(self.inner, NumberRepr::Float32(_) | NumberRepr::Float64(_))
    }

    /// Reports whether this value is an arbitrary-precision integer.
    ///
    /// # Returns
    ///
    /// `true` for `BigInt` values when the `big-integer` feature is enabled;
    /// otherwise, `false`.
    #[inline]
    #[must_use]
    pub fn is_big_integer(self) -> bool {
        #[cfg(feature = "big-integer")]
        {
            matches!(self.inner, NumberRepr::BigInteger(_))
        }
        #[cfg(not(feature = "big-integer"))]
        {
            false
        }
    }

    /// Reports whether this value is an arbitrary-precision decimal.
    ///
    /// # Returns
    ///
    /// `true` for `BigDecimal` values when the `big-decimal` feature is
    /// enabled; otherwise, `false`.
    #[inline]
    #[must_use]
    pub fn is_big_decimal(self) -> bool {
        #[cfg(feature = "big-decimal")]
        {
            matches!(self.inner, NumberRepr::BigDecimal(_))
        }
        #[cfg(not(feature = "big-decimal"))]
        {
            false
        }
    }

    /// Reports whether this value is NaN.
    ///
    /// # Returns
    ///
    /// `true` only for a primitive NaN payload.
    #[inline]
    #[must_use]
    pub fn is_nan(self) -> bool {
        match self.inner {
            NumberRepr::Float32(value) => value.is_nan(),
            NumberRepr::Float64(value) => value.is_nan(),
            _ => false,
        }
    }

    /// Reports whether this value is an infinite primitive float.
    ///
    /// # Returns
    ///
    /// `true` for positive or negative infinity; otherwise, `false`.
    #[inline]
    #[must_use]
    pub fn is_infinite(self) -> bool {
        match self.inner {
            NumberRepr::Float32(value) => value.is_infinite(),
            NumberRepr::Float64(value) => value.is_infinite(),
            _ => false,
        }
    }

    /// Reports whether this value is finite.
    ///
    /// # Returns
    ///
    /// `true` for all integers, arbitrary-precision values, and finite
    /// primitive floats; otherwise, `false`.
    #[inline]
    #[must_use]
    pub fn is_finite(self) -> bool {
        !self.is_nan() && !self.is_infinite()
    }

    /// Reports whether this value is mathematically zero.
    ///
    /// # Returns
    ///
    /// `true` for integer zero and both positive and negative floating-point
    /// zero; otherwise, `false`.
    #[must_use]
    pub fn is_zero(self) -> bool {
        match self.inner {
            NumberRepr::Int8(value) => value == 0,
            NumberRepr::Int16(value) => value == 0,
            NumberRepr::Int32(value) => value == 0,
            NumberRepr::Int64(value) => value == 0,
            NumberRepr::Int128(value) => value == 0,
            NumberRepr::UInt8(value) => value == 0,
            NumberRepr::UInt16(value) => value == 0,
            NumberRepr::UInt32(value) => value == 0,
            NumberRepr::UInt64(value) => value == 0,
            NumberRepr::UInt128(value) => value == 0,
            NumberRepr::Float32(value) => value == 0.0,
            NumberRepr::Float64(value) => value == 0.0,
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => value.is_zero(),
            #[cfg(feature = "big-decimal")]
            NumberRepr::BigDecimal(value) => value.is_zero(),
            #[cfg(not(any(feature = "big-integer", feature = "big-decimal")))]
            NumberRepr::Lifetime(_, impossible) => match impossible {},
        }
    }

    /// Reports whether this value is greater than zero.
    ///
    /// # Returns
    ///
    /// `true` for positive finite or infinite values; zero, negative values,
    /// and NaN return `false`.
    #[must_use]
    pub fn is_positive(self) -> bool {
        match self.inner {
            NumberRepr::Int8(value) => value > 0,
            NumberRepr::Int16(value) => value > 0,
            NumberRepr::Int32(value) => value > 0,
            NumberRepr::Int64(value) => value > 0,
            NumberRepr::Int128(value) => value > 0,
            NumberRepr::UInt8(value) => value > 0,
            NumberRepr::UInt16(value) => value > 0,
            NumberRepr::UInt32(value) => value > 0,
            NumberRepr::UInt64(value) => value > 0,
            NumberRepr::UInt128(value) => value > 0,
            NumberRepr::Float32(value) => value > 0.0,
            NumberRepr::Float64(value) => value > 0.0,
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => value.is_positive(),
            #[cfg(feature = "big-decimal")]
            NumberRepr::BigDecimal(value) => value.is_positive(),
            #[cfg(not(any(feature = "big-integer", feature = "big-decimal")))]
            NumberRepr::Lifetime(_, impossible) => match impossible {},
        }
    }

    /// Reports whether this value is less than zero.
    ///
    /// # Returns
    ///
    /// `true` for negative finite or infinite values; zero, positive values,
    /// and NaN return `false`.
    #[must_use]
    pub fn is_negative(self) -> bool {
        match self.inner {
            NumberRepr::Int8(value) => value < 0,
            NumberRepr::Int16(value) => value < 0,
            NumberRepr::Int32(value) => value < 0,
            NumberRepr::Int64(value) => value < 0,
            NumberRepr::Int128(value) => value < 0,
            NumberRepr::UInt8(_) => false,
            NumberRepr::UInt16(_) => false,
            NumberRepr::UInt32(_) => false,
            NumberRepr::UInt64(_) => false,
            NumberRepr::UInt128(_) => false,
            NumberRepr::Float32(value) => value < 0.0,
            NumberRepr::Float64(value) => value < 0.0,
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => value.is_negative(),
            #[cfg(feature = "big-decimal")]
            NumberRepr::BigDecimal(value) => value.is_negative(),
            #[cfg(not(any(feature = "big-integer", feature = "big-decimal")))]
            NumberRepr::Lifetime(_, impossible) => match impossible {},
        }
    }

    /// Compares this value with `right` under an explicit numeric policy.
    ///
    /// Fixed-width comparisons do not require heap allocation. Some paths
    /// involving `BigInt` or `BigDecimal` may clone coefficients or construct
    /// exact rational or decimal values, with cost depending on the operand
    /// representations. Direct comparisons between some large-number
    /// representations avoid that work. Conversion limits and session budgets
    /// do not apply to this independent comparison; constrain untrusted number
    /// representations at the input boundary when their size must be bounded.
    ///
    /// See the [type-level examples](Self) for exact, approximate, and NaN
    /// comparisons. Approximate comparison is not transitive across mixed
    /// representations; do not use it for sorting or ordered keys.
    ///
    /// # Parameters
    ///
    /// * `right` - Right numeric operand.
    /// * `policy` - Exact or approximate comparison policy.
    ///
    /// # Returns
    ///
    /// The numeric ordering, or `None` when either operand is NaN.
    pub fn compare(self, right: NumberRef<'_>, policy: NumericComparisonPolicy) -> Option<Ordering> {
        if self.is_nan() || right.is_nan() {
            return None;
        }
        match (self.is_infinite(), right.is_infinite()) {
            (true, true) => {
                return Some(if self.is_negative() == right.is_negative() {
                    Ordering::Equal
                } else if self.is_negative() {
                    Ordering::Less
                } else {
                    Ordering::Greater
                });
            }
            (true, false) => {
                return Some(if self.is_negative() {
                    Ordering::Less
                } else {
                    Ordering::Greater
                });
            }
            (false, true) => {
                return Some(if right.is_negative() {
                    Ordering::Greater
                } else {
                    Ordering::Less
                });
            }
            (false, false) => {}
        }
        if policy == NumericComparisonPolicy::Approximate
            && (self.is_float() || right.is_float())
            && let (Some(left), Some(right)) = (self.to_approximate_f64(), right.to_approximate_f64())
            && left.is_finite()
            && right.is_finite()
        {
            return left.partial_cmp(&right);
        }
        #[cfg(any(feature = "big-integer", feature = "big-decimal"))]
        {
            #[cfg(feature = "big-integer")]
            let has_big_integer = self.is_big_integer() || right.is_big_integer();
            #[cfg(not(feature = "big-integer"))]
            let has_big_integer = false;
            #[cfg(feature = "big-decimal")]
            let has_big_decimal = self.is_big_decimal() || right.is_big_decimal();
            #[cfg(not(feature = "big-decimal"))]
            let has_big_decimal = false;
            if has_big_integer || has_big_decimal {
                #[cfg(feature = "big-decimal")]
                if policy == NumericComparisonPolicy::Exact
                    && self.is_big_decimal() != right.is_big_decimal()
                    && let Some(ordering) = self.compare_zero_or_opposite_sign(right)
                {
                    return Some(ordering);
                }
                return self.compare_exact_rational(right);
            }
        }
        self.compare_fixed(right)
    }

    /// Compares mixed numeric representations when zero or opposite signs
    /// determine their ordering without constructing exact rational values.
    ///
    /// # Parameters
    ///
    /// * `right` - Right numeric operand.
    ///
    /// # Returns
    ///
    /// The exact ordering when either value is zero or their nonzero signs
    /// differ; otherwise, `None`.
    #[cfg(feature = "big-decimal")]
    fn compare_zero_or_opposite_sign(self, right: NumberRef<'_>) -> Option<Ordering> {
        let left_zero = self.is_zero();
        let right_zero = right.is_zero();
        if left_zero {
            return Some(if right_zero {
                Ordering::Equal
            } else if right.is_negative() {
                Ordering::Greater
            } else {
                Ordering::Less
            });
        }
        if right_zero {
            return Some(if self.is_negative() {
                Ordering::Less
            } else {
                Ordering::Greater
            });
        }
        if self.is_negative() != right.is_negative() {
            return Some(if self.is_negative() {
                Ordering::Less
            } else {
                Ordering::Greater
            });
        }
        None
    }

    /// Returns the private representation for numeric algorithms.
    ///
    /// # Returns
    ///
    /// The crate-private `NumberRepr` payload borrowed or copied by this value.
    #[inline]
    pub(in crate::numeric) const fn inner(self) -> NumberRepr<'a> {
        self.inner
    }

    /// Compares arbitrary-precision pairs through exact rational values.
    ///
    /// Decimal scales that cannot be materialized as a practical power of ten
    /// fall back to `BigDecimal`'s exact scale-aware ordering.
    ///
    /// # Parameters
    ///
    /// * `right` - Right arbitrary-precision operand.
    ///
    /// # Returns
    ///
    /// Their exact mathematical ordering, or `None` for non-finite values.
    #[cfg(any(feature = "big-integer", feature = "big-decimal"))]
    fn compare_exact_rational(self, right: NumberRef<'_>) -> Option<Ordering> {
        #[cfg(feature = "big-integer")]
        if let (NumberRepr::BigInteger(left), NumberRepr::BigInteger(right)) = (self.inner, right.inner) {
            return Some(left.cmp(right));
        }
        #[cfg(feature = "big-integer")]
        if let Some(ordering) = self.compare_big_integer_fixed(right) {
            return Some(ordering);
        }
        #[cfg(feature = "big-integer")]
        if let Some(ordering) = self.compare_big_integer_float(right) {
            return Some(ordering);
        }
        #[cfg(feature = "big-decimal")]
        if let (NumberRepr::BigDecimal(left), NumberRepr::BigDecimal(right)) = (self.inner, right.inner) {
            return Some(left.cmp(right));
        }
        match (self.to_exact_rational(), right.to_exact_rational()) {
            (Some(left), Some(right)) => Some(left.cmp(&right)),
            #[cfg(feature = "big-decimal")]
            _ => self.compare_exact_decimal(right),
            #[cfg(not(feature = "big-decimal"))]
            _ => None,
        }
    }

    /// Compares a `BigInt` directly with a fixed-width integer.
    ///
    /// # Parameters
    ///
    /// * `right` - Right numeric operand.
    ///
    /// # Returns
    ///
    /// The ordering when the pair contains a `BigInt` and no floating-point
    /// or decimal value; otherwise, `None`.
    #[cfg(feature = "big-integer")]
    #[inline]
    fn compare_big_integer_fixed(self, right: NumberRef<'_>) -> Option<Ordering> {
        match (self.inner, right.inner) {
            (NumberRepr::BigInteger(left), right) => compare_big_integer_to_fixed(left, right),
            (left, NumberRepr::BigInteger(right)) => compare_big_integer_to_fixed(right, left).map(Ordering::reverse),
            _ => None,
        }
    }

    /// Compares a `BigInt` directly with a finite floating-point value when
    /// zero, sign, or highest-bit ordering determines the result.
    #[cfg(feature = "big-integer")]
    #[inline]
    fn compare_big_integer_float(self, right: NumberRef<'_>) -> Option<Ordering> {
        match (self.inner, right.inner) {
            (NumberRepr::BigInteger(left), NumberRepr::Float32(_) | NumberRepr::Float64(_)) => {
                compare_big_integer_float(left, right)
            }
            (NumberRepr::Float32(_) | NumberRepr::Float64(_), NumberRepr::BigInteger(right)) => {
                compare_big_integer_float(right, self).map(Ordering::reverse)
            }
            _ => None,
        }
    }

    /// Compares values through exact arbitrary-precision decimal
    /// representations.
    ///
    /// # Parameters
    ///
    /// * `right` - Right numeric operand.
    ///
    /// # Returns
    ///
    /// Their mathematical ordering, or `None` when either operand is
    /// non-finite.
    #[cfg(feature = "big-decimal")]
    #[inline]
    fn compare_exact_decimal(self, right: NumberRef<'_>) -> Option<Ordering> {
        Some(self.to_exact_decimal()?.cmp(&right.to_exact_decimal()?))
    }

    /// Compares two finite fixed-width numeric values exactly.
    ///
    /// # Parameters
    ///
    /// * `right` - Right fixed-width operand.
    ///
    /// # Returns
    ///
    /// Their mathematical ordering, or `None` for a non-finite or unsupported
    /// input.
    fn compare_fixed(self, right: NumberRef<'_>) -> Option<Ordering> {
        let (left_negative, left_significand, left_exponent) = finite_parts(self)?;
        let (right_negative, right_significand, right_exponent) = finite_parts(right)?;
        if left_significand == 0 && right_significand == 0 {
            return Some(Ordering::Equal);
        }
        match left_negative.cmp(&right_negative) {
            Ordering::Less => Some(Ordering::Greater),
            Ordering::Greater => Some(Ordering::Less),
            Ordering::Equal => {
                let ordering = compare_magnitude(left_significand, left_exponent, right_significand, right_exponent);
                Some(if left_negative { ordering.reverse() } else { ordering })
            }
        }
    }

    /// Projects this value to `f64` for approximate comparison.
    ///
    /// Fixed-width integers and primitive floats convert by widening or
    /// casting. Arbitrary-precision values use `ToPrimitive::to_f64`, which
    /// may lose precision or return `None` when the magnitude cannot be
    /// represented or a decimal scale cannot be safely projected.
    ///
    /// # Returns
    ///
    /// The approximate `f64` projection, or `None` when an arbitrary-precision
    /// value cannot be represented as `f64` or a decimal scale cannot be
    /// safely projected.
    fn to_approximate_f64(self) -> Option<f64> {
        match self.inner {
            NumberRepr::Int8(value) => Some(f64::from(value)),
            NumberRepr::Int16(value) => Some(f64::from(value)),
            NumberRepr::Int32(value) => Some(f64::from(value)),
            NumberRepr::Int64(value) => Some(value as f64),
            NumberRepr::Int128(value) => Some(value as f64),
            NumberRepr::UInt8(value) => Some(f64::from(value)),
            NumberRepr::UInt16(value) => Some(f64::from(value)),
            NumberRepr::UInt32(value) => Some(f64::from(value)),
            NumberRepr::UInt64(value) => Some(value as f64),
            NumberRepr::UInt128(value) => Some(value as f64),
            NumberRepr::Float32(value) => Some(f64::from(value)),
            NumberRepr::Float64(value) => Some(value),
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => value.to_f64(),
            #[cfg(feature = "big-decimal")]
            NumberRepr::BigDecimal(value) => {
                let (coefficient, scale) = value.as_bigint_and_scale();
                // The coefficient bit count bounds the scale reduction conservatively.
                let max_scale_reduction = i64::try_from(coefficient.bits()).ok()?;
                scale.checked_sub(max_scale_reduction)?;
                value.to_f64()
            }
            #[cfg(not(any(feature = "big-integer", feature = "big-decimal")))]
            NumberRepr::Lifetime(_, impossible) => match impossible {},
        }
    }

    /// Converts this finite numeric value into an exact rational.
    ///
    /// # Returns
    ///
    /// The exact mathematical value, or `None` for non-finite values or an
    /// impractically large decimal scale.
    #[cfg(any(feature = "big-integer", feature = "big-decimal"))]
    fn to_exact_rational(self) -> Option<BigRational> {
        match self.inner {
            NumberRepr::Int8(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::Int16(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::Int32(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::Int64(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::Int128(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::UInt8(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::UInt16(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::UInt32(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::UInt64(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::UInt128(value) => Some(BigRational::from_integer(BigInt::from(value))),
            NumberRepr::Float32(value) => Some(f32_rational(value)),
            NumberRepr::Float64(value) => Some(f64_rational(value)),
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => Some(BigRational::from_integer(value.clone())),
            #[cfg(feature = "big-decimal")]
            NumberRepr::BigDecimal(value) => decimal_rational(value),
        }
    }

    /// Converts this finite numeric value into an exact arbitrary-precision
    /// decimal.
    ///
    /// `BigDecimal`'s primitive-float conversion decodes the IEEE significand
    /// and exponent exactly; it does not use display formatting.
    ///
    /// # Returns
    ///
    /// The exact decimal value, or `None` for a non-finite primitive float.
    #[cfg(feature = "big-decimal")]
    fn to_exact_decimal(self) -> Option<BigDecimal> {
        match self.inner {
            NumberRepr::Int8(value) => Some(BigDecimal::from(value)),
            NumberRepr::Int16(value) => Some(BigDecimal::from(value)),
            NumberRepr::Int32(value) => Some(BigDecimal::from(value)),
            NumberRepr::Int64(value) => Some(BigDecimal::from(value)),
            NumberRepr::Int128(value) => Some(BigDecimal::from(value)),
            NumberRepr::UInt8(value) => Some(BigDecimal::from(value)),
            NumberRepr::UInt16(value) => Some(BigDecimal::from(value)),
            NumberRepr::UInt32(value) => Some(BigDecimal::from(value)),
            NumberRepr::UInt64(value) => Some(BigDecimal::from(value)),
            NumberRepr::UInt128(value) => Some(BigDecimal::from(value)),
            NumberRepr::Float32(value) => BigDecimal::try_from(value).ok(),
            NumberRepr::Float64(value) => BigDecimal::try_from(value).ok(),
            #[cfg(feature = "big-integer")]
            NumberRepr::BigInteger(value) => Some(BigDecimal::from(value.clone())),
            NumberRepr::BigDecimal(value) => Some(value.clone()),
        }
    }
}