jsonx-lib 0.5.2

Strict RFC 8259 JSON: a borrowing parser, a pull reader, and a deterministic writer, with budgets checked before allocation and no recursion. No dependencies, no_std.
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
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
//! JSON numbers, kept as their exact text.

use alloc::{borrow::Cow, string::String};
use core::fmt;

use crate::{Format, float, lexer};

/// A JSON number, kept as the exact text of the document.
///
/// Nothing is converted while parsing: the number borrows its digits from the
/// input, so a 30-digit integer or a decimal with more precision than `f64`
/// survives a read and a write unchanged. Conversion to a Rust number happens
/// only when it is asked for, with [`as_i64`](Self::as_i64),
/// [`as_u64`](Self::as_u64), or [`as_f64`](Self::as_f64), each of which says
/// exactly when it succeeds.
///
/// Two numbers are equal when their text is: `1`, `1.0`, and `1e0` are three
/// different numbers here, as they are three different documents. Compare
/// [`as_f64`](Self::as_f64) results to compare values.
///
/// # Examples
///
/// ```
/// use jsonx_lib::{parse, Number};
///
/// let doc = parse("[12345678901234567890123, 2.50, -7]")?;
/// let big = doc[0].as_number().unwrap();
/// assert_eq!(big.as_str(), "12345678901234567890123"); // exact
/// assert_eq!(big.as_u64(), None); // does not fit
/// assert_eq!(doc[1].as_number().unwrap().as_str(), "2.50"); // trailing zero kept
/// assert_eq!(doc[2].as_i64(), Some(-7));
///
/// assert_eq!(Number::from(42u8).as_str(), "42");
/// assert_eq!(Number::from_f64(0.1).unwrap().as_str(), "0.1");
/// # Ok::<(), jsonx_lib::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Number<'a> {
    /// Always one complete RFC 8259 number.
    text: Cow<'a, str>,
}

/// The value of `text` if it is all ASCII digits (an integer's text, sign
/// removed) and fits a `u64`; `None` for anything else, a fraction or
/// exponent included. One pass, with no overflow check below 20 digits.
#[inline]
fn digits(text: &[u8]) -> Option<u64> {
    let mut value: u64 = 0;
    if text.len() < 20 {
        if text.is_empty() {
            return None;
        }
        // At most 19 digits: below `u64::MAX`.
        for &b in text {
            let digit = b.wrapping_sub(b'0');
            if digit > 9 {
                return None;
            }
            value = value * 10 + u64::from(digit);
        }
        Some(value)
    } else {
        for &b in text {
            let digit = b.wrapping_sub(b'0');
            if digit > 9 {
                return None;
            }
            value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
        }
        Some(value)
    }
}

impl<'a> Number<'a> {
    /// Wraps text the tokenizer has already checked.
    #[inline]
    pub(crate) const fn from_valid(text: &'a str) -> Self {
        Self {
            text: Cow::Borrowed(text),
        }
    }

    /// Makes a number from its JSON text, which must be exactly one number in
    /// RFC 8259 syntax with nothing around it. The text is borrowed, not
    /// copied, so arbitrary-precision values pass through unchanged.
    ///
    /// Returns `None` for anything else: `+1`, `01`, `.5`, `1.`, `NaN`,
    /// whitespace, or an empty string.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{to_string, Number, Value};
    ///
    /// let price = Number::from_text("19.990").unwrap();
    /// assert_eq!(to_string(&Value::Number(price)), "19.990");
    /// assert!(Number::from_text("1.").is_none());
    /// assert!(Number::from_text("0x10").is_none());
    /// ```
    #[must_use]
    pub fn from_text(text: &'a str) -> Option<Self> {
        lexer::is_number(text).then_some(Self::from_valid(text))
    }

