Skip to main content

Number

Struct Number 

Source
pub struct Number<'a> { /* private fields */ }
Expand description

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, as_u64, or 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 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");

Implementations§

Source§

impl<'a> Number<'a>

Source

pub fn from_text(text: &'a str) -> Option<Self>

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());
Source

pub fn from_f64(value: f64) -> Option<Number<'static>>

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());
Source

pub fn as_str(&self) -> &str

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");
Source

pub fn is_integer(&self) -> bool

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());
Source

pub fn as_i64(&self) -> Option<i64>

The number as an i64, if its text is an integer (see 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
Source

pub fn as_u64(&self) -> Option<u64>

The number as a u64, if its text is an integer (see 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));
Source

pub fn as_i128(&self) -> Option<i128>

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);
Source

pub fn as_u128(&self) -> Option<u128>

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);
Source

pub fn whole_value(&self) -> Option<i128>

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 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.

§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
Source

pub fn as_f32(&self) -> Option<f32>

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);
Source

pub fn as_f64(&self) -> Option<f64>

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, as_u64, or the exact 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);
Source

pub fn into_owned(self) -> Number<'static>

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");

Trait Implementations§

Source§

impl<'a> Clone for Number<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Number<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Number<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Writes the number’s exact text.

Source§

impl<'a> Eq for Number<'a>

Source§

impl<'a> From<Number<'a>> for Value<'a>

Source§

fn from(n: Number<'a>) -> Self

Converts to this type from the input type.
Source§

impl From<i8> for Number<'static>

Source§

fn from(value: i8) -> Self

Writes the integer in decimal.

Source§

impl From<i16> for Number<'static>

Source§

fn from(value: i16) -> Self

Writes the integer in decimal.

Source§

impl From<i32> for Number<'static>

Source§

fn from(value: i32) -> Self

Writes the integer in decimal.

Source§

impl From<i64> for Number<'static>

Source§

fn from(value: i64) -> Self

Writes the integer in decimal.

Source§

impl From<i128> for Number<'static>

Source§

fn from(value: i128) -> Self

Writes the integer in decimal.

Source§

impl From<isize> for Number<'static>

Source§

fn from(value: isize) -> Self

Writes the integer in decimal.

Source§

impl From<u8> for Number<'static>

Source§

fn from(value: u8) -> Self

Writes the integer in decimal.

Source§

impl From<u16> for Number<'static>

Source§

fn from(value: u16) -> Self

Writes the integer in decimal.

Source§

impl From<u32> for Number<'static>

Source§

fn from(value: u32) -> Self

Writes the integer in decimal.

Source§

impl From<u64> for Number<'static>

Source§

fn from(value: u64) -> Self

Writes the integer in decimal.

Source§

impl From<u128> for Number<'static>

Source§

fn from(value: u128) -> Self

Writes the integer in decimal.

Source§

impl From<usize> for Number<'static>

Source§

fn from(value: usize) -> Self

Writes the integer in decimal.

Source§

impl<'de> FromJson<'de> for Number<'de>

Source§

fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError>

Reads one value from reader, which is positioned where a value comes next. Read more
Source§

fn absent() -> Option<Self>

The value for an object member that is absent, if absence is allowed: None (absence is an error) by default, Some(None) for Option<T>, and Some(Nullable::Absent) for Nullable<T>. Read more
Source§

impl<'a> Hash for Number<'a>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> PartialEq for Number<'a>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<'a> StructuralPartialEq for Number<'a>

Source§

impl ToJson for Number<'_>

Source§

fn to_json(&self, out: ValueWriter<'_>) -> Written

Writes self as one JSON value.
Source§

fn is_absent(&self) -> bool

Whether ObjectWriter::optional leaves this member out. false, except for Option<T>, where it is is_none(), and the pointer types, which ask what they point to. Read more

Auto Trait Implementations§

§

impl<'a> Forget for Number<'a>

§

impl<'a> Freeze for Number<'a>

§

impl<'a> Move for Number<'a>

§

impl<'a> RefUnwindSafe for Number<'a>

§

impl<'a> Send for Number<'a>

§

impl<'a> Sync for Number<'a>

§

impl<'a> Unpin for Number<'a>

§

impl<'a> UnsafeUnpin for Number<'a>

§

impl<'a> UnwindSafe for Number<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.