mysql_connector/connection/
serialization.rs

1use {super::ParseBuf, crate::error::ProtocolError};
2
3pub(crate) trait Serialize {
4    fn serialize(&self, buf: &mut Vec<u8>);
5}
6
7pub(crate) trait Deserialize<'de>: Sized {
8    /// Size of a serialized value (in bytes), if it's constant
9    const SIZE: Option<usize>;
10    type Ctx;
11
12    fn deserialize(buf: &mut ParseBuf<'de>, ctx: Self::Ctx) -> Result<Self, ProtocolError>;
13}
14
15macro_rules! num_serialization {
16    ($($t:ty),* $(,)?) => {
17        $(
18            const _: () = {
19                const MY_SIZE: usize = std::mem::size_of::<$t>();
20
21                impl Serialize for $t {
22                    fn serialize(&self, buf: &mut Vec<u8>) {
23                        buf.extend_from_slice(&self.to_le_bytes())
24                    }
25                }
26
27                impl<'de> Deserialize<'de> for $t {
28                    const SIZE: Option<usize> = Some(MY_SIZE);
29                    type Ctx = ();
30
31                    fn deserialize(buf: &mut ParseBuf<'de>, _ctx: Self::Ctx) -> Result<Self, ProtocolError> {
32                        let bytes = buf.eat(MY_SIZE);
33                        Ok(unsafe { <$t>::from_le_bytes(*(bytes as *const _ as *const [_; MY_SIZE])) })
34                    }
35                }
36            };
37        )*
38    };
39}
40
41num_serialization!(u8, u16, u32, u64, u128);
42num_serialization!(i8, i16, i32, i64, i128);
43num_serialization!(f32, f64);
44
45impl<'de, const N: usize> Deserialize<'de> for [u8; N] {
46    const SIZE: Option<usize> = Some(N);
47    type Ctx = ();
48
49    fn deserialize(buf: &mut ParseBuf<'de>, _ctx: Self::Ctx) -> Result<Self, ProtocolError> {
50        Ok(unsafe { *(buf.eat(N) as *const _ as *const [u8; N]) })
51    }
52}