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
43impl<'a> Number<'a> {
44 /// Wraps text the tokenizer has already checked.
45 #[inline]
46 pub(crate) const fn from_valid(text: &'a str) -> Self {
47 Self {
48 text: Cow::Borrowed(text),
49 }
50 }
51
52 /// Makes a number from its JSON text, which must be exactly one number in
53 /// RFC 8259 syntax with nothing around it. The text is borrowed, not
54 /// copied, so arbitrary-precision values pass through unchanged.
55 ///
56 /// Returns `None` for anything else: `+1`, `01`, `.5`, `1.`, `NaN`,
57 /// whitespace, or an empty string.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use jsonx_lib::{to_string, Number, Value};
63 ///
64 /// let price = Number::from_text("19.990").unwrap();
65 /// assert_eq!(to_string(&Value::Number(price)), "19.990");
66 /// assert!(Number::from_text("1.").is_none());
67 /// assert!(Number::from_text("0x10").is_none());
68 /// ```
69 #[must_use]
70 pub fn from_text(text: &'a str) -> Option<Self> {
71 lexer::is_number(text).then_some(Self::from_valid(text))
72 }
73
74 /// Makes a number from an `f64`, written as the shortest text that reads
75 /// back as the same `f64`. Returns `None` for NaN and the infinities,
76 /// which JSON cannot represent.
77 ///
78 /// The text has a fraction or an exponent, so it reads back as a float:
79 /// `1.0` is written `1.0`, not `1`. Values from 1e-5 up to below 1e16 are
80 /// written as decimals (`0.00001`, `123.456`, `1000000000000000.0`); the
81 /// rest in exponent form (`1e16`, `1.5e-7`, `-2.2250738585072014e-308`).
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use jsonx_lib::Number;
87 ///
88 /// assert_eq!(Number::from_f64(1.0).unwrap().as_str(), "1.0");
89 /// assert_eq!(Number::from_f64(-0.0).unwrap().as_str(), "-0.0");
90 /// assert_eq!(Number::from_f64(1e100).unwrap().as_str(), "1e100");
91 /// assert_eq!(Number::from_f64(0.1 + 0.2).unwrap().as_str(), "0.30000000000000004");
92 /// assert!(Number::from_f64(f64::NAN).is_none());
93 /// ```
94 #[must_use]
95 pub fn from_f64(value: f64) -> Option<Number<'static>> {
96 format_f64(value).map(|text| Number {
97 text: Cow::Owned(text),
98 })
99 }
100
101 /// The number's text, exactly as written in the document (or as this crate
102 /// wrote it, for a number made from a Rust value).
103 ///
104 /// # Examples
105 ///
106 /// ```
107 /// use jsonx_lib::parse;
108 ///
109 /// assert_eq!(parse("1E+02")?.as_number().unwrap().as_str(), "1E+02");
110 /// # Ok::<(), jsonx_lib::Error>(())
111 /// ```
112 #[inline]
113 #[must_use]
114 pub fn as_str(&self) -> &str {
115 &self.text
116 }
117
118 /// Whether the text is an integer: no fraction and no exponent. `2.0` and
119 /// `2e3` are not integers by this test, though their values are whole.
120 ///
121 /// # Examples
122 ///
123 /// ```
124 /// use jsonx_lib::Number;
125 ///
126 /// assert!(Number::from(-3).is_integer());
127 /// assert!(!Number::from_text("2.0").unwrap().is_integer());
128 /// ```
129 #[must_use]
130 pub fn is_integer(&self) -> bool {
131 !self.text.bytes().any(|b| matches!(b, b'.' | b'e' | b'E'))
132 }
133
134 /// The number as an `i64`, if its text is an integer (see
135 /// [`is_integer`](Self::is_integer)) in `i64`'s range. `None` otherwise:
136 /// nothing is rounded or truncated.
137 ///
138 /// # Examples
139 ///
140 /// ```
141 /// use jsonx_lib::Number;
142 ///
143 /// let n = |s| Number::from_text(s).unwrap();
144 /// assert_eq!(n("-9223372036854775808").as_i64(), Some(i64::MIN));
145 /// assert_eq!(n("9223372036854775808").as_i64(), None); // out of range
146 /// assert_eq!(n("3.0").as_i64(), None); // not an integer's text
147 /// ```
148 #[must_use]
149 pub fn as_i64(&self) -> Option<i64> {
150 if self.is_integer() {
151 self.text.parse().ok()
152 } else {
153 None
154 }
155 }
156
157 /// The number as a `u64`, if its text is an integer (see
158 /// [`is_integer`](Self::is_integer)) in `u64`'s range. `-0` reads as `0`.
159 /// `None` otherwise: nothing is rounded or truncated.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use jsonx_lib::Number;
165 ///
166 /// let n = |s| Number::from_text(s).unwrap();
167 /// assert_eq!(n("18446744073709551615").as_u64(), Some(u64::MAX));
168 /// assert_eq!(n("-1").as_u64(), None);
169 /// assert_eq!(n("-0").as_u64(), Some(0));
170 /// ```
171 #[must_use]
172 pub fn as_u64(&self) -> Option<u64> {
173 if !self.is_integer() {
174 return None;
175 }
176 match self.text.strip_prefix('-') {
177 // The grammar forbids leading zeros, so `-0` is the only negative
178 // integer text with a value `u64` can hold.
179 Some("0") => Some(0),
180 Some(_) => None,
181 None => self.text.parse().ok(),
182 }
183 }
184
185 /// The number as the nearest `f64` (correctly rounded), or `None` if it is
186 /// too large in magnitude to be finite (`1e400`). A value too small to
187 /// represent rounds to zero, as IEEE 754 does. Integers beyond 2^53 lose
188 /// precision; use [`as_i64`](Self::as_i64), [`as_u64`](Self::as_u64), or
189 /// the exact [`as_str`](Self::as_str) when that matters.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use jsonx_lib::Number;
195 ///
196 /// let n = |s| Number::from_text(s).unwrap();
197 /// assert_eq!(n("2.5e-3").as_f64(), Some(0.0025));
198 /// assert_eq!(n("7").as_f64(), Some(7.0));
199 /// assert_eq!(n("1e400").as_f64(), None);
200 /// ```
201 #[must_use]
202 pub fn as_f64(&self) -> Option<f64> {
203 self.text.parse::<f64>().ok().filter(|x| x.is_finite())
204 }
205
206 /// Copies borrowed text so the number no longer borrows from the input.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use jsonx_lib::Number;
212 ///
213 /// let owned: Number<'static> = {
214 /// let text = String::from("12.5");
215 /// Number::from_text(&text).unwrap().into_owned()
216 /// };
217 /// assert_eq!(owned.as_str(), "12.5");
218 /// ```
219 #[must_use]
220 pub fn into_owned(self) -> Number<'static> {
221 Number {
222 text: Cow::Owned(self.text.into_owned()),
223 }
224 }
225}
226
227macro_rules! from_integer {
228 ($($t:ty),*) => {$(
229 impl From<$t> for Number<'static> {
230 /// Writes the integer in decimal.
231 #[inline]
232 fn from(value: $t) -> Self {
233 let mut text = String::new();
234 // Writing to a `String` cannot fail.
235 let _infallible = write!(text, "{value}");
236 Self { text: Cow::Owned(text) }
237 }
238 }
239 )*};
240}
241
242from_integer!(
243 i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
244);
245
246impl fmt::Display for Number<'_> {
247 /// Writes the number's exact text.
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 f.write_str(&self.text)
250 }
251}
252
253impl fmt::Debug for Number<'_> {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(&self.text)
256 }
257}
258
259/// A fixed buffer for `core::fmt` output, so formatting an `f64` needs no
260/// allocation before the final text is built.
261struct StackText {
262 buf: [u8; 40],
263 len: usize,
264}
265
266impl fmt::Write for StackText {
267 fn write_str(&mut self, s: &str) -> fmt::Result {
268 let end = self.len + s.len();
269 let slot = self.buf.get_mut(self.len..end).ok_or(fmt::Error)?;
270 slot.copy_from_slice(s.as_bytes());
271 self.len = end;
272 Ok(())
273 }
274}
275
276/// Pushes `count` ASCII zeros.
277fn zeros(out: &mut String, count: usize) {
278 out.extend(core::iter::repeat_n('0', count));
279}
280
281/// The shortest round-trip text for a finite `f64`, laid out as described on
282/// [`Number::from_f64`].
283///
284/// `core`'s `{:e}` formatting already yields the shortest digit string that
285/// reads back as the same `f64` (it is the same algorithm `Display` uses); this
286/// only moves the decimal point.
287fn format_f64(value: f64) -> Option<String> {
288 if !value.is_finite() {
289 return None;
290 }
291 let mut sci = StackText {
292 buf: [0; 40],
293 len: 0,
294 };
295 write!(sci, "{value:e}").ok()?;
296 let sci = core::str::from_utf8(sci.buf.get(..sci.len)?).ok()?;
297 let (negative, sci) = match sci.strip_prefix('-') {
298 Some(rest) => (true, rest),
299 None => (false, sci),
300 };
301 let (mantissa, exponent) = sci.split_once('e')?;
302 let exponent: i32 = exponent.parse().ok()?;
303 // `{:e}` writes one digit before the point.
304 let (lead, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
305
306 let mut out = String::with_capacity(26);
307 if negative {
308 out.push('-');
309 }
310 if (-5..16).contains(&exponent) {
311 if let Ok(point) = usize::try_from(exponent) {
312 // `point` digits of `frac` go before the decimal point.
313 out.push_str(lead);
314 if frac.len() <= point {
315 out.push_str(frac);
316 zeros(&mut out, point - frac.len());
317 out.push_str(".0");
318 } else {
319 out.push_str(frac.get(..point)?);
320 out.push('.');
321 out.push_str(frac.get(point..)?);
322 }
323 } else {
324 out.push_str("0.");
325 zeros(&mut out, exponent.unsigned_abs() as usize - 1);
326 out.push_str(lead);
327 out.push_str(frac);
328 }
329 } else {
330 out.push_str(lead);
331 if !frac.is_empty() {
332 out.push('.');
333 out.push_str(frac);
334 }
335 write!(out, "e{exponent}").ok()?;
336 }
337 Some(out)
338}
339
340#[cfg(test)]
341mod tests {
342 use alloc::vec::Vec;
343
344 use proptest::prelude::*;
345
346 use super::*;
347
348 fn f(x: f64) -> String {
349 format_f64(x).unwrap_or_default()
350 }
351
352 #[test]
353 fn test_format_f64_layouts() {
354 let cases: &[(f64, &str)] = &[
355 (0.0, "0.0"),
356 (-0.0, "-0.0"),
357 (1.0, "1.0"),
358 (1.5, "1.5"),
359 (100.0, "100.0"),
360 (123.456, "123.456"),
361 (0.1, "0.1"),
362 (1e-5, "0.00001"),
363 (1.5e-5, "0.000015"),
364 (1e-6, "1e-6"),
365 (1.5e-7, "1.5e-7"),
366 (1e15, "1000000000000000.0"),
367 (1e16, "1e16"),
368 (1.7976931348623157e308, "1.7976931348623157e308"),
369 (5e-324, "5e-324"),
370 (-2.2250738585072014e-308, "-2.2250738585072014e-308"),
371 (123456789012345.67, "123456789012345.67"),
372 ];
373 for &(x, want) in cases {
374 assert_eq!(f(x), want, "{x:e}");
375 }
376 assert!(format_f64(f64::NAN).is_none());
377 assert!(format_f64(f64::INFINITY).is_none());
378 assert!(format_f64(f64::NEG_INFINITY).is_none());
379 }
380
381 #[test]
382 fn test_integer_conversions_exact() {
383 assert_eq!(Number::from(i64::MIN).as_i64(), Some(i64::MIN));
384 assert_eq!(Number::from(u64::MAX).as_u64(), Some(u64::MAX));
385 assert_eq!(Number::from(u64::MAX).as_i64(), None);
386 assert_eq!(Number::from(-1i8).as_u64(), None);
387 assert_eq!(
388 Number::from(u128::MAX).as_str(),
389 "340282366920938463463374607431768211455"
390 );
391 }
392
393 proptest! {
394 #[test]
395 fn prop_f64_text_is_valid_and_round_trips(bits in any::<u64>()) {
396 let x = f64::from_bits(bits);
397 prop_assume!(x.is_finite());
398 let n = Number::from_f64(x).unwrap_or_else(|| Number::from(0));
399 prop_assert!(lexer::is_number(n.as_str()), "{}", n.as_str());
400 prop_assert!(!n.is_integer());
401 let back = n.as_f64().unwrap_or(f64::NAN);
402 prop_assert_eq!(back.to_bits(), x.to_bits());
403 // Shortest: no representation with fewer significant digits exists,
404 // which `{:e}` guarantees; check the text carries exactly its digits.
405 let digits: Vec<u8> = alloc::format!("{x:e}").bytes().take_while(|&b| b != b'e').filter(u8::is_ascii_digit).collect();
406 let ours: Vec<u8> = n.as_str().bytes().take_while(|&b| b != b'e' && b != b'E').filter(u8::is_ascii_digit).collect();
407 let trim = |d: &[u8]| -> Vec<u8> {
408 let s: &[u8] = d;
409 let start = s.iter().position(|&b| b != b'0').unwrap_or(s.len());
410 let end = s.iter().rposition(|&b| b != b'0').map_or(start, |e| e + 1);
411 s.get(start..end.max(start)).unwrap_or(&[]).to_vec()
412 };
413 prop_assert_eq!(trim(&digits), trim(&ours));
414 }
415
416 #[test]
417 fn prop_i64_round_trips(x in any::<i64>()) {
418 prop_assert_eq!(Number::from(x).as_i64(), Some(x));
419 }
420
421 #[test]
422 fn prop_u64_round_trips(x in any::<u64>()) {
423 prop_assert_eq!(Number::from(x).as_u64(), Some(x));
424 }
425 }
426}