    /// Makes a number from an `f64`, written as the shortest text that reads
    /// back as the same `f64`. Returns `None` for NaN and the infinities,
    /// which JSON cannot represent.
    ///
    /// The text has a fraction or an exponent, so it reads back as a float:
    /// `1.0` is written `1.0`, not `1`. Values from 1e-5 up to below 1e16 are
    /// written as decimals (`0.00001`, `123.456`, `1000000000000000.0`); the
    /// rest in exponent form (`1e16`, `1.5e-7`, `-2.2250738585072014e-308`).
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// assert_eq!(Number::from_f64(1.0).unwrap().as_str(), "1.0");
    /// assert_eq!(Number::from_f64(-0.0).unwrap().as_str(), "-0.0");
    /// assert_eq!(Number::from_f64(1e100).unwrap().as_str(), "1e100");
    /// assert_eq!(Number::from_f64(0.1 + 0.2).unwrap().as_str(), "0.30000000000000004");
    /// assert!(Number::from_f64(f64::NAN).is_none());
    /// ```
    #[must_use]
    pub fn from_f64(value: f64) -> Option<Number<'static>> {
        format_f64(value).map(|text| Number {
            text: Cow::Owned(text),
        })
    }

    /// The number's text, exactly as written in the document (or as this crate
    /// wrote it, for a number made from a Rust value).
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::parse;
    ///
    /// assert_eq!(parse("1E+02")?.as_number().unwrap().as_str(), "1E+02");
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Whether the text is an integer: no fraction and no exponent. `2.0` and
    /// `2e3` are not integers by this test, though their values are whole.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// assert!(Number::from(-3).is_integer());
    /// assert!(!Number::from_text("2.0").unwrap().is_integer());
    /// ```
    #[must_use]
    pub fn is_integer(&self) -> bool {
        !self.text.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'))
    }

    /// The number as an `i64`, if its text is an integer (see
    /// [`is_integer`](Self::is_integer)) in `i64`'s range. `None` otherwise:
    /// nothing is rounded or truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let n = |s| Number::from_text(s).unwrap();
    /// assert_eq!(n("-9223372036854775808").as_i64(), Some(i64::MIN));
    /// assert_eq!(n("9223372036854775808").as_i64(), None); // out of range
    /// assert_eq!(n("3.0").as_i64(), None); // not an integer's text
    /// ```
    #[must_use]
    #[inline]
    pub fn as_i64(&self) -> Option<i64> {
        match self.text.strip_prefix('-') {
            Some(magnitude) => 0i64.checked_sub_unsigned(digits(magnitude.as_bytes())?),
            None => i64::try_from(digits(self.text.as_bytes())?).ok(),
        }
    }

    /// The number as a `u64`, if its text is an integer (see
    /// [`is_integer`](Self::is_integer)) in `u64`'s range. `-0` reads as `0`.
    /// `None` otherwise: nothing is rounded or truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let n = |s| Number::from_text(s).unwrap();
    /// assert_eq!(n("18446744073709551615").as_u64(), Some(u64::MAX));
    /// assert_eq!(n("-1").as_u64(), None);
    /// assert_eq!(n("-0").as_u64(), Some(0));
    /// ```
    #[must_use]
    #[inline]
    pub fn as_u64(&self) -> Option<u64> {
        match self.text.strip_prefix('-') {
            // The grammar forbids leading zeros, so `-0` is the only negative
            // integer text with a value `u64` can hold.
            Some("0") => Some(0),
            Some(_) => None,
            None => digits(self.text.as_bytes()),
        }
    }

    /// The number as an `i128`, if its text is an integer in `i128`'s range.
    /// `None` otherwise: nothing is rounded or truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let big = Number::from_text("-170141183460469231731687303715884105728").unwrap();
    /// assert_eq!(big.as_i128(), Some(i128::MIN));
    /// assert_eq!(Number::from_text("1e3").unwrap().as_i128(), None);
    /// ```
    #[must_use]
    pub fn as_i128(&self) -> Option<i128> {
        if self.is_integer() {
            self.text.parse().ok()
        } else {
            None
        }
    }

    /// The number as a `u128`, if its text is an integer in `u128`'s range.
    /// `-0` reads as `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let n = Number::from_text("340282366920938463463374607431768211455").unwrap();
    /// assert_eq!(n.as_u128(), Some(u128::MAX));
    /// assert_eq!(Number::from_text("-0").unwrap().as_u128(), Some(0));
    /// assert_eq!(Number::from_text("-1").unwrap().as_u128(), None);
    /// ```
    #[must_use]
    pub fn as_u128(&self) -> Option<u128> {
        if !self.is_integer() {
            return None;
        }
        match self.text.strip_prefix('-') {
            Some("0") => Some(0),
            Some(_) => None,
            None => self.text.parse().ok(),
        }
    }

    /// The number's value, if it is a whole number in `i128`'s range,
    /// however it is written: `100`, `1e2`, `100.0`, and `1000e-1` are all
    /// `Some(100)`, `-0.0` is `Some(0)`, and `1.5` or `1e40` are `None`. The
    /// decimal digits and the exponent are worked exactly: nothing goes
    /// through floating point, so nothing is rounded.
    ///
    /// [`as_i64`](Self::as_i64) and its siblings read integer *text* only;
    /// this reads integer *values*, for data from writers that put whole
    /// numbers in exponent or fraction form. See also
    /// [`Numbers::WholeValues`](crate::Numbers::WholeValues).
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let n = |s| Number::from_text(s).unwrap();
    /// assert_eq!(n("1e2").whole_value(), Some(100));
    /// assert_eq!(n("2.50e1").whole_value(), Some(25));
    /// assert_eq!(n("-12.000").whole_value(), Some(-12));
    /// assert_eq!(n("0.5e1").whole_value(), Some(5));
    /// assert_eq!(n("1.25").whole_value(), None);
    /// assert_eq!(n("1e39").whole_value(), None); // past i128
    /// ```
    #[must_use]
    pub fn whole_value(&self) -> Option<i128> {
        let text = self.text.as_bytes();
        let (negative, text) = match text.split_first() {
            Some((b'-', rest)) => (true, rest),
            _ => (false, text),
        };
        let (mantissa, exponent) = match text.iter().position(|&b| b == b'e' || b == b'E') {
            Some(at) => (text.get(..at)?, text.get(at + 1..)?),
            None => (text, &b""[..]),
        };
        let (int, frac) = match mantissa.iter().position(|&b| b == b'.') {
            Some(at) => (mantissa.get(..at)?, mantissa.get(at + 1..)?),
            None => (mantissa, &b""[..]),
        };
        // The exponent, saturated: anything past +-2^62 is far out of range
        // or far below one either way.
        let (exp_negative, exp_digits) = match exponent.split_first() {
            Some((b'-', rest)) => (true, rest),
            Some((b'+', rest)) => (false, rest),
            _ => (false, exponent),
        };
        let mut exp: i64 = 0;
        for &d in exp_digits {
            exp = exp.saturating_mul(10).saturating_add(i64::from(d - b'0'));
        }
        if exp_negative {
            exp = -exp;
        }
        // The significant digits, and the power of ten they are scaled by.
        let digits = int.iter().chain(frac.iter()).copied();
        let mut scale = exp.saturating_sub(frac.len() as i64);
        let significant: alloc::vec::Vec<u8> = digits.skip_while(|&d| d == b'0').collect();
        let trailing = significant.iter().rev().take_while(|&&d| d == b'0').count();
        let significant = significant.get(..significant.len() - trailing)?;
        scale = scale.saturating_add(trailing as i64);
        if significant.is_empty() {
            return Some(0);
        }
        if scale < 0 || (significant.len() as i64).saturating_add(scale) > 39 {
            return None;
        }
        let mut magnitude: u128 = 0;
        for &d in significant {
            magnitude = magnitude
                .checked_mul(10)?
                .checked_add(u128::from(d - b'0'))?;
        }
        for _ in 0..scale {
            magnitude = magnitude.checked_mul(10)?;
        }
        if negative {
            0i128.checked_sub_unsigned(magnitude)
        } else {
            i128::try_from(magnitude).ok()
        }
    }

    /// The number as the nearest `f32` (correctly rounded from the text
    /// itself, not through `f64`), or `None` if that is not finite (`1e39`).
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// assert_eq!(Number::from_text("0.1").unwrap().as_f32(), Some(0.1));
    /// assert_eq!(Number::from_text("1e39").unwrap().as_f32(), None);
    /// ```
    #[must_use]
    pub fn as_f32(&self) -> Option<f32> {
        self.text.parse::<f32>().ok().filter(|x| x.is_finite())
    }

    /// The number as the nearest `f64` (correctly rounded), or `None` if it is
    /// too large in magnitude to be finite (`1e400`). A value too small to
    /// represent rounds to zero, as IEEE 754 does. Integers beyond 2^53 lose
    /// precision; use [`as_i64`](Self::as_i64), [`as_u64`](Self::as_u64), or
    /// the exact [`as_str`](Self::as_str) when that matters.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let n = |s| Number::from_text(s).unwrap();
    /// assert_eq!(n("2.5e-3").as_f64(), Some(0.0025));
    /// assert_eq!(n("7").as_f64(), Some(7.0));
    /// assert_eq!(n("1e400").as_f64(), None);
    /// ```
    #[must_use]
    pub fn as_f64(&self) -> Option<f64> {
        self.text.parse::<f64>().ok().filter(|x| x.is_finite())
    }

    /// Copies borrowed text so the number no longer borrows from the input.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::Number;
    ///
    /// let owned: Number<'static> = {
    ///     let text = String::from("12.5");
    ///     Number::from_text(&text).unwrap().into_owned()
    /// };
    /// assert_eq!(owned.as_str(), "12.5");
    /// ```
    #[must_use]
    pub fn into_owned(self) -> Number<'static> {
        Number {
            text: Cow::Owned(self.text.into_owned()),
        }
    }
}

