From 69b4571c6bafcd7d9f675d3eb49d4c088d372eea Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Tue, 10 Jul 2018 16:27:58 -0700 Subject: 0.5: Support floats nan, inf, and +/-0.0. cc #224 --- src/ser.rs | 49 +++++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 26 deletions(-) (limited to 'src/ser.rs') diff --git a/src/ser.rs b/src/ser.rs index 8f4e72b..9d989db 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -737,6 +737,27 @@ impl<'a> Serializer<'a> { } } +macro_rules! serialize_float { + ($this:expr, $v:expr) => {{ + $this.emit_key("float")?; + if ($v.is_nan() || $v == 0.0) && $v.is_sign_negative() { + drop(write!($this.dst, "-")); + } + if $v.is_nan() { + drop(write!($this.dst, "nan")); + } else { + drop(write!($this.dst, "{}", $v)); + } + if $v % 1.0 == 0.0 { + drop(write!($this.dst, ".0")); + } + if let State::Table { .. } = $this.state { + $this.dst.push_str("\n"); + } + return Ok(()); + }}; +} + impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { type Ok = (); type Error = Error; @@ -785,35 +806,11 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { } fn serialize_f32(self, v: f32) -> Result<(), Self::Error> { - if !v.is_finite() { - return Err(Error::NumberInvalid); - } - - self.emit_key("float")?; - drop(write!(self.dst, "{}", v)); - if v % 1.0 == 0.0 { - drop(write!(self.dst, ".0")); - } - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) + serialize_float!(self, v) } fn serialize_f64(self, v: f64) -> Result<(), Self::Error> { - if !v.is_finite() { - return Err(Error::NumberInvalid); - } - - self.emit_key("float")?; - drop(write!(self.dst, "{}", v)); - if v % 1.0 == 0.0 { - drop(write!(self.dst, ".0")); - } - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) + serialize_float!(self, v) } fn serialize_char(self, v: char) -> Result<(), Self::Error> { -- cgit v1.2.3