Skip to content

Add support for 'nan' #921

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,22 @@ impl<'de, R: Read<'de>> Deserializer<R> {
let err = match self.peek_or_null().unwrap_or(b'\x00') {
b'n' => {
self.eat_char();
if let Err(err) = self.parse_ident(b"ull") {
return err;
match self.peek_or_null().unwrap_or(b'\x00') {
#[cfg(feature = "std")]
b'a' => {
if let Err(err) = self.parse_ident(b"an") {
return err;
}
de::Error::invalid_type(Unexpected::Float(::std::f64::NAN), exp)
}
b'u' => {
if let Err(err) = self.parse_ident(b"ull") {
return err;
}
de::Error::invalid_type(Unexpected::Unit, exp)
}
_ => self.peek_error(ErrorCode::ExpectedSomeValue),
}
de::Error::invalid_type(Unexpected::Unit, exp)
}
b't' => {
self.eat_char();
Expand Down Expand Up @@ -326,6 +338,12 @@ impl<'de, R: Read<'de>> Deserializer<R> {
tri!(self.parse_integer(false)).visit(visitor)
}
b'0'..=b'9' => tri!(self.parse_integer(true)).visit(visitor),
#[cfg(feature = "std")]
b'n' => {
self.eat_char();
tri!(self.parse_ident(b"an"));
tri!(Ok(ParserNumber::F64(::std::f64::NAN))).visit(visitor)
}
_ => Err(self.peek_invalid_type(&visitor)),
};

Expand Down Expand Up @@ -1321,8 +1339,19 @@ impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> {
let value = match peek {
b'n' => {
self.eat_char();
tri!(self.parse_ident(b"ull"));
visitor.visit_unit()
match tri!(self.peek()) {
#[cfg(feature = "std")]
Some(b'a') => {
tri!(self.parse_ident(b"an"));
visitor.visit_f64(::std::f64::NAN)
}
Some(b'u') => {
tri!(self.parse_ident(b"ull"));
visitor.visit_unit()
}
Some(_) => Err(self.peek_invalid_type(&visitor)),
None => Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
b't' => {
self.eat_char();
Expand Down
5 changes: 5 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ macro_rules! json_internal {
let _ = $object.insert(($($key)+).into(), $value);
};

// Next value is `nan`.
(@object $object:ident ($($key:tt)+) (: nan $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!(::std::f64::NAN)) $($rest)*);
};

// Next value is `null`.
(@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => {
json_internal!(@object $object [$($key)+] (json_internal!(null)) $($rest)*);
Expand Down
18 changes: 13 additions & 5 deletions src/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ impl Number {
/// ```
/// # use serde_json::json;
/// #
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
/// let v = json!({ "a": 256.0, "b": 64, "c": -64});
///
/// assert!(v["a"].is_f64());
///
Expand Down Expand Up @@ -230,7 +230,7 @@ impl Number {
/// ```
/// # use serde_json::json;
/// #
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
/// let v = json!({ "a": 256.0, "b": 64, "c": -64});
///
/// assert_eq!(v["a"].as_f64(), Some(256.0));
/// assert_eq!(v["b"].as_f64(), Some(64.0));
Expand All @@ -245,7 +245,7 @@ impl Number {
N::Float(n) => Some(n),
}
#[cfg(feature = "arbitrary_precision")]
self.n.parse::<f64>().ok().filter(|float| float.is_finite())
self.n.parse::<f64>().ok().filter(|float| !float.is_infinite())
}

/// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON
Expand All @@ -258,7 +258,7 @@ impl Number {
/// #
/// assert!(Number::from_f64(256.0).is_some());
///
/// assert!(Number::from_f64(f64::NAN).is_none());
/// assert!(Number::from_f64(f64::INFINITY).is_none());
/// ```
#[inline]
pub fn from_f64(f: f64) -> Option<Number> {
Expand All @@ -275,6 +275,14 @@ impl Number {
};
Some(Number { n })
} else {
#[cfg(all(not(feature = "arbitrary_precision"), feature = "std"))]
{
if f.is_nan() {
return Some(Number {
n: N::Float(::std::f64::NAN),
});
}
}
None
}
}
Expand All @@ -294,7 +302,7 @@ impl Display for Number {
match self.n {
N::PosInt(u) => formatter.write_str(itoa::Buffer::new().format(u)),
N::NegInt(i) => formatter.write_str(itoa::Buffer::new().format(i)),
N::Float(f) => formatter.write_str(ryu::Buffer::new().format_finite(f)),
N::Float(f) => formatter.write_str(ryu::Buffer::new().format(f)),
}
}

Expand Down
16 changes: 14 additions & 2 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,13 @@ where
#[inline]
fn serialize_f32(self, value: f32) -> Result<()> {
match value.classify() {
FpCategory::Nan | FpCategory::Infinite => {
FpCategory::Nan => {
tri!(self
.formatter
.write_number_str(&mut self.writer, "nan")
.map_err(Error::io));
}
FpCategory::Infinite => {
tri!(self
.formatter
.write_null(&mut self.writer)
Expand All @@ -192,7 +198,13 @@ where
#[inline]
fn serialize_f64(self, value: f64) -> Result<()> {
match value.classify() {
FpCategory::Nan | FpCategory::Infinite => {
FpCategory::Nan => {
tri!(self
.formatter
.write_number_str(&mut self.writer, "nan")
.map_err(Error::io));
}
FpCategory::Infinite => {
tri!(self
.formatter
.write_null(&mut self.writer)
Expand Down
3 changes: 3 additions & 0 deletions tests/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ fn value_bool() {

#[test]
fn value_number() {
#[cfg(all(not(feature = "arbitrary_precision"), feature = "std"))]
assert_eq!(format!("{:?}", json!(::std::f64::NAN)), "Number(NaN)");

assert_eq!(format!("{:?}", json!(1)), "Number(1)");
assert_eq!(format!("{:?}", json!(-1)), "Number(-1)");
assert_eq!(format!("{:?}", json!(1.0)), "Number(1.0)");
Expand Down
23 changes: 21 additions & 2 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,21 @@ fn test_write_f64() {
#[test]
fn test_encode_nonfinite_float_yields_null() {
let v = to_value(::std::f64::NAN).unwrap();
assert!(v.is_null());
if !cfg!(feature = "arbitrary_precision") && cfg!(feature = "std") {
assert!(v.is_f64());
} else {
assert!(v.is_null());
}

let v = to_value(::std::f64::INFINITY).unwrap();
assert!(v.is_null());

let v = to_value(::std::f32::NAN).unwrap();
assert!(v.is_null());
if !cfg!(feature = "arbitrary_precision") && cfg!(feature = "std") {
assert!(v.is_f64());
} else {
assert!(v.is_null());
}

let v = to_value(::std::f32::INFINITY).unwrap();
assert!(v.is_null());
Expand Down Expand Up @@ -693,6 +701,17 @@ fn test_parse_null() {
test_parse_ok(vec![("null", ())]);
}

#[test]
fn test_parse_nan() {
test_parse_err::<()>(&[
("n", "EOF while parsing a value at line 1 column 1"),
("na", "expected ident at line 1 column 2"),
("nana", "expected ident at line 1 column 2"),
]);

assert!(from_str::<f64>("nan").unwrap().is_nan());
}

#[test]
fn test_parse_bool() {
test_parse_err::<bool>(&[
Expand Down