macro_rules! from_integer {
    ($($t:ty => $via:ty, $write:ident);* $(;)?) => {$(
        impl From<$t> for Number<'static> {
            /// Writes the integer in decimal.
            #[inline]
            fn from(value: $t) -> Self {
                let mut text = String::new();
                $write(&mut text, <$via>::from(value));
                Self { text: Cow::Owned(text) }
            }
        }
    )*};
}

from_integer!(
    i8 => i64, write_i64; i16 => i64, write_i64; i32 => i64, write_i64; i64 => i64, write_i64;
    u8 => u64, write_u64; u16 => u64, write_u64; u32 => u64, write_u64; u64 => u64, write_u64;
    i128 => i128, write_i128; u128 => u128, write_u128;
);

impl From<isize> for Number<'static> {
    /// Writes the integer in decimal.
    #[inline]
    fn from(value: isize) -> Self {
        let mut text = String::new();
        // `isize` is at most 64 bits on every target Rust supports; the
        // 128-bit path covers anything wider.
        match i64::try_from(value) {
            Ok(n) => write_i64(&mut text, n),
            Err(_) => write_i128(&mut text, value as i128),
        }
        Self {
            text: Cow::Owned(text),
        }
    }
}

impl From<usize> for Number<'static> {
    /// Writes the integer in decimal.
    #[inline]
    fn from(value: usize) -> Self {
        let mut text = String::new();
        match u64::try_from(value) {
            Ok(n) => write_u64(&mut text, n),
            Err(_) => write_u128(&mut text, value as u128),
        }
        Self {
            text: Cow::Owned(text),
        }
    }
}

