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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
use crate::error::IntegerError;

use musli::Context;

use crate::parser::Parser;

use self::traits::FromUnsigned;
pub(crate) use self::traits::{Float, Signed, Unsigned};

/// Fully deconstructed parts of a signed number.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub(crate) struct SignedPartsBase<T>
where
    T: Signed,
{
    /// If the number is negative.
    pub(crate) is_negative: bool,
    /// The unsigned component of the number.
    pub(crate) unsigned: T::Unsigned,
}

impl<T> SignedPartsBase<T>
where
    T: Signed,
{
    pub(crate) fn compute(self) -> Result<T, IntegerError> {
        let Self {
            is_negative,
            unsigned,
        } = self;

        match if is_negative {
            unsigned.negate()
        } else {
            unsigned.signed()
        } {
            Some(value) => Ok(value),
            None => Err(IntegerError::IntegerOverflow),
        }
    }
}

/// Fully deconstructed parts of a signed number.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub(crate) struct SignedPartsFull<T>
where
    T: Signed,
{
    /// If the number is negative.
    pub(crate) is_negative: bool,
    /// The unsigned component of the number.
    pub(crate) unsigned: Parts<T::Unsigned>,
}

impl<T> SignedPartsFull<T>
where
    T: Signed,
{
    #[inline(always)]
    pub(crate) fn compute(self) -> Result<T, IntegerError> {
        let Self {
            is_negative,
            unsigned: parts,
        } = self;

        let value = parts.compute()?;

        match if is_negative {
            value.negate()
        } else {
            value.signed()
        } {
            Some(value) => Ok(value),
            None => Err(IntegerError::IntegerOverflow),
        }
    }

    #[inline(always)]
    pub(crate) fn compute_float<F>(self) -> F
    where
        F: Float,
        F: FromUnsigned<T::Unsigned>,
    {
        let Self {
            is_negative,
            unsigned: parts,
        } = self;
        let value = parts.compute_float::<F>();

        if is_negative {
            value.negate()
        } else {
            value
        }
    }
}

/// The mantissa, or anything after a decimal point.
#[derive(Clone, Copy)]
pub(crate) struct Mantissa<T> {
    /// The value of the mantissa.
    value: T,
    /// The exponent of the mantissa.
    exp: i32,
}

impl<T> Mantissa<T>
where
    T: Unsigned,
{
    fn into_float<F>(self) -> Mantissa<F>
    where
        F: FromUnsigned<T>,
    {
        Mantissa {
            value: self.value.into_float::<F>(),
            exp: self.exp,
        }
    }
}

impl<F> Mantissa<F>
where
    F: Float,
{
    /// Compute as float with a negative exponent.
    #[inline]
    fn compute_float(self, e: i32) -> F {
        self.value.pow10(e - self.exp)
    }
}

impl<T> Default for Mantissa<T>
where
    T: Unsigned,
{
    fn default() -> Self {
        Self {
            value: T::ZERO,
            exp: 0i32,
        }
    }
}

/// Fully deconstructed parts of an unsigned number.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub(crate) struct Parts<T> {
    /// The base, or everything before a decimal point.
    pub(crate) base: T,
    /// The mantissa, or anything after a decimal point.
    pub(crate) m: Mantissa<T>,
    /// The exponent of the number.
    pub(crate) e: i32,
}

impl<T> Parts<T>
where
    T: Unsigned,
{
    #[inline(always)]
    pub(crate) fn compute(self) -> Result<T, IntegerError> {
        macro_rules! check {
            ($expr:expr, $kind:ident) => {
                match $expr {
                    Some(value) => value,
                    None => return Err(IntegerError::$kind),
                }
            };
        }

        let Self { mut base, m, e } = self;

        if e == 0 {
            if !m.value.is_zero() {
                return Err(IntegerError::Decimal);
            }

            return Ok(base);
        }

        if e >= 0 {
            // Decoding the specified mantissa would result in a fractional number.
            let mantissa_exp = check!(e.checked_sub(m.exp).filter(|n| *n >= 0), Decimal) as u32;

            if !base.is_zero() {
                base = check!(base.checked_pow10(e as u32), IntegerOverflow);
            }

            let base = check! {
                m.value
                    .checked_pow10(mantissa_exp)
                    .and_then(|m| base.checked_add(m)),
                IntegerOverflow
            };

            Ok(base)
        } else if !m.value.is_zero() {
            Err(IntegerError::Decimal)
        } else {
            Ok(check!(base.checked_neg_pow10(-e as u32), Decimal))
        }
    }

    #[inline(always)]
    pub(crate) fn compute_float<F>(self) -> F
    where
        F: Float,
        F: FromUnsigned<T>,
    {
        let Self { base, m, e } = self;
        base.into_float::<F>().pow10(e) + m.into_float::<F>().compute_float(e)
    }
}

