Skip to main content

jsonx_lib/
number.rs

1//! JSON numbers, kept as their exact text.
2
3use alloc::{borrow::Cow, string::String};
4use core::fmt::{self, Write as _};
5
6use crate::lexer;
7
8/// A JSON number, kept as the exact text of the document.
9///
10/// Nothing is converted while parsing: the number borrows its digits from the
11/// input, so a 30-digit integer or a decimal with more precision than `f64`
12/// survives a read and a write unchanged. Conversion to a Rust number happens
13/// only when it is asked for, with [`as_i64`](Self::as_i64),
14/// [`as_u64`](Self::as_u64), or [`as_f64`](Self::as_f64), each of which says
15/// exactly when it succeeds.
16///
17/// Two numbers are equal when their text is: `1`, `1.0`, and `1e0` are three
18/// different numbers here, as they are three different documents. Compare
19/// [`as_f64`](Self::as_f64) results to compare values.
20///
21/// # Examples
22///
23/// ```
24/// use jsonx_lib::{parse, Number};
25///
26/// let doc = parse("[12345678901234567890123, 2.50, -7]")?;
27/// let big = doc[0].as_number().unwrap();
28/// assert_eq!(big.as_str(), "12345678901234567890123"); // exact
29/// assert_eq!(big.as_u64(), None); // does not fit
30/// assert_eq!(doc[1].as_number().unwrap().as_str(), "2.50"); // trailing zero kept
31/// assert_eq!(doc[2].as_i64(), Some(-7));
32///
33/// assert_eq!(Number::from(42u8).as_str(), "42");
34/// assert_eq!(Number::from_f64(0.1).unwrap().as_str(), "0.1");
35/// # Ok::<(), jsonx_lib::Error>(())
36/// ```
37#[derive(Clone, PartialEq, Eq, Hash)]
38pub struct Number<'a> {
39    /// Always one complete RFC 8259 number.
40    text: Cow<'a, str>,
41}
42
43/// The value of `text` if it is all ASCII digits (an integer's text, sign
44/// removed) and fits a `u64`; `None` for anything else, a fraction or
45/// exponent included. One pass, with no overflow check below 20 digits.
46#[inline]
47fn digits(text: &[u8]) -> Option<u64> {
48    let mut value: u64 = 0;
49    if text.len() < 20 {
50        if text.is_empty() {
51            return None;
52        }
53        // At most 19 digits: below `u64::MAX`.
54        for &b in text {
55            let digit = b.wrapping_sub(b'0');
56            if digit > 9 {
57                return None;
58            }
59            value = value * 10 + u64::from(digit);
60        }
61        Some(value)
62    } else {
63        for &b in text {
64            let digit = b.wrapping_sub(b'0');
65            if digit > 9 {
66                return None;
67            }
68            value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
69        }
70        Some(value)
71    }
72}
73
74impl<'a> Number<'a> {
75    /// Wraps text the tokenizer has already checked.
76    #[inline]
77    pub(crate) const fn from_valid(text: &'a str) -> Self {
78        Self {
79            text: Cow::Borrowed(text),
80        }
81    }
82
83    /// Makes a number from its JSON text, which must be exactly one number in
84    /// RFC 8259 syntax with nothing around it. The text is borrowed, not
85    /// copied, so arbitrary-precision values pass through unchanged.
86    ///
87    /// Returns `None` for anything else: `+1`, `01`, `.5`, `1.`, `NaN`,
88    /// whitespace, or an empty string.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use jsonx_lib::{to_string, Number, Value};
94    ///
95    /// let price = Number::from_text("19.990").unwrap();
96    /// assert_eq!(to_string(&Value::Number(price)), "19.990");
97    /// assert!(Number::from_text("1.").is_none());
98    /// assert!(Number::from_text("0x10").is_none());
99    /// ```
100    #[must_use]
101    pub fn from_text(text: &'a str) -> Option<Self> {
102        lexer::is_number(text).then_some(Self::from_valid(text))
103    }
104
105    /// Makes a number from an `f64`, written as the shortest text that reads
106    /// back as the same `f64`. Returns `None` for NaN and the infinities,
107    /// which JSON cannot represent.
108    ///
109    /// The text has a fraction or an exponent, so it reads back as a float:
110    /// `1.0` is written `1.0`, not `1`. Values from 1e-5 up to below 1e16 are
111    /// written as decimals (`0.00001`, `123.456`, `1000000000000000.0`); the
112    /// rest in exponent form (`1e16`, `1.5e-7`, `-2.2250738585072014e-308`).
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use jsonx_lib::Number;
118    ///
119    /// assert_eq!(Number::from_f64(1.0).unwrap().as_str(), "1.0");
120    /// assert_eq!(Number::from_f64(-0.0).unwrap().as_str(), "-0.0");
121    /// assert_eq!(Number::from_f64(1e100).unwrap().as_str(), "1e100");
122    /// assert_eq!(Number::from_f64(0.1 + 0.2).unwrap().as_str(), "0.30000000000000004");
123    /// assert!(Number::from_f64(f64::NAN).is_none());
124    /// ```
125    #[must_use]
126    pub fn from_f64(value: f64) -> Option<Number<'static>> {
127        format_f64(value).map(|text| Number {
128            text: Cow::Owned(text),
129        })
130    }
131
132    /// The number's text, exactly as written in the document (or as this crate
133    /// wrote it, for a number made from a Rust value).
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use jsonx_lib::parse;
139    ///
140    /// assert_eq!(parse("1E+02")?.as_number().unwrap().as_str(), "1E+02");
141    /// # Ok::<(), jsonx_lib::Error>(())
142    /// ```
143    #[inline]
144    #[must_use]
145    pub fn as_str(&self) -> &str {
146        &self.text
147    }
148
149    /// Whether the text is an integer: no fraction and no exponent. `2.0` and
150    /// `2e3` are not integers by this test, though their values are whole.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use jsonx_lib::Number;
156    ///
157    /// assert!(Number::from(-3).is_integer());
158    /// assert!(!Number::from_text("2.0").unwrap().is_integer());
159    /// ```
160    #[must_use]
161    pub fn is_integer(&self) -> bool {
162        !self.text.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'))
163    }
164
165    /// The number as an `i64`, if its text is an integer (see
166    /// [`is_integer`](Self::is_integer)) in `i64`'s range. `None` otherwise:
167    /// nothing is rounded or truncated.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// use jsonx_lib::Number;
173    ///
174    /// let n = |s| Number::from_text(s).unwrap();
175    /// assert_eq!(n("-9223372036854775808").as_i64(), Some(i64::MIN));
176    /// assert_eq!(n("9223372036854775808").as_i64(), None); // out of range
177    /// assert_eq!(n("3.0").as_i64(), None); // not an integer's text
178    /// ```
179    #[must_use]
180    #[inline]
181    pub fn as_i64(&self) -> Option<i64> {
182        match self.text.strip_prefix('-') {
183            Some(magnitude) => 0i64.checked_sub_unsigned(digits(magnitude.as_bytes())?),
184            None => i64::try_from(digits(self.text.as_bytes())?).ok(),
185        }
186    }
187
188    /// The number as a `u64`, if its text is an integer (see
189    /// [`is_integer`](Self::is_integer)) in `u64`'s range. `-0` reads as `0`.
190    /// `None` otherwise: nothing is rounded or truncated.
191    ///
192    /// # Examples
193    ///
194    /// ```
195    /// use jsonx_lib::Number;
196    ///
197    /// let n = |s| Number::from_text(s).unwrap();
198    /// assert_eq!(n("18446744073709551615").as_u64(), Some(u64::MAX));
199    /// assert_eq!(n("-1").as_u64(), None);
200    /// assert_eq!(n("-0").as_u64(), Some(0));
201    /// ```
202    #[must_use]
203    #[inline]
204    pub fn as_u64(&self) -> Option<u64> {
205        match self.text.strip_prefix('-') {
206            // The grammar forbids leading zeros, so `-0` is the only negative
207            // integer text with a value `u64` can hold.
208            Some("0") => Some(0),
209            Some(_) => None,
210            None => digits(self.text.as_bytes()),
211        }
212    }
213
214    /// The number as an `i128`, if its text is an integer in `i128`'s range.
215    /// `None` otherwise: nothing is rounded or truncated.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use jsonx_lib::Number;
221    ///
222    /// let big = Number::from_text("-170141183460469231731687303715884105728").unwrap();
223    /// assert_eq!(big.as_i128(), Some(i128::MIN));
224    /// assert_eq!(Number::from_text("1e3").unwrap().as_i128(), None);
225    /// ```
226    #[must_use]
227    pub fn as_i128(&self) -> Option<i128> {
228        if self.is_integer() {
229            self.text.parse().ok()
230        } else {
231            None
232        }
233    }
234
235    /// The number as a `u128`, if its text is an integer in `u128`'s range.
236    /// `-0` reads as `0`.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use jsonx_lib::Number;
242    ///
243    /// let n = Number::from_text("340282366920938463463374607431768211455").unwrap();
244    /// assert_eq!(n.as_u128(), Some(u128::MAX));
245    /// assert_eq!(Number::from_text("-0").unwrap().as_u128(), Some(0));
246    /// assert_eq!(Number::from_text("-1").unwrap().as_u128(), None);
247    /// ```
248    #[must_use]
249    pub fn as_u128(&self) -> Option<u128> {
250        if !self.is_integer() {
251            return None;
252        }
253        match self.text.strip_prefix('-') {
254            Some("0") => Some(0),
255            Some(_) => None,
256            None => self.text.parse().ok(),
257        }
258    }
259
260    /// The number's value, if it is a whole number in `i128`'s range,
261    /// however it is written: `100`, `1e2`, `100.0`, and `1000e-1` are all
262    /// `Some(100)`, `-0.0` is `Some(0)`, and `1.5` or `1e40` are `None`. The
263    /// decimal digits and the exponent are worked exactly: nothing goes
264    /// through floating point, so nothing is rounded.
265    ///
266    /// [`as_i64`](Self::as_i64) and its siblings read integer *text* only;
267    /// this reads integer *values*, for data from writers that put whole
268    /// numbers in exponent or fraction form. See also
269    /// [`Numbers::WholeValues`](crate::Numbers::WholeValues).
270    ///
271    /// # Examples
272    ///
273    /// ```
274    /// use jsonx_lib::Number;
275    ///
276    /// let n = |s| Number::from_text(s).unwrap();
277    /// assert_eq!(n("1e2").whole_value(), Some(100));
278    /// assert_eq!(n("2.50e1").whole_value(), Some(25));
279    /// assert_eq!(n("-12.000").whole_value(), Some(-12));
280    /// assert_eq!(n("0.5e1").whole_value(), Some(5));
281    /// assert_eq!(n("1.25").whole_value(), None);
282    /// assert_eq!(n("1e39").whole_value(), None); // past i128
283    /// ```
284    #[must_use]
285    pub fn whole_value(&self) -> Option<i128> {
286        let text = self.text.as_bytes();
287        let (negative, text) = match text.split_first() {
288            Some((b'-', rest)) => (true, rest),
289            _ => (false, text),
290        };
291        let (mantissa, exponent) = match text.iter().position(|&b| b == b'e' || b == b'E') {
292            Some(at) => (text.get(..at)?, text.get(at + 1..)?),
293            None => (text, &b""[..]),
294        };
295        let (int, frac) = match mantissa.iter().position(|&b| b == b'.') {
296            Some(at) => (mantissa.get(..at)?, mantissa.get(at + 1..)?),
297            None => (mantissa, &b""[..]),
298        };
299        // The exponent, saturated: anything past +-2^62 is far out of range
300        // or far below one either way.
301        let (exp_negative, exp_digits) = match exponent.split_first() {
302            Some((b'-', rest)) => (true, rest),
303            Some((b'+', rest)) => (false, rest),
304            _ => (false, exponent),
305        };
306        let mut exp: i64 = 0;
307        for &d in exp_digits {
308            exp = exp.saturating_mul(10).saturating_add(i64::from(d - b'0'));
309        }
310        if exp_negative {
311            exp = -exp;
312        }
313        // The significant digits, and the power of ten they are scaled by.
314        let digits = int.iter().chain(frac.iter()).copied();
315        let mut scale = exp.saturating_sub(frac.len() as i64);
316        let significant: alloc::vec::Vec<u8> = digits.skip_while(|&d| d == b'0').collect();
317        let trailing = significant.iter().rev().take_while(|&&d| d == b'0').count();
318        let significant = significant.get(..significant.len() - trailing)?;
319        scale = scale.saturating_add(trailing as i64);
320        if significant.is_empty() {
321            return Some(0);
322        }
323        if scale < 0 || (significant.len() as i64).saturating_add(scale) > 39 {
324            return None;
325        }
326        let mut magnitude: u128 = 0;
327        for &d in significant {
328            magnitude = magnitude
329                .checked_mul(10)?
330                .checked_add(u128::from(d - b'0'))?;
331        }
332        for _ in 0..scale {
333            magnitude = magnitude.checked_mul(10)?;
334        }
335        if negative {
336            0i128.checked_sub_unsigned(magnitude)
337        } else {
338            i128::try_from(magnitude).ok()
339        }
340    }
341
342    /// The number as the nearest `f32` (correctly rounded from the text
343    /// itself, not through `f64`), or `None` if that is not finite (`1e39`).
344    ///
345    /// # Examples
346    ///
347    /// ```
348    /// use jsonx_lib::Number;
349    ///
350    /// assert_eq!(Number::from_text("0.1").unwrap().as_f32(), Some(0.1));
351    /// assert_eq!(Number::from_text("1e39").unwrap().as_f32(), None);
352    /// ```
353    #[must_use]
354    pub fn as_f32(&self) -> Option<f32> {
355        self.text.parse::<f32>().ok().filter(|x| x.is_finite())
356    }
357
358    /// The number as the nearest `f64` (correctly rounded), or `None` if it is
359    /// too large in magnitude to be finite (`1e400`). A value too small to
360    /// represent rounds to zero, as IEEE 754 does. Integers beyond 2^53 lose
361    /// precision; use [`as_i64`](Self::as_i64), [`as_u64`](Self::as_u64), or
362    /// the exact [`as_str`](Self::as_str) when that matters.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use jsonx_lib::Number;
368    ///
369    /// let n = |s| Number::from_text(s).unwrap();
370    /// assert_eq!(n("2.5e-3").as_f64(), Some(0.0025));
371    /// assert_eq!(n("7").as_f64(), Some(7.0));
372    /// assert_eq!(n("1e400").as_f64(), None);
373    /// ```
374    #[must_use]
375    pub fn as_f64(&self) -> Option<f64> {
376        self.text.parse::<f64>().ok().filter(|x| x.is_finite())
377    }
378
379    /// Copies borrowed text so the number no longer borrows from the input.
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use jsonx_lib::Number;
385    ///
386    /// let owned: Number<'static> = {
387    ///     let text = String::from("12.5");
388    ///     Number::from_text(&text).unwrap().into_owned()
389    /// };
390    /// assert_eq!(owned.as_str(), "12.5");
391    /// ```
392    #[must_use]
393    pub fn into_owned(self) -> Number<'static> {
394        Number {
395            text: Cow::Owned(self.text.into_owned()),
396        }
397    }
398}
399
400macro_rules! from_integer {
401    ($($t:ty => $via:ty, $write:ident);* $(;)?) => {$(
402        impl From<$t> for Number<'static> {
403            /// Writes the integer in decimal.
404            #[inline]
405            fn from(value: $t) -> Self {
406                let mut text = String::new();
407                $write(&mut text, <$via>::from(value));
408                Self { text: Cow::Owned(text) }
409            }
410        }
411    )*};
412}
413
414from_integer!(
415    i8 => i64, write_i64; i16 => i64, write_i64; i32 => i64, write_i64; i64 => i64, write_i64;
416    u8 => u64, write_u64; u16 => u64, write_u64; u32 => u64, write_u64; u64 => u64, write_u64;
417    i128 => i128, write_i128; u128 => u128, write_u128;
418);
419
420impl From<isize> for Number<'static> {
421    /// Writes the integer in decimal.
422    #[inline]
423    fn from(value: isize) -> Self {
424        let mut text = String::new();
425        // `isize` is at most 64 bits on every target Rust supports; the
426        // 128-bit path covers anything wider.
427        match i64::try_from(value) {
428            Ok(n) => write_i64(&mut text, n),
429            Err(_) => write_i128(&mut text, value as i128),
430        }
431        Self {
432            text: Cow::Owned(text),
433        }
434    }
435}
436
437impl From<usize> for Number<'static> {
438    /// Writes the integer in decimal.
439    #[inline]
440    fn from(value: usize) -> Self {
441        let mut text = String::new();
442        match u64::try_from(value) {
443            Ok(n) => write_u64(&mut text, n),
444            Err(_) => write_u128(&mut text, value as u128),
445        }
446        Self {
447            text: Cow::Owned(text),
448        }
449    }
450}
451
452impl fmt::Display for Number<'_> {
453    /// Writes the number's exact text.
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.write_str(&self.text)
456    }
457}
458
459impl fmt::Debug for Number<'_> {
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        f.write_str(&self.text)
462    }
463}
464
465/// A fixed buffer for `core::fmt` output, so formatting an `f64` needs no
466/// allocation before the final text is built.
467struct StackText {
468    buf: [u8; 40],
469    len: usize,
470}
471
472impl fmt::Write for StackText {
473    fn write_str(&mut self, s: &str) -> fmt::Result {
474        let end = self.len + s.len();
475        let slot = self.buf.get_mut(self.len..end).ok_or(fmt::Error)?;
476        slot.copy_from_slice(s.as_bytes());
477        self.len = end;
478        Ok(())
479    }
480}
481
482/// Pushes `count` ASCII zeros.
483fn zeros(out: &mut String, count: usize) {
484    out.extend(core::iter::repeat_n('0', count));
485}
486
487/// Appends `value` in decimal. Digits are produced into a stack buffer, so
488/// nothing is allocated beyond `out`'s own growth.
489#[inline]
490pub(crate) fn write_u64(out: &mut String, value: u64) {
491    let mut digits = [0u8; 20];
492    let mut at = digits.len();
493    let mut rest = value;
494    loop {
495        at -= 1;
496        if let Some(slot) = digits.get_mut(at) {
497            // `rest % 10` is below 10.
498            *slot = b'0' + (rest % 10) as u8;
499        }
500        rest /= 10;
501        if rest == 0 {
502            break;
503        }
504    }
505    out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
506}
507
508/// Appends `value` in decimal.
509#[inline]
510pub(crate) fn write_i64(out: &mut String, value: i64) {
511    if value < 0 {
512        out.push('-');
513    }
514    write_u64(out, value.unsigned_abs());
515}
516
517/// Appends `value` in decimal; 128-bit division only above `u64::MAX`.
518pub(crate) fn write_u128(out: &mut String, value: u128) {
519    if let Ok(small) = u64::try_from(value) {
520        return write_u64(out, small);
521    }
522    let mut digits = [0u8; 39];
523    let mut at = digits.len();
524    let mut rest = value;
525    while rest > 0 {
526        at -= 1;
527        if let Some(slot) = digits.get_mut(at) {
528            *slot = b'0' + (rest % 10) as u8;
529        }
530        rest /= 10;
531    }
532    out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
533}
534
535/// Appends `value` in decimal.
536pub(crate) fn write_i128(out: &mut String, value: i128) {
537    if value < 0 {
538        out.push('-');
539    }
540    write_u128(out, value.unsigned_abs());
541}
542
543/// The shortest round-trip text for a finite `f64`, laid out as described on
544/// [`Number::from_f64`].
545fn format_f64(value: f64) -> Option<String> {
546    let mut out = String::with_capacity(26);
547    write_f64(&mut out, value).then_some(out)
548}
549
550/// Appends the shortest round-trip text for `value`, laid out as described
551/// on [`Number::from_f64`]. Returns `false`, writing nothing, for NaN and
552/// the infinities.
553///
554/// `core`'s `{:e}` formatting already yields the shortest digit string that
555/// reads back as the same `f64` (it is the same algorithm `Display` uses); this
556/// only moves the decimal point.
557pub(crate) fn write_f64(out: &mut String, value: f64) -> bool {
558    if !value.is_finite() {
559        return false;
560    }
561    let mut sci = StackText {
562        buf: [0; 40],
563        len: 0,
564    };
565    write!(sci, "{value:e}").is_ok() && layout(out, &sci)
566}
567
568/// As [`write_f64`] for an `f32`: the shortest text that reads back as the
569/// same `f32` (`0.1f32` is `0.1`, not the `0.10000000149011612` of its
570/// widening to `f64`).
571pub(crate) fn write_f32(out: &mut String, value: f32) -> bool {
572    if !value.is_finite() {
573        return false;
574    }
575    let mut sci = StackText {
576        buf: [0; 40],
577        len: 0,
578    };
579    write!(sci, "{value:e}").is_ok() && layout(out, &sci)
580}
581
582/// Lays out `{:e}` text (`-1.5e-7`) as JSON, decimals for exponents from -5
583/// up to 15 and exponent form otherwise. Writes nothing and returns `false`
584/// if `sci` is not in that form (it always is).
585fn layout(out: &mut String, sci: &StackText) -> bool {
586    let Some(sci) = sci
587        .buf
588        .get(..sci.len)
589        .and_then(|b| core::str::from_utf8(b).ok())
590    else {
591        return false;
592    };
593    let (negative, sci) = match sci.strip_prefix('-') {
594        Some(rest) => (true, rest),
595        None => (false, sci),
596    };
597    let Some((mantissa, exponent)) = sci.split_once('e') else {
598        return false;
599    };
600    let Ok(exponent) = exponent.parse::<i32>() else {
601        return false;
602    };
603    // `{:e}` writes one digit before the point.
604    let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
605    if negative {
606        out.push('-');
607    }
608    if (-5..16).contains(&exponent) {
609        if let Ok(point) = usize::try_from(exponent) {
610            // `point` digits of `frac` go before the decimal point.
611            out.push_str(lead);
612            if frac.len() <= point {
613                out.push_str(frac);
614                zeros(out, point - frac.len());
615                out.push_str(".0");
616            } else {
617                let (int, rest) = frac.split_at_checked(point).unwrap_or((frac, ""));
618                out.push_str(int);
619                out.push('.');
620                out.push_str(rest);
621            }
622        } else {
623            out.push_str("0.");
624            zeros(out, exponent.unsigned_abs() as usize - 1);
625            out.push_str(lead);
626            out.push_str(frac);
627        }
628    } else {
629        out.push_str(lead);
630        if !frac.is_empty() {
631            out.push('.');
632            out.push_str(frac);
633        }
634        out.push('e');
635        write_i64(out, i64::from(exponent));
636    }
637    true
638}
639#[cfg(test)]
640mod tests {
641    use alloc::vec::Vec;
642
643    use proptest::prelude::*;
644
645    use super::*;
646
647    #[test]
648    fn test_integer_reads_agree_with_the_standard_parser() {
649        let texts = [
650            "0",
651            "-0",
652            "1",
653            "-1",
654            "9",
655            "10",
656            "18446744073709551615",
657            "18446744073709551616",
658            "99999999999999999999",
659            "100000000000000000000",
660            "9223372036854775807",
661            "9223372036854775808",
662            "-9223372036854775808",
663            "-9223372036854775809",
664            "1234567890123456789",
665            "12345678901234567890",
666            "-12345678901234567890",
667            "1.0",
668            "1e2",
669            "-1.5",
670            "0.0",
671            "-0e0",
672            "123456789012345678901234567890",
673        ];
674        for text in texts {
675            let n = Number::from_text(text).unwrap();
676            let integer = n.is_integer();
677            let want_i64 = integer.then(|| text.parse::<i64>().ok()).flatten();
678            let want_u64 = match text.strip_prefix('-') {
679                Some("0") => Some(0),
680                Some(_) => None,
681                None => integer.then(|| text.parse::<u64>().ok()).flatten(),
682            };
683            assert_eq!(n.as_i64(), want_i64, "{text}");
684            assert_eq!(n.as_u64(), want_u64, "{text}");
685        }
686    }
687
688    fn f(x: f64) -> String {
689        format_f64(x).unwrap_or_default()
690    }
691
692    #[test]
693    fn test_format_f64_layouts() {
694        let cases: &[(f64, &str)] = &[
695            (0.0, "0.0"),
696            (-0.0, "-0.0"),
697            (1.0, "1.0"),
698            (1.5, "1.5"),
699            (100.0, "100.0"),
700            (123.456, "123.456"),
701            (0.1, "0.1"),
702            (1e-5, "0.00001"),
703            (1.5e-5, "0.000015"),
704            (1e-6, "1e-6"),
705            (1.5e-7, "1.5e-7"),
706            (1e15, "1000000000000000.0"),
707            (1e16, "1e16"),
708            (1.7976931348623157e308, "1.7976931348623157e308"),
709            (5e-324, "5e-324"),
710            (-2.2250738585072014e-308, "-2.2250738585072014e-308"),
711            (123456789012345.67, "123456789012345.67"),
712        ];
713        for &(x, want) in cases {
714            assert_eq!(f(x), want, "{x:e}");
715        }
716        assert!(format_f64(f64::NAN).is_none());
717        assert!(format_f64(f64::INFINITY).is_none());
718        assert!(format_f64(f64::NEG_INFINITY).is_none());
719    }
720
721    #[test]
722    fn test_integer_conversions_exact() {
723        assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
724        assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
725        assert_eq!(Number::from(u64::MAX).as_i64(), None);
726        assert_eq!(Number::from(-1i8).as_u64(), None);
727        assert_eq!(
728            Number::from(u128::MAX).as_str(),
729            "340282366920938463463374607431768211455"
730        );
731    }
732
733    #[test]
734    fn test_integer_writers_match_core_formatting() {
735        let mut out = String::new();
736        for n in [
737            0u64,
738            1,
739            9,
740            10,
741            99,
742            100,
743            12_345,
744            u64::from(u32::MAX),
745            u64::MAX,
746        ] {
747            out.clear();
748            write_u64(&mut out, n);
749            assert_eq!(out, alloc::format!("{n}"));
750        }
751        for n in [0i64, -1, 1, i64::MIN, i64::MAX, -1_000_000] {
752            out.clear();
753            write_i64(&mut out, n);
754            assert_eq!(out, alloc::format!("{n}"));
755        }
756        for n in [
757            0u128,
758            u128::from(u64::MAX),
759            u128::from(u64::MAX) + 1,
760            u128::MAX,
761        ] {
762            out.clear();
763            write_u128(&mut out, n);
764            assert_eq!(out, alloc::format!("{n}"));
765        }
766        for n in [i128::MIN, i128::MAX, -1, 0] {
767            out.clear();
768            write_i128(&mut out, n);
769            assert_eq!(out, alloc::format!("{n}"));
770        }
771        assert_eq!(Number::from(isize::MIN).as_i64(), Some(isize::MIN as i64));
772        assert_eq!(Number::from(usize::MAX).as_u64(), Some(usize::MAX as u64));
773    }
774
775    #[test]
776    fn test_whole_value_edges() {
777        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
778        assert_eq!(n("0").whole_value(), Some(0));
779        assert_eq!(n("-0.000e5").whole_value(), Some(0));
780        assert_eq!(n("1e-0").whole_value(), Some(1));
781        assert_eq!(n("1E+3").whole_value(), Some(1000));
782        assert_eq!(n("10e-1").whole_value(), Some(1));
783        assert_eq!(n("1e-1").whole_value(), None);
784        assert_eq!(n("1e99999999999999999999").whole_value(), None);
785        assert_eq!(n("1e-99999999999999999999").whole_value(), None);
786        assert_eq!(n("0e99999999999999999999").whole_value(), Some(0));
787        assert_eq!(
788            n("-170141183460469231731687303715884105728").whole_value(),
789            Some(i128::MIN)
790        );
791        assert_eq!(
792            n("170141183460469231731687303715884105728").whole_value(),
793            None
794        );
795        assert_eq!(
796            n("1.7014118346046923173168730371588410572e38").whole_value(),
797            Some(170_141_183_460_469_231_731_687_303_715_884_105_720)
798        );
799        assert_eq!(n("1.23e2").whole_value(), Some(123));
800    }
801
802    #[test]
803    fn test_wide_and_narrow_conversions() {
804        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
805        assert_eq!(n("170141183460469231731687303715884105728").as_i128(), None);
806        assert_eq!(n("2.5").as_u128(), None);
807        assert_eq!(n("2.5").as_i128(), None);
808        assert_eq!(n("12").as_u128(), Some(12));
809        assert_eq!(n("-3").as_f32(), Some(-3.0));
810        // The same text rounds to f32 directly: no double rounding.
811        assert_eq!(n("16777217").as_f32(), Some(16_777_216.0));
812    }
813
814    #[test]
815    fn test_f32_is_shortest_for_f32() {
816        let mut out = String::new();
817        assert!(write_f32(&mut out, 0.1));
818        assert_eq!(out, "0.1");
819        out.clear();
820        assert!(write_f32(&mut out, 1.0e20));
821        assert_eq!(out, "1e20");
822        assert!(!write_f32(&mut out, f32::NAN));
823        assert!(!write_f64(&mut out, f64::INFINITY));
824    }
825
826    proptest! {
827        #[test]
828        fn prop_f32_text_round_trips(bits in any::<u32>()) {
829            let x = f32::from_bits(bits);
830            prop_assume!(x.is_finite());
831            let mut out = String::new();
832            prop_assert!(write_f32(&mut out, x));
833            prop_assert!(lexer::is_number(&out), "{}", out);
834            prop_assert_eq!(out.parse::<f32>().map(f32::to_bits).ok(), Some(x.to_bits()));
835        }
836
837        /// Every spelling of an integer reads back as the integer.
838        #[test]
839        fn prop_whole_value_of_any_spelling(n in any::<i64>(), shift in 0usize..20, zeros in 0usize..4) {
840            let plain = alloc::format!("{n}");
841            prop_assert_eq!(Number::from_text(&plain).and_then(|x| x.whole_value()), Some(i128::from(n)));
842            // n * 10^shift written as n followed by `zeros` zeros and an exponent.
843            let spelled = alloc::format!("{n}{}e{}", "0".repeat(zeros), shift as i64 - zeros as i64);
844            let want = i128::from(n).checked_mul(10i128.pow(shift as u32));
845            prop_assert_eq!(Number::from_text(&spelled).and_then(|x| x.whole_value()), want);
846            let fraction = alloc::format!("{n}.{}", "0".repeat(zeros + 1));
847            prop_assert_eq!(Number::from_text(&fraction).and_then(|x| x.whole_value()), Some(i128::from(n)));
848        }
849
850        #[test]
851        fn prop_integer_writers_match_core(n in any::<i128>()) {
852            let mut out = String::new();
853            write_i128(&mut out, n);
854            prop_assert_eq!(out, alloc::format!("{n}"));
855        }
856
857        #[test]
858        fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
859            let x = f64::from_bits(bits);
860            prop_assume!(x.is_finite());
861            let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
862            prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
863            prop_assert!(!n.is_integer());
864            let back = n.as_f64().unwrap_or(f64::NAN);
865            prop_assert_eq!(back.to_bits(), x.to_bits());
866            // Shortest: no representation with fewer significant digits exists,
867            // which `{:e}` guarantees; check the text carries exactly its digits.
868            let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
869            let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
870            let trim = |d: &[u8]| -> Vec<u8> {
871                let s: &[u8] = d;
872                let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
873                let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
874                s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
875            };
876            prop_assert_eq!(trim(&digits), trim(&ours));
877        }
878
879        #[test]
880        fn prop_i64_round_trips(x in any::<i64>()) {
881            prop_assert_eq!(Number::from(x).as_i64(), Some(x));
882        }
883
884        #[test]
885        fn prop_u64_round_trips(x in any::<u64>()) {
886            prop_assert_eq!(Number::from(x).as_u64(), Some(x));
887        }
888    }
889}