impl fmt::Display for Number<'_> {
    /// Writes the number's exact text.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

impl fmt::Debug for Number<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// Pushes `count` ASCII zeros.
#[cfg(test)]
fn zeros(out: &mut String, count: usize) {
    out.extend(core::iter::repeat_n('0', count));
}

/// Appends `value` in decimal. Digits are produced into a stack buffer, so
/// nothing is allocated beyond `out`'s own growth.
#[inline]
pub(crate) fn write_u64(out: &mut String, value: u64) {
    let mut digits = [0u8; 20];
    let start = float::put_digits(&mut digits, 20, value);
    float::push_ascii(out, digits.get(start..).unwrap_or_default());
}

/// Appends `value` in decimal.
#[inline]
pub(crate) fn write_i64(out: &mut String, value: i64) {
    if value < 0 {
        out.push('-');
    }
    write_u64(out, value.unsigned_abs());
}

/// Appends `value` in decimal; 128-bit division only above `u64::MAX`.
pub(crate) fn write_u128(out: &mut String, value: u128) {
    if let Ok(small) = u64::try_from(value) {
        return write_u64(out, small);
    }
    let mut digits = [0u8; 39];
    let mut at = digits.len();
    let mut rest = value;
    while rest > 0 {
        at -= 1;
        if let Some(slot) = digits.get_mut(at) {
            *slot = b'0' + (rest % 10) as u8;
        }
        rest /= 10;
    }
    out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
}