/// Implementation to skip over a well-formed JSON number.
pub(crate) fn skip_number<'de, P, C>(cx: &C, mut p: P) -> Result<(), C::Error>
where
    P: Parser<'de>,
    C: ?Sized + Context,
{
    p.skip_whitespace(cx)?;

    let start = cx.mark();

    if p.peek_byte(cx)? == Some(b'-') {
        p.skip(cx, 1)?;
    }

    match p.read_byte(cx)? {
        b'0' => (),
        b if is_digit_nonzero(b) => {
            p.consume_while(cx, is_digit)?;
        }
        _ => {
            return Err(cx.marked_message(start, IntegerError::InvalidNumeric));
        }
    }

    if p.peek_byte(cx)? == Some(b'.') {
        p.skip(cx, 1)?;
        p.consume_while(cx, is_digit)?;
    }

    if matches!(p.peek_byte(cx)?, Some(b'e') | Some(b'E')) {
        p.skip(cx, 1)?;

        match p.peek_byte(cx)? {
            Some(b'-') => {
                p.skip(cx, 1)?;
            }
            Some(b'+') => {
                p.skip(cx, 1)?;
            }
            _ => (),
        };

        p.consume_while(cx, is_digit)?;
    }

    Ok(())
}

/// Partially parse an unsigned value.
#[cfg_attr(feature = "parse-full", allow(unused))]
#[inline(never)]
pub(crate) fn parse_unsigned_base<'de, T, C, P>(cx: &C, mut p: P) -> Result<T, C::Error>
where
    T: Unsigned,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    p.skip_whitespace(cx)?;

    let start = cx.mark();
    decode_unsigned_base::<T, _, _>(cx, p, start)
}

/// Fully parse an unsigned value.
#[cfg_attr(not(feature = "parse-full"), allow(unused))]
#[inline(never)]
pub(crate) fn parse_unsigned_full<'de, T, C, P>(cx: &C, mut p: P) -> Result<T, C::Error>
where
    T: Unsigned,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    p.skip_whitespace(cx)?;

    let start = cx.mark();

    match decode_unsigned_full(cx, p, start)?.compute() {
        Ok(value) => Ok(value),
        Err(error) => Err(cx.marked_message(start, error)),
    }
}

/// Decode a signed integer.
#[inline(always)]
fn decode_signed_base<'de, T, C, P>(cx: &C, mut p: P) -> Result<SignedPartsBase<T>, C::Error>
where
    C: ?Sized + Context,
    T: Signed,
    P: Parser<'de>,
{
    let start = cx.mark();

    let is_negative = if p.peek_byte(cx)? == Some(b'-') {
        p.skip(cx, 1)?;
        true
    } else {
        false
    };

    let unsigned = decode_unsigned_base::<T::Unsigned, _, _>(cx, p, start)?;

    Ok(SignedPartsBase {
        is_negative,
        unsigned,
    })
}

/// Decode a full signed integer.
pub(crate) fn decode_signed_full<'de, T, C, P>(
    cx: &C,
    p: &mut P,
) -> Result<SignedPartsFull<T>, C::Error>
where
    C: ?Sized + Context,
    T: Signed,
    P: ?Sized + Parser<'de>,
{
    p.skip_whitespace(cx)?;

    decode_signed_full_inner(cx, p)
}

/// Decode a full signed integer.
#[inline(always)]
fn decode_signed_full_inner<'de, T, C, P>(cx: &C, mut p: P) -> Result<SignedPartsFull<T>, C::Error>
where
    C: ?Sized + Context,
    T: Signed,
    P: Parser<'de>,
{
    let start = cx.mark();

    let is_negative = if p.peek_byte(cx)? == Some(b'-') {
        p.skip(cx, 1)?;
        true
    } else {
        false
    };

    let parts = decode_unsigned_full::<T::Unsigned, _, _>(cx, p, start)?;

    Ok(SignedPartsFull {
        is_negative,
        unsigned: parts,
    })
}

