messagepack_core/decode/
float.rs

1use super::{DecodeBorrowed, Error};
2use crate::{formats::Format, io::IoRead};
3
4macro_rules! impl_decode_float {
5    ($ty:ty,$format:path) => {
6        impl<'de> DecodeBorrowed<'de> for $ty {
7            type Value = Self;
8
9            fn decode_borrowed_with_format<R>(
10                format: Format,
11                reader: &mut R,
12            ) -> core::result::Result<Self::Value, Error<R::Error>>
13            where
14                R: IoRead<'de>,
15            {
16                match format {
17                    $format => {
18                        const SIZE: usize = core::mem::size_of::<$ty>();
19                        let bytes = reader.read_slice(SIZE).map_err(Error::Io)?;
20                        let slice = bytes.as_bytes();
21                        let data: [u8; SIZE] =
22                            slice.try_into().map_err(|_| Error::UnexpectedEof)?;
23                        let val = <$ty>::from_be_bytes(data);
24                        Ok(val)
25                    }
26                    _ => Err(Error::UnexpectedFormat),
27                }
28            }
29        }
30    };
31}
32
33impl_decode_float!(f32, Format::Float32);
34impl_decode_float!(f64, Format::Float64);
35
36#[cfg(test)]
37mod tests {
38    use crate::decode::Decode;
39
40    #[test]
41    fn decode_f32() {
42        let buf: &[u8] = &[0xca, 0x42, 0xf6, 0xe9, 0x79];
43        let mut r = crate::io::SliceReader::new(buf);
44        let decoded = f32::decode(&mut r).unwrap();
45        let expect = 123.456;
46        assert_eq!(decoded, expect);
47        assert_eq!(r.rest().len(), 0);
48    }
49
50    #[test]
51    fn decode_f64() {
52        let buf: &[u8] = &[0xcb, 0x40, 0xfe, 0x24, 0x0c, 0x9f, 0xcb, 0x0c, 0x02];
53        let mut r = crate::io::SliceReader::new(buf);
54        let decoded = f64::decode(&mut r).unwrap();
55        let expect = 123456.789012;
56        assert_eq!(decoded, expect);
57        assert_eq!(r.rest().len(), 0);
58    }
59}