/// Appends `value` in decimal.
pub(crate) fn write_i128(out: &mut String, value: i128) {
    if value < 0 {
        out.push('-');
    }
    write_u128(out, value.unsigned_abs());
}

/// The shortest round-trip text for a finite `f64`, laid out as described on
/// [`Number::from_f64`].
fn format_f64(value: f64) -> Option<String> {
    let mut out = String::with_capacity(26);
    write_f64(&mut out, value).then_some(out)
}

/// Appends the shortest round-trip text for `value`, laid out as described
/// on [`Number::from_f64`]. Returns `false`, writing nothing, for NaN and
/// the infinities.
#[inline]
pub(crate) fn write_f64(out: &mut String, value: f64) -> bool {
    write_f64_as(out, value, Format::compact())
}

/// [`write_f64`] with the float options of `format`: the `+` of a positive
/// exponent, and how an exact tie is broken.
pub(crate) fn write_f64_as(out: &mut String, value: f64, format: Format) -> bool {
    if !value.is_finite() {
        return false;
    }
    let decimal = float::f64_decimal(value, format.ties());
    float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
    true
}

/// As [`write_f64`] for an `f32`: the shortest text that reads back as the
/// same `f32` (`0.1f32` is `0.1`, not the `0.10000000149011612` of its
/// widening to `f64`).
#[cfg(test)]
pub(crate) fn write_f32(out: &mut String, value: f32) -> bool {
    write_f32_as(out, value, Format::compact())
}

/// [`write_f32`] with the float options of `format`.
pub(crate) fn write_f32_as(out: &mut String, value: f32, format: Format) -> bool {
    if !value.is_finite() {
        return false;
    }
    let decimal = float::f32_decimal(value, format.ties());
    float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
    true
}