/// Fully parse a signed value.
#[cfg_attr(feature = "parse-full", allow(unused))]
#[inline(never)]
pub(crate) fn parse_signed_base<'de, T, C, P>(cx: &C, mut p: P) -> Result<T, C::Error>
where
    T: Signed,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    p.skip_whitespace(cx)?;

    let start = cx.mark();

    match decode_signed_base(cx, p)?.compute() {
        Ok(value) => Ok(value),
        Err(error) => Err(cx.marked_message(start, error)),
    }
}

/// Fully parse a signed value.
#[cfg_attr(not(feature = "parse-full"), allow(unused))]
#[inline(never)]
pub(crate) fn parse_signed_full<'de, T, C, P>(cx: &C, mut p: P) -> Result<T, C::Error>
where
    T: Signed,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    p.skip_whitespace(cx)?;

    let start = cx.mark();

    match decode_signed_full_inner(cx, p)?.compute() {
        Ok(value) => Ok(value),
        Err(error) => Err(cx.marked_message(start, error)),
    }
}

/// Generically decode a single (whole) integer from a stream of bytes abiding
/// by JSON convention for format.
#[inline(always)]
fn decode_unsigned_base<'de, T, C, P>(cx: &C, mut p: P, start: C::Mark) -> Result<T, C::Error>
where
    T: Unsigned,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    let base = match p.read_byte(cx)? {
        b'0' => T::ZERO,
        b if is_digit_nonzero(b) => {
            let mut base = T::from_byte(b - b'0');

            while let Some(true) = p.peek_byte(cx)?.map(is_digit) {
                base = digit(cx, base, p.borrow_mut(), start)?;
            }

            base
        }
        _ => {
            return Err(cx.marked_message(start, IntegerError::InvalidNumeric));
        }
    };

    Ok(base)
}

/// Generically decode a single (whole) integer from a stream of bytes abiding
/// by JSON convention for format.
#[inline(always)]
fn decode_unsigned_full<'de, T, C, P>(
    cx: &C,
    mut p: P,
    start: C::Mark,
) -> Result<Parts<T>, C::Error>
where
    T: Unsigned,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    let base = decode_unsigned_base(cx, p.borrow_mut(), start)?;

    let mut m = Mantissa::<T>::default();

    if let Some(b'.') = p.peek_byte(cx)? {
        p.skip(cx, 1)?;

        // NB: we use unchecked operations over mantissa_exp since the mantissa
        // for any supported type would overflow long before this.
        m.exp = m.exp.wrapping_add(decode_zeros(cx, p.borrow_mut())?);

        // Stored zeros so that the last segment of zeros can be ignored since
        // they have no bearing on the value of the integer.
        let mut zeros = 0;

        while let Some(true) = p.peek_byte(cx)?.map(is_digit) {
            // Accrue accumulated zeros.
            if zeros > 0 {
                m.exp += zeros;
                m.value = match m.value.checked_pow10(zeros as u32) {
                    Some(mantissa) => mantissa,
                    None => {
                        return Err(cx.marked_message(start, IntegerError::IntegerOverflow));
                    }
                };
            }

            m.exp += 1;
            m.value = digit(cx, m.value, p.borrow_mut(), start)?;
            zeros = decode_zeros(cx, p.borrow_mut())?;
        }
    }

    let e = if matches!(p.peek_byte(cx)?, Some(b'e' | b'E')) {
        p.skip(cx, 1)?;
        decode_exponent(cx, p, start)?
    } else {
        0
    };

    Ok(Parts { base, m, e })
}

/// Decode an exponent.
#[inline(always)]
fn decode_exponent<'de, P, C>(cx: &C, mut p: P, start: C::Mark) -> Result<i32, C::Error>
where
    P: Parser<'de>,
    C: ?Sized + Context,
{
    let mut is_negative = false;
    let mut e = 0u32;

    match p.peek_byte(cx)? {
        Some(b'-') => {
            p.skip(cx, 1)?;
            is_negative = true
        }
        Some(b'+') => {
            p.skip(cx, 1)?;
        }
        _ => (),
    };

    while let Some(true) = p.peek_byte(cx)?.map(is_digit) {
        e = digit(cx, e, p.borrow_mut(), start)?;
    }

    match if is_negative { e.negate() } else { e.signed() } {
        Some(value) => Ok(value),
        None => Err(cx.marked_message(start, IntegerError::IntegerOverflow)),
    }
}

