rbdc_mysql/types/
year.rs

1use crate::types::{Decode, Encode};
2use crate::value::{MySqlValue, MySqlValueFormat};
3use byteorder::{ByteOrder, LittleEndian};
4use rbdc::Error;
5use std::fmt::{Debug, Display, Formatter};
6
7#[derive(serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq)]
8#[serde(rename = "Year")]
9pub struct Year(pub u16);
10
11impl Display for Year {
12    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
13        write!(f, "{}", self.0)
14    }
15}
16
17impl Debug for Year {
18    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
19        write!(f, "Year({})", self.0)
20    }
21}
22
23impl Encode for Year {
24    fn encode(self, buf: &mut Vec<u8>) -> Result<usize, Error> {
25        buf.push(2);
26        buf.extend_from_slice(&self.0.to_le_bytes());
27        Ok(2)
28    }
29}
30
31impl Decode for Year {
32    fn decode(value: MySqlValue) -> Result<Self, Error> {
33        Ok(Self({
34            match value.format() {
35                MySqlValueFormat::Text => value.as_str()?.parse().unwrap_or_default(),
36                MySqlValueFormat::Binary => {
37                    let buf = value.as_bytes()?;
38                    LittleEndian::read_u16(&buf[1..])
39                }
40            }
41        }))
42    }
43}