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