/// Decode a single digit into `out`.
#[inline(always)]
fn digit<'de, T, C, P>(cx: &C, out: T, mut p: P, start: C::Mark) -> Result<T, C::Error>
where
    T: Unsigned,
    P: Parser<'de>,
    C: ?Sized + Context,
{
    let Some(out) = out.checked_mul10() else {
        return Err(cx.marked_message(start, IntegerError::IntegerOverflow));
    };

    Ok(out + T::from_byte(p.read_byte(cx)? - b'0'))
}

/// Decode sequence of zeros.
#[inline(always)]
fn decode_zeros<'de, P, C>(cx: &C, mut p: P) -> Result<i32, C::Error>
where
    P: Parser<'de>,
    C: ?Sized + Context,
{
    let mut count = 0i32;

    while let Some(b'0') = p.peek_byte(cx)? {
        count = count.wrapping_add(1);
        p.skip(cx, 1)?;
    }

    Ok(count)
}

// Test if b is numeric.
#[inline]
fn is_digit(b: u8) -> bool {
    b.is_ascii_digit()
}

// Test if b is numeric.
#[inline(always)]
fn is_digit_nonzero(b: u8) -> bool {
    (b'1'..=b'9').contains(&b)
}

mod traits {
    use core::fmt;
    use core::ops::{Add, Not};

    pub(crate) trait Unsigned: Sized + fmt::Debug + Add<Self, Output = Self> {
        type Signed: Signed<Unsigned = Self>;

        const ZERO: Self;

        fn from_byte(b: u8) -> Self;

        fn is_zero(&self) -> bool;

        /// Calculate `self * 10 ** e`.
        fn checked_pow10(self, exp: u32) -> Option<Self>;

        /// Calculate `self / 10 ** e`.
        fn checked_neg_pow10(self, e: u32) -> Option<Self>;

        fn checked_mul10(self) -> Option<Self>;

        fn checked_add(self, other: Self) -> Option<Self>;

        fn checked_pow(self, exp: u32) -> Option<Self>;

        fn negate(self) -> Option<Self::Signed>;

        fn signed(self) -> Option<Self::Signed>;

        fn into_float<F>(self) -> F
        where
            F: FromUnsigned<Self>;
    }

    pub(crate) trait Signed: Sized + fmt::Debug {
        type Unsigned: Unsigned<Signed = Self>;
    }

    pub(crate) trait FromUnsigned<T> {
        fn from_unsigned(value: T) -> Self;
    }

    pub(crate) trait Float: Sized + Add<Self, Output = Self> {
        fn negate(self) -> Self;

        fn pow10(self, e: i32) -> Self;
    }

    macro_rules! count {
        (()) => { 0 };
        ((_)) => { 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 };

        (($($s:tt)*) $first:tt $($tt:tt)*) => {
            count!(($($s)* _) $($tt)*)
        };
    }

    macro_rules! unsigned {
        ($unsigned:ty, $signed:ty, [$($pows:literal),* $(,)?]) => {
            impl Unsigned for $unsigned {
                type Signed = $signed;

                const ZERO: Self = 0;

                #[inline(always)]
                fn from_byte(b: u8) -> Self {
                    b as $unsigned
                }

                #[inline(always)]
                fn is_zero(&self) -> bool {
                    *self == 0
                }

                #[inline(always)]
                fn checked_pow10(self, e: u32) -> Option<Self> {
                    static POWS: [$unsigned; count!(() $($pows)*)] = [
                        $($pows),*
                    ];

                    let n = if let Some(e) = POWS.get(e as usize) {
                        *e
                    } else {
                        10.checked_pow(e)?
                    };

                    self.checked_mul(n)
                }

                #[inline(always)]
                fn checked_neg_pow10(self, e: u32) -> Option<Self> {
                    const ONE: $unsigned = 1;
                    let div = ONE.checked_pow10(e)?;

                    if self % div != 0 {
                        None
                    } else {
                        Some(self / div)
                    }
                }

                #[inline(always)]
                fn checked_mul10(self) -> Option<Self> {
                    self.checked_mul(10)
                }

                #[inline(always)]
                fn checked_add(self, other: Self) -> Option<Self> {
                    <$unsigned>::checked_add(self, other)
                }

                #[inline(always)]
                fn checked_pow(self, exp: u32) -> Option<Self> {
                    <$unsigned>::checked_pow(self, exp)
                }

                #[inline(always)]
                fn negate(self) -> Option<Self::Signed> {
                    if self > (<$unsigned>::MAX >> 1) + 1 {
                        None
                    } else {
                        Some(self.not().wrapping_add(1) as $signed)
                    }
                }

                #[inline(always)]
                fn signed(self) -> Option<Self::Signed> {
                    if self > <$unsigned>::MAX >> 1 {
                        None
                    } else {
                        Some(self as $signed)
                    }
                }

                #[inline(always)]
                fn into_float<F>(self) -> F where F: FromUnsigned<Self> {
                    F::from_unsigned(self)
                }
            }

            impl Signed for $signed {
                type Unsigned = $unsigned;
            }
        };
    }