/// The text 0.5.0 wrote, kept as the reference the tests compare with:
/// `core`'s `{:e}` digits, laid out with decimals for exponents from -5 up
/// to 15 and exponent form otherwise.
#[cfg(test)]
pub(crate) fn core_text(sci: &str) -> String {
    let mut out = String::new();
    let (negative, sci) = match sci.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, sci),
    };
    let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
    let exponent: i32 = exponent.parse().unwrap_or(0);
    let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
    if negative {
        out.push('-');
    }
    if (-5..16).contains(&exponent) {
        if let Ok(point) = usize::try_from(exponent) {
            out.push_str(lead);
            if frac.len() <= point {
                out.push_str(frac);
                zeros(&mut out, point - frac.len());
                out.push_str(".0");
            } else {
                let (int, rest) = frac.split_at_checked(point).unwrap_or((frac, ""));
                out.push_str(int);
                out.push('.');
                out.push_str(rest);
            }
        } else {
            out.push_str("0.");
            zeros(&mut out, exponent.unsigned_abs() as usize - 1);
            out.push_str(lead);
            out.push_str(frac);
        }
    } else {
        out.push_str(lead);
        if !frac.is_empty() {
            out.push('.');
            out.push_str(frac);
        }
        out.push('e');
        out.push_str(&alloc::format!("{exponent}"));
    }
    out
}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;

    use proptest::prelude::*;

    use super::*;

    #[test]
    fn test_integer_reads_agree_with_the_standard_parser() {
        let texts = [
            "0",
            "-0",
            "1",
            "-1",
            "9",
            "10",
            "18446744073709551615",
            "18446744073709551616",
            "99999999999999999999",
            "100000000000000000000",
            "9223372036854775807",
            "9223372036854775808",
            "-9223372036854775808",
            "-9223372036854775809",
            "1234567890123456789",
            "12345678901234567890",
            "-12345678901234567890",
            "1.0",
            "1e2",
            "-1.5",
            "0.0",
            "-0e0",
            "123456789012345678901234567890",
        ];
        for text in texts {
            let n = Number::from_text(text).unwrap();
            let integer = n.is_integer();
            let want_i64 = integer.then(|| text.parse::<i64>().ok()).flatten();
            let want_u64 = match text.strip_prefix('-') {
                Some("0") => Some(0),
                Some(_) => None,
                None => integer.then(|| text.parse::<u64>().ok()).flatten(),
            };
            assert_eq!(n.as_i64(), want_i64, "{text}");
            assert_eq!(n.as_u64(), want_u64, "{text}");
        }
    }

    fn f(x: f64) -> String {
        format_f64(x).unwrap_or_default()
    }

    #[test]
    fn test_format_f64_layouts() {
        let cases: &[(f64, &str)] = &[
            (0.0, "0.0"),
            (-0.0, "-0.0"),
            (1.0, "1.0"),
            (1.5, "1.5"),
            (100.0, "100.0"),
            (123.456, "123.456"),
            (0.1, "0.1"),
            (1e-5, "0.00001"),
            (1.5e-5, "0.000015"),
            (1e-6, "1e-6"),
            (1.5e-7, "1.5e-7"),
            (1e15, "1000000000000000.0"),
            (1e16, "1e16"),
            (1.7976931348623157e308, "1.7976931348623157e308"),
            (5e-324, "5e-324"),
            (-2.2250738585072014e-308, "-2.2250738585072014e-308"),
            (123456789012345.67, "123456789012345.67"),
        ];
        for &(x, want) in cases {
            assert_eq!(f(x), want, "{x:e}");
        }
        assert!(format_f64(f64::NAN).is_none());
        assert!(format_f64(f64::INFINITY).is_none());
        assert!(format_f64(f64::NEG_INFINITY).is_none());
    }

    #[test]
    fn test_integer_conversions_exact() {
        assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
        assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
        assert_eq!(Number::from(u64::MAX).as_i64(), None);
        assert_eq!(Number::from(-1i8).as_u64(), None);
        assert_eq!(
            Number::from(u128::MAX).as_str(),
            "340282366920938463463374607431768211455"
        );
    }

    #[test]
    fn test_integer_writers_match_core_formatting() {
        let mut out = String::new();
        for n in [
            0u64,
            1,
            9,
            10,
            99,
            100,
            12_345,
            u64::from(u32::MAX),
            u64::MAX,
        ] {
            out.clear();
            write_u64(&mut out, n);
            assert_eq!(out, alloc::format!("{n}"));
        }
        for n in [0i64, -1, 1, i64::MIN, i64::MAX, -1_000_000] {
            out.clear();
            write_i64(&mut out, n);
            assert_eq!(out, alloc::format!("{n}"));
        }
        for n in [
            0u128,
            u128::from(u64::MAX),
            u128::from(u64::MAX) + 1,
            u128::MAX,
        ] {
            out.clear();
            write_u128(&mut out, n);
            assert_eq!(out, alloc::format!("{n}"));
        }
        for n in [i128::MIN, i128::MAX, -1, 0] {
            out.clear();
            write_i128(&mut out, n);
            assert_eq!(out, alloc::format!("{n}"));
        }
        assert_eq!(Number::from(isize::MIN).as_i64(), Some(isize::MIN as i64));
        assert_eq!(Number::from(usize::MAX).as_u64(), Some(usize::MAX as u64));
    }

    #[test]
    fn test_whole_value_edges() {
        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
        assert_eq!(n("0").whole_value(), Some(0));
        assert_eq!(n("-0.000e5").whole_value(), Some(0));
        assert_eq!(n("1e-0").whole_value(), Some(1));
        assert_eq!(n("1E+3").whole_value(), Some(1000));
        assert_eq!(n("10e-1").whole_value(), Some(1));
        assert_eq!(n("1e-1").whole_value(), None);
        assert_eq!(n("1e99999999999999999999").whole_value(), None);
        assert_eq!(n("1e-99999999999999999999").whole_value(), None);
        assert_eq!(n("0e99999999999999999999").whole_value(), Some(0));
        assert_eq!(
            n("-170141183460469231731687303715884105728").whole_value(),
            Some(i128::MIN)
        );
        assert_eq!(
            n("170141183460469231731687303715884105728").whole_value(),
            None
        );
        assert_eq!(
            n("1.7014118346046923173168730371588410572e38").whole_value(),
            Some(170_141_183_460_469_231_731_687_303_715_884_105_720)
        );
        assert_eq!(n("1.23e2").whole_value(), Some(123));
    }

    #[test]
    fn test_wide_and_narrow_conversions() {
        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
        assert_eq!(n("170141183460469231731687303715884105728").as_i128(), None);
        assert_eq!(n("2.5").as_u128(), None);
        assert_eq!(n("2.5").as_i128(), None);
        assert_eq!(n("12").as_u128(), Some(12));
        assert_eq!(n("-3").as_f32(), Some(-3.0));
        // The same text rounds to f32 directly: no double rounding.
        assert_eq!(n("16777217").as_f32(), Some(16_777_216.0));
    }

    #[test]
    fn test_f32_is_shortest_for_f32() {
        let mut out = String::new();
        assert!(write_f32(&mut out, 0.1));
        assert_eq!(out, "0.1");
        out.clear();
        assert!(write_f32(&mut out, 1.0e20));
        assert_eq!(out, "1e20");
        assert!(!write_f32(&mut out, f32::NAN));
        assert!(!write_f64(&mut out, f64::INFINITY));
    }

    #[test]
    fn test_float_options_through_format() {
        let both = Format::compact().exponent_plus(true).even_ties(true);
        let tie = 164_696_460_098_373.0 + 0.625;
        let text = |x: f64, format: Format| {
            let mut out = String::new();
            assert!(write_f64_as(&mut out, x, format));
            out
        };
        assert_eq!(text(1e16, both), "1e+16");
        assert_eq!(text(-1e-7, both), "-1e-7");
        assert_eq!(text(tie, both), "164696460098373.62");
        assert_eq!(
            text(tie, Format::compact().exponent_plus(true)),
            "164696460098373.63"
        );
        assert_eq!(text(1e300, Format::pretty().exponent_plus(true)), "1e+300");
        let mut out = String::new();
        assert!(write_f32_as(&mut out, 1e20, both));
        assert_eq!(out, "1e+20");
        assert!(!write_f32_as(&mut out, f32::INFINITY, both));
        assert!(!write_f64_as(&mut out, f64::NAN, both));
        assert_eq!(out, "1e+20");
        // The options ride along with the other settings.
        let f = Format::compact()
            .html_safe(true)
            .exponent_plus(true)
            .even_ties(true);
        assert!(f.exponent_plus && f.even_ties && f.html && !f.pretty);
        assert_eq!(Format::default(), Format::compact());
        assert_ne!(both, Format::compact());
    }

    proptest! {
        /// With both float options on, the text is still one valid JSON
        /// number that reads back as the same float; the `+` alone is the
        /// only difference `exponent_plus` makes.
        #[test]
        fn prop_float_options_keep_the_value(bits in any::<u64>()) {
            let x = f64::from_bits(bits);
            prop_assume!(x.is_finite());
            let both = Format::compact().exponent_plus(true).even_ties(true);
            let mut out = String::new();
            prop_assert!(write_f64_as(&mut out, x, both));
            prop_assert!(lexer::is_number(&out), "{}", out);
            prop_assert_eq!(out.parse::<f64>().map(f64::to_bits).ok(), Some(x.to_bits()));
            let mut plain = String::new();
            prop_assert!(write_f64_as(&mut plain, x, Format::compact().exponent_plus(true)));
            let mut default = String::new();
            prop_assert!(write_f64(&mut default, x));
            prop_assert_eq!(plain.replacen("e+", "e", 1), default);
        }

        #[test]
        fn prop_f32_text_round_trips(bits in any::<u32>()) {
            let x = f32::from_bits(bits);
            prop_assume!(x.is_finite());
            let mut out = String::new();
            prop_assert!(write_f32(&mut out, x));
            prop_assert!(lexer::is_number(&out), "{}", out);
            prop_assert_eq!(out.parse::<f32>().map(f32::to_bits).ok(), Some(x.to_bits()));
        }

        /// Every spelling of an integer reads back as the integer.
        #[test]
        fn prop_whole_value_of_any_spelling(n in any::<i64>(), shift in 0usize..20, zeros in 0usize..4) {
            let plain = alloc::format!("{n}");
            prop_assert_eq!(Number::from_text(&plain).and_then(|x| x.whole_value()), Some(i128::from(n)));
            // n * 10^shift written as n followed by `zeros` zeros and an exponent.
            let spelled = alloc::format!("{n}{}e{}", "0".repeat(zeros), shift as i64 - zeros as i64);
            let want = i128::from(n).checked_mul(10i128.pow(shift as u32));
            prop_assert_eq!(Number::from_text(&spelled).and_then(|x| x.whole_value()), want);
            let fraction = alloc::format!("{n}.{}", "0".repeat(zeros + 1));
            prop_assert_eq!(Number::from_text(&fraction).and_then(|x| x.whole_value()), Some(i128::from(n)));
        }

        #[test]
        fn prop_integer_writers_match_core(n in any::<i128>()) {
            let mut out = String::new();
            write_i128(&mut out, n);
            prop_assert_eq!(out, alloc::format!("{n}"));
        }

        #[test]
        fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
            let x = f64::from_bits(bits);
            prop_assume!(x.is_finite());
            let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
            prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
            prop_assert!(!n.is_integer());
            let back = n.as_f64().unwrap_or(f64::NAN);
            prop_assert_eq!(back.to_bits(), x.to_bits());
            // Shortest: no representation with fewer significant digits exists,
            // which `{:e}` guarantees; check the text carries exactly its digits.
            let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
            let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
            let trim = |d: &[u8]| -> Vec<u8> {
                let s: &[u8] = d;
                let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
                let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
                s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
            };
            prop_assert_eq!(trim(&digits), trim(&ours));
        }

        #[test]
        fn prop_i64_round_trips(x in any::<i64>()) {
            prop_assert_eq!(Number::from(x).as_i64(), Some(x));
        }

        #[test]
        fn prop_u64_round_trips(x in any::<u64>()) {
            prop_assert_eq!(Number::from(x).as_u64(), Some(x));
        }
    }
}