1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::{errors::Result, types::BoltWireFormat, version::Version};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::mem;

pub const MARKER: u8 = 0xC1;

#[derive(Debug, PartialEq, Clone)]
pub struct BoltFloat {
    pub value: f64,
}

impl BoltFloat {
    pub fn new(value: f64) -> BoltFloat {
        BoltFloat { value }
    }
}

impl BoltWireFormat for BoltFloat {
    fn can_parse(_: Version, input: &[u8]) -> bool {
        input[0] == MARKER
    }

    fn parse(_: Version, input: &mut Bytes) -> Result<BoltFloat> {
        let _marker = input.get_u8();
        let value = input.get_f64();
        Ok(BoltFloat::new(value))
    }

    fn write_into(&self, _version: Version, bytes: &mut BytesMut) -> Result<()> {
        bytes.reserve(mem::size_of::<u8>() + mem::size_of::<f64>());
        bytes.put_u8(MARKER);
        bytes.put_f64(self.value);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_serialize_float() {
        let b: Bytes = BoltFloat::new(1.23).into_bytes(Version::V4_1).unwrap();
        assert_eq!(
            &b[..],
            &[0xC1, 0x3F, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE]
        );

        let b: Bytes = BoltFloat::new(-1.23).into_bytes(Version::V4_1).unwrap();
        assert_eq!(
            &b[..],
            &[0xC1, 0xBF, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE,]
        );
    }

    #[test]
    fn should_deserialize_float() {
        let mut input = Bytes::from_static(&[0xC1, 0x3F, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE]);
        let bolt_float: BoltFloat = BoltFloat::parse(Version::V4_1, &mut input).unwrap();
        assert_eq!(bolt_float.value, 1.23);

        let mut input = Bytes::from_static(&[0xC1, 0xBF, 0xF3, 0xAE, 0x14, 0x7A, 0xE1, 0x47, 0xAE]);
        let bolt_float: BoltFloat = BoltFloat::parse(Version::V4_1, &mut input).unwrap();
        assert_eq!(bolt_float.value, -1.23);
    }
}