    unsigned!(u8, i8, [1, 10, 100,]);

    unsigned!(u16, i16, [1, 10, 100, 1000, 10000,]);

    unsigned!(
        u32,
        i32,
        [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,]
    );

    unsigned!(
        u64,
        i64,
        [
            1,
            10,
            100,
            1000,
            10000,
            100000,
            1000000,
            10000000,
            100000000,
            1000000000,
            10000000000,
            100000000000,
            1000000000000,
            10000000000000,
            100000000000000,
            1000000000000000,
            10000000000000000,
            100000000000000000,
            1000000000000000000,
            10000000000000000000,
        ]
    );

    unsigned!(
        u128,
        i128,
        [
            1,
            10,
            100,
            1000,
            10000,
            100000,
            1000000,
            10000000,
            100000000,
            1000000000,
            10000000000,
            100000000000,
            1000000000000,
            10000000000000,
            100000000000000,
            1000000000000000,
            10000000000000000,
            100000000000000000,
            1000000000000000000,
            10000000000000000000,
            100000000000000000000,
            1000000000000000000000,
            10000000000000000000000,
            100000000000000000000000,
            1000000000000000000000000,
            10000000000000000000000000,
            100000000000000000000000000,
            1000000000000000000000000000,
            10000000000000000000000000000,
            100000000000000000000000000000,
            1000000000000000000000000000000,
            10000000000000000000000000000000,
        ]
    );

    #[cfg(target_pointer_width = "32")]
    unsigned!(
        usize,
        isize,
        [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,]
    );

    #[cfg(target_pointer_width = "64")]
    unsigned!(
        usize,
        isize,
        [
            1,
            10,
            100,
            1000,
            10000,
            100000,
            1000000,
            10000000,
            100000000,
            1000000000,
            10000000000,
            100000000000,
            1000000000000,
            10000000000000,
            100000000000000,
            1000000000000000,
            10000000000000000,
            100000000000000000,
            1000000000000000000,
            10000000000000000000,
        ]
    );

    macro_rules! float {
        ($float:ty, $fallback:path) => {
            impl Float for $float {
                #[inline]
                fn negate(self) -> Self {
                    -self
                }

                #[inline]
                #[cfg(feature = "std")]
                fn pow10(self, e: i32) -> Self {
                    self * <$float>::powi(10.0, e)
                }

                #[inline]
                #[cfg(not(feature = "std"))]
                fn pow10(self, e: i32) -> Self {
                    self * $fallback(10.0, e)
                }
            }

            impl FromUnsigned<u8> for $float {
                fn from_unsigned(value: u8) -> Self {
                    value as $float
                }
            }

            impl FromUnsigned<u16> for $float {
                fn from_unsigned(value: u16) -> Self {
                    value as $float
                }
            }

            impl FromUnsigned<u32> for $float {
                fn from_unsigned(value: u32) -> Self {
                    value as $float
                }
            }

            impl FromUnsigned<u64> for $float {
                fn from_unsigned(value: u64) -> Self {
                    value as $float
                }
            }

            impl FromUnsigned<u128> for $float {
                fn from_unsigned(value: u128) -> Self {
                    value as $float
                }
            }
        };
    }

    float!(f32, self::no_std::powf32);
    float!(f64, self::no_std::powf64);

    #[cfg(not(feature = "std"))]
    mod no_std {
        macro_rules! powf {
            ($ty:ty, $name:ident) => {
                #[inline(never)]
                pub(crate) fn $name(mut base: $ty, mut exp: i32) -> $ty {
                    if exp == 0 {
                        return 1.0;
                    }

                    while exp & 1 == 0 {
                        base = base * base;
                        exp >>= 1;
                    }

                    if exp == 1 {
                        return base;
                    }

                    let mut acc = base;

                    while exp > 1 {
                        exp >>= 1;
                        base = base * base;

                        if exp & 1 == 1 {
                            acc = acc * base;
                        }
                    }

                    acc
                }
            };
        }

        powf!(f32, powf32);
        powf!(f64, powf64);
    }
}