diff --git a/src/de.rs b/src/de.rs index aa76fd0..f9f27e6 100644 --- a/src/de.rs +++ b/src/de.rs @@ -61,6 +61,12 @@ impl Deserialize for bool { } } +impl Deserialize for f16 { + fn deserialize(raw: &mut Deserializer) -> Result { + raw.float().map(|f| f as f16) + } +} + impl Deserialize for f32 { fn deserialize(raw: &mut Deserializer) -> Result { raw.float().map(|f| f as f32) @@ -772,9 +778,9 @@ impl Deserializer { Ok(Special::Unassigned(b as u8)) } 0x19 => { - let f = self.u16(1)?; + let f = self.u16(1)? as u16; self.advance(3)?; - Ok(Special::Float(f as f64)) + Ok(Special::Float(f16::from_bits(f) as f64)) } 0x1a => { let f = self.u32(1)? as u32; @@ -974,6 +980,16 @@ mod test { assert_eq!(float, 100000.0); } + #[test] + fn float16() { + let vec = vec![0xf9, 0x3c, 0x00]; + let mut raw = Deserializer::from(vec); + + let float = raw.float().unwrap(); + + assert_eq!(float, 1.0); + } + #[test] fn array() { let vec = vec![0x86, 0, 1, 2, 3, 4, 5]; diff --git a/src/lib.rs b/src/lib.rs index 641b2bd..72b29a4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,7 @@ //! ``` #![no_std] +#![feature(f16)] #[cfg(test)] #[macro_use] extern crate quickcheck; diff --git a/src/se.rs b/src/se.rs index 166b2a5..e5d7f97 100644 --- a/src/se.rs +++ b/src/se.rs @@ -41,6 +41,11 @@ impl Serialize for bool { serializer.write_special(Special::Bool(*self)) } } +impl Serialize for f16 { + fn serialize<'a>(&self, serializer: &'a mut Serializer) -> Result<&'a mut Serializer> { + serializer.write_special(Special::Float((*self) as f64)) + } +} impl Serialize for f32 { fn serialize<'a>(&self, serializer: &'a mut Serializer) -> Result<&'a mut Serializer> { serializer.write_special(Special::Float((*self) as f64)) @@ -302,6 +307,18 @@ impl Serializer { Ok(self) } + #[inline] + fn write_f16(&mut self, value: f16) -> Result<&mut Self> { + self.data.extend_from_slice(&value.to_be_bytes()); + Ok(self) + } + + #[inline] + fn write_f32(&mut self, value: f32) -> Result<&mut Self> { + self.data.extend_from_slice(&value.to_be_bytes()); + Ok(self) + } + #[inline] fn write_f64(&mut self, value: f64) -> Result<&mut Self> { self.data.extend_from_slice(&value.to_be_bytes());