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;
5
6use crate::{Format, float, 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/// Pushes `count` ASCII zeros.
466#[cfg(test)]
467fn zeros(out: &mut String, count: usize) {
468    out.extend(core::iter::repeat_n('0', count));
469}
470
471/// Appends `value` in decimal. Digits are produced into a stack buffer, so
472/// nothing is allocated beyond `out`'s own growth.
473#[inline]
474pub(crate) fn write_u64(out: &mut String, value: u64) {
475    let mut digits = [0u8; 20];
476    let start = float::put_digits(&mut digits, 20, value);
477    float::push_ascii(out, digits.get(start..).unwrap_or_default());
478}
479
480/// Appends `value` in decimal.
481#[inline]
482pub(crate) fn write_i64(out: &mut String, value: i64) {
483    if value < 0 {
484        out.push('-');
485    }
486    write_u64(out, value.unsigned_abs());
487}
488
489/// Appends `value` in decimal; 128-bit division only above `u64::MAX`.
490pub(crate) fn write_u128(out: &mut String, value: u128) {
491    if let Ok(small) = u64::try_from(value) {
492        return write_u64(out, small);
493    }
494    let mut digits = [0u8; 39];
495    let mut at = digits.len();
496    let mut rest = value;
497    while rest > 0 {
498        at -= 1;
499        if let Some(slot) = digits.get_mut(at) {
500            *slot = b'0' + (rest % 10) as u8;
501        }
502        rest /= 10;
503    }
504    out.push_str(core::str::from_utf8(digits.get(at..).unwrap_or_default()).unwrap_or("0"));
505}
506
507/// Appends `value` in decimal.
508pub(crate) fn write_i128(out: &mut String, value: i128) {
509    if value < 0 {
510        out.push('-');
511    }
512    write_u128(out, value.unsigned_abs());
513}
514
515/// The shortest round-trip text for a finite `f64`, laid out as described on
516/// [`Number::from_f64`].
517fn format_f64(value: f64) -> Option<String> {
518    let mut out = String::with_capacity(26);
519    write_f64(&mut out, value).then_some(out)
520}
521
522/// Appends the shortest round-trip text for `value`, laid out as described
523/// on [`Number::from_f64`]. Returns `false`, writing nothing, for NaN and
524/// the infinities.
525#[inline]
526pub(crate) fn write_f64(out: &mut String, value: f64) -> bool {
527    write_f64_as(out, value, Format::compact())
528}
529
530/// [`write_f64`] with the float options of `format`: the `+` of a positive
531/// exponent, and how an exact tie is broken.
532pub(crate) fn write_f64_as(out: &mut String, value: f64, format: Format) -> bool {
533    if !value.is_finite() {
534        return false;
535    }
536    let decimal = float::f64_decimal(value, format.ties());
537    float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
538    true
539}
540
541/// As [`write_f64`] for an `f32`: the shortest text that reads back as the
542/// same `f32` (`0.1f32` is `0.1`, not the `0.10000000149011612` of its
543/// widening to `f64`).
544#[cfg(test)]
545pub(crate) fn write_f32(out: &mut String, value: f32) -> bool {
546    write_f32_as(out, value, Format::compact())
547}
548
549/// [`write_f32`] with the float options of `format`.
550pub(crate) fn write_f32_as(out: &mut String, value: f32, format: Format) -> bool {
551    if !value.is_finite() {
552        return false;
553    }
554    let decimal = float::f32_decimal(value, format.ties());
555    float::write_decimal(out, value.is_sign_negative(), decimal, format.exponent_plus);
556    true
557}
558
559/// The text 0.5.0 wrote, kept as the reference the tests compare with:
560/// `core`'s `{:e}` digits, laid out with decimals for exponents from -5 up
561/// to 15 and exponent form otherwise.
562#[cfg(test)]
563pub(crate) fn core_text(sci: &str) -> String {
564    let mut out = String::new();
565    let (negative, sci) = match sci.strip_prefix('-') {
566        Some(rest) => (true, rest),
567        None => (false, sci),
568    };
569    let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
570    let exponent: i32 = exponent.parse().unwrap_or(0);
571    let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
572    if negative {
573        out.push('-');
574    }
575    if (-5..16).contains(&exponent) {
576        if let Ok(point) = usize::try_from(exponent) {
577            out.push_str(lead);
578            if frac.len() <= point {
579                out.push_str(frac);
580                zeros(&mut out, point - frac.len());
581                out.push_str(".0");
582            } else {
583                let (int, rest) = frac.split_at_checked(point).unwrap_or((frac, ""));
584                out.push_str(int);
585                out.push('.');
586                out.push_str(rest);
587            }
588        } else {
589            out.push_str("0.");
590            zeros(&mut out, exponent.unsigned_abs() as usize - 1);
591            out.push_str(lead);
592            out.push_str(frac);
593        }
594    } else {
595        out.push_str(lead);
596        if !frac.is_empty() {
597            out.push('.');
598            out.push_str(frac);
599        }
600        out.push('e');
601        out.push_str(&alloc::format!("{exponent}"));
602    }
603    out
604}
605
606#[cfg(test)]
607mod tests {
608    use alloc::vec::Vec;
609
610    use proptest::prelude::*;
611
612    use super::*;
613
614    #[test]
615    fn test_integer_reads_agree_with_the_standard_parser() {
616        let texts = [
617            "0",
618            "-0",
619            "1",
620            "-1",
621            "9",
622            "10",
623            "18446744073709551615",
624            "18446744073709551616",
625            "99999999999999999999",
626            "100000000000000000000",
627            "9223372036854775807",
628            "9223372036854775808",
629            "-9223372036854775808",
630            "-9223372036854775809",
631            "1234567890123456789",
632            "12345678901234567890",
633            "-12345678901234567890",
634            "1.0",
635            "1e2",
636            "-1.5",
637            "0.0",
638            "-0e0",
639            "123456789012345678901234567890",
640        ];
641        for text in texts {
642            let n = Number::from_text(text).unwrap();
643            let integer = n.is_integer();
644            let want_i64 = integer.then(|| text.parse::<i64>().ok()).flatten();
645            let want_u64 = match text.strip_prefix('-') {
646                Some("0") => Some(0),
647                Some(_) => None,
648                None => integer.then(|| text.parse::<u64>().ok()).flatten(),
649            };
650            assert_eq!(n.as_i64(), want_i64, "{text}");
651            assert_eq!(n.as_u64(), want_u64, "{text}");
652        }
653    }
654
655    fn f(x: f64) -> String {
656        format_f64(x).unwrap_or_default()
657    }
658
659    #[test]
660    fn test_format_f64_layouts() {
661        let cases: &[(f64, &str)] = &[
662            (0.0, "0.0"),
663            (-0.0, "-0.0"),
664            (1.0, "1.0"),
665            (1.5, "1.5"),
666            (100.0, "100.0"),
667            (123.456, "123.456"),
668            (0.1, "0.1"),
669            (1e-5, "0.00001"),
670            (1.5e-5, "0.000015"),
671            (1e-6, "1e-6"),
672            (1.5e-7, "1.5e-7"),
673            (1e15, "1000000000000000.0"),
674            (1e16, "1e16"),
675            (1.7976931348623157e308, "1.7976931348623157e308"),
676            (5e-324, "5e-324"),
677            (-2.2250738585072014e-308, "-2.2250738585072014e-308"),
678            (123456789012345.67, "123456789012345.67"),
679        ];
680        for &(x, want) in cases {
681            assert_eq!(f(x), want, "{x:e}");
682        }
683        assert!(format_f64(f64::NAN).is_none());
684        assert!(format_f64(f64::INFINITY).is_none());
685        assert!(format_f64(f64::NEG_INFINITY).is_none());
686    }
687
688    #[test]
689    fn test_integer_conversions_exact() {
690        assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
691        assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
692        assert_eq!(Number::from(u64::MAX).as_i64(), None);
693        assert_eq!(Number::from(-1i8).as_u64(), None);
694        assert_eq!(
695            Number::from(u128::MAX).as_str(),
696            "340282366920938463463374607431768211455"
697        );
698    }
699
700    #[test]
701    fn test_integer_writers_match_core_formatting() {
702        let mut out = String::new();
703        for n in [
704            0u64,
705            1,
706            9,
707            10,
708            99,
709            100,
710            12_345,
711            u64::from(u32::MAX),
712            u64::MAX,
713        ] {
714            out.clear();
715            write_u64(&mut out, n);
716            assert_eq!(out, alloc::format!("{n}"));
717        }
718        for n in [0i64, -1, 1, i64::MIN, i64::MAX, -1_000_000] {
719            out.clear();
720            write_i64(&mut out, n);
721            assert_eq!(out, alloc::format!("{n}"));
722        }
723        for n in [
724            0u128,
725            u128::from(u64::MAX),
726            u128::from(u64::MAX) + 1,
727            u128::MAX,
728        ] {
729            out.clear();
730            write_u128(&mut out, n);
731            assert_eq!(out, alloc::format!("{n}"));
732        }
733        for n in [i128::MIN, i128::MAX, -1, 0] {
734            out.clear();
735            write_i128(&mut out, n);
736            assert_eq!(out, alloc::format!("{n}"));
737        }
738        assert_eq!(Number::from(isize::MIN).as_i64(), Some(isize::MIN as i64));
739        assert_eq!(Number::from(usize::MAX).as_u64(), Some(usize::MAX as u64));
740    }
741
742    #[test]
743    fn test_whole_value_edges() {
744        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
745        assert_eq!(n("0").whole_value(), Some(0));
746        assert_eq!(n("-0.000e5").whole_value(), Some(0));
747        assert_eq!(n("1e-0").whole_value(), Some(1));
748        assert_eq!(n("1E+3").whole_value(), Some(1000));
749        assert_eq!(n("10e-1").whole_value(), Some(1));
750        assert_eq!(n("1e-1").whole_value(), None);
751        assert_eq!(n("1e99999999999999999999").whole_value(), None);
752        assert_eq!(n("1e-99999999999999999999").whole_value(), None);
753        assert_eq!(n("0e99999999999999999999").whole_value(), Some(0));
754        assert_eq!(
755            n("-170141183460469231731687303715884105728").whole_value(),
756            Some(i128::MIN)
757        );
758        assert_eq!(
759            n("170141183460469231731687303715884105728").whole_value(),
760            None
761        );
762        assert_eq!(
763            n("1.7014118346046923173168730371588410572e38").whole_value(),
764            Some(170_141_183_460_469_231_731_687_303_715_884_105_720)
765        );
766        assert_eq!(n("1.23e2").whole_value(), Some(123));
767    }
768
769    #[test]
770    fn test_wide_and_narrow_conversions() {
771        let n = |t: &'static str| Number::from_text(t).unwrap_or_else(|| Number::from(0));
772        assert_eq!(n("170141183460469231731687303715884105728").as_i128(), None);
773        assert_eq!(n("2.5").as_u128(), None);
774        assert_eq!(n("2.5").as_i128(), None);
775        assert_eq!(n("12").as_u128(), Some(12));
776        assert_eq!(n("-3").as_f32(), Some(-3.0));
777        // The same text rounds to f32 directly: no double rounding.
778        assert_eq!(n("16777217").as_f32(), Some(16_777_216.0));
779    }
780
781    #[test]
782    fn test_f32_is_shortest_for_f32() {
783        let mut out = String::new();
784        assert!(write_f32(&mut out, 0.1));
785        assert_eq!(out, "0.1");
786        out.clear();
787        assert!(write_f32(&mut out, 1.0e20));
788        assert_eq!(out, "1e20");
789        assert!(!write_f32(&mut out, f32::NAN));
790        assert!(!write_f64(&mut out, f64::INFINITY));
791    }
792
793    #[test]
794    fn test_float_options_through_format() {
795        let both = Format::compact().exponent_plus(true).even_ties(true);
796        let tie = 164_696_460_098_373.0 + 0.625;
797        let text = |x: f64, format: Format| {
798            let mut out = String::new();
799            assert!(write_f64_as(&mut out, x, format));
800            out
801        };
802        assert_eq!(text(1e16, both), "1e+16");
803        assert_eq!(text(-1e-7, both), "-1e-7");
804        assert_eq!(text(tie, both), "164696460098373.62");
805        assert_eq!(
806            text(tie, Format::compact().exponent_plus(true)),
807            "164696460098373.63"
808        );
809        assert_eq!(text(1e300, Format::pretty().exponent_plus(true)), "1e+300");
810        let mut out = String::new();
811        assert!(write_f32_as(&mut out, 1e20, both));
812        assert_eq!(out, "1e+20");
813        assert!(!write_f32_as(&mut out, f32::INFINITY, both));
814        assert!(!write_f64_as(&mut out, f64::NAN, both));
815        assert_eq!(out, "1e+20");
816        // The options ride along with the other settings.
817        let f = Format::compact()
818            .html_safe(true)
819            .exponent_plus(true)
820            .even_ties(true);
821        assert!(f.exponent_plus && f.even_ties && f.html && !f.pretty);
822        assert_eq!(Format::default(), Format::compact());
823        assert_ne!(both, Format::compact());
824    }
825
826    proptest! {
827        /// With both float options on, the text is still one valid JSON
828        /// number that reads back as the same float; the `+` alone is the
829        /// only difference `exponent_plus` makes.
830        #[test]
831        fn prop_float_options_keep_the_value(bits in any::<u64>()) {
832            let x = f64::from_bits(bits);
833            prop_assume!(x.is_finite());
834            let both = Format::compact().exponent_plus(true).even_ties(true);
835            let mut out = String::new();
836            prop_assert!(write_f64_as(&mut out, x, both));
837            prop_assert!(lexer::is_number(&out), "{}", out);
838            prop_assert_eq!(out.parse::<f64>().map(f64::to_bits).ok(), Some(x.to_bits()));
839            let mut plain = String::new();
840            prop_assert!(write_f64_as(&mut plain, x, Format::compact().exponent_plus(true)));
841            let mut default = String::new();
842            prop_assert!(write_f64(&mut default, x));
843            prop_assert_eq!(plain.replacen("e+", "e", 1), default);
844        }
845
846        #[test]
847        fn prop_f32_text_round_trips(bits in any::<u32>()) {
848            let x = f32::from_bits(bits);
849            prop_assume!(x.is_finite());
850            let mut out = String::new();
851            prop_assert!(write_f32(&mut out, x));
852            prop_assert!(lexer::is_number(&out), "{}", out);
853            prop_assert_eq!(out.parse::<f32>().map(f32::to_bits).ok(), Some(x.to_bits()));
854        }
855
856        /// Every spelling of an integer reads back as the integer.
857        #[test]
858        fn prop_whole_value_of_any_spelling(n in any::<i64>(), shift in 0usize..20, zeros in 0usize..4) {
859            let plain = alloc::format!("{n}");
860            prop_assert_eq!(Number::from_text(&plain).and_then(|x| x.whole_value()), Some(i128::from(n)));
861            // n * 10^shift written as n followed by `zeros` zeros and an exponent.
862            let spelled = alloc::format!("{n}{}e{}", "0".repeat(zeros), shift as i64 - zeros as i64);
863            let want = i128::from(n).checked_mul(10i128.pow(shift as u32));
864            prop_assert_eq!(Number::from_text(&spelled).and_then(|x| x.whole_value()), want);
865            let fraction = alloc::format!("{n}.{}", "0".repeat(zeros + 1));
866            prop_assert_eq!(Number::from_text(&fraction).and_then(|x| x.whole_value()), Some(i128::from(n)));
867        }
868
869        #[test]
870        fn prop_integer_writers_match_core(n in any::<i128>()) {
871            let mut out = String::new();
872            write_i128(&mut out, n);
873            prop_assert_eq!(out, alloc::format!("{n}"));
874        }
875
876        #[test]
877        fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
878            let x = f64::from_bits(bits);
879            prop_assume!(x.is_finite());
880            let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
881            prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
882            prop_assert!(!n.is_integer());
883            let back = n.as_f64().unwrap_or(f64::NAN);
884            prop_assert_eq!(back.to_bits(), x.to_bits());
885            // Shortest: no representation with fewer significant digits exists,
886            // which `{:e}` guarantees; check the text carries exactly its digits.
887            let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
888            let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
889            let trim = |d: &[u8]| -> Vec<u8> {
890                let s: &[u8] = d;
891                let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
892                let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
893                s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
894            };
895            prop_assert_eq!(trim(&digits), trim(&ours));
896        }
897
898        #[test]
899        fn prop_i64_round_trips(x in any::<i64>()) {
900            prop_assert_eq!(Number::from(x).as_i64(), Some(x));
901        }
902
903        #[test]
904        fn prop_u64_round_trips(x in any::<u64>()) {
905            prop_assert_eq!(Number::from(x).as_u64(), Some(x));
906        }
907    }
908}