1use crate::types::{Decode, Encode};
2use crate::value::{MySqlValue, MySqlValueFormat};
3use byteorder::{ByteOrder, LittleEndian};
4use rbdc::date::Date;
5use rbdc::Error;
6use std::str::FromStr;
7
8impl Encode for Date {
9 fn encode(self, buf: &mut Vec<u8>) -> Result<usize, Error> {
10 buf.push(4);
11 let year = &(self.0.year as u16).to_le_bytes();
13 buf.extend_from_slice(year);
14 buf.push(self.0.mon as u8);
15 buf.push(self.0.day as u8);
16 Ok(4)
17 }
18}
19
20impl Decode for Date {
21 fn decode(value: MySqlValue) -> Result<Self, Error> {
22 Ok(Date(match value.format() {
23 MySqlValueFormat::Text => {
24 fastdate::Date::from_str(value.as_str()?).map_err(|e| Error::from(e.to_string()))?
25 }
26 MySqlValueFormat::Binary => {
27 let buf = value.as_bytes()?;
28 decode_date_buf(&buf[1..])?
30 }
31 }))
32 }
33}
34
35pub fn decode_date_buf(buf: &[u8]) -> Result<fastdate::Date, Error> {
36 if buf.is_empty() {
37 return Ok(fastdate::Date {
39 day: 0,
40 mon: 0,
41 year: 0,
42 });
43 }
44 Ok(fastdate::Date {
45 day: buf[3],
46 mon: buf[2],
47 year: LittleEndian::read_u16(buf) as i32,
48 })
49}