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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::ops::{Add, Deref, DerefMut};
use std::str::FromStr;
use std::time::SystemTime;
use bson::Bson;
use bson::spec::BinarySubtype;
use chrono::{Local, Utc};
use serde::{Deserializer, Serializer};
use serde::de::Error;
use crate::types::BINARY_SUBTYPE_TIME_LOCAL;

/// TimeLocal
/// Rust type              Postgres type(s)
/// chrono::NaiveTime      TIME
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TimeNative {
    pub inner: chrono::NaiveTime,
}

impl serde::Serialize for TimeNative {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        let utc = self.inner.to_string();
        return bson::Binary {
            subtype: BinarySubtype::UserDefined(BINARY_SUBTYPE_TIME_LOCAL),
            bytes: utc.into_bytes(),
        }.serialize(serializer);
    }
}

impl<'de> serde::Deserialize<'de> for TimeNative {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        match Bson::deserialize(deserializer)? {
            Bson::String(s) => {
                return Ok(Self {
                    inner: chrono::NaiveTime::from_str(&s).or_else(|e| Err(D::Error::custom(e.to_string())))?,
                });
            }
            Bson::Binary(data) => {
                let s = String::from_utf8(data.bytes).unwrap_or_default();
                return Ok(Self {
                    inner: chrono::NaiveTime::from_str(&s).or_else(|e|Err(D::Error::custom(e.to_string())))?,
                });
            }
            _ => {
                Err(D::Error::custom("deserialize un supported bson type!"))
            }}
    }
}

impl std::fmt::Display for TimeNative {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl std::fmt::Debug for TimeNative {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl Deref for TimeNative {
    type Target = chrono::NaiveTime;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for TimeNative {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl TimeNative {
    /// Returns a [`DateTime`] which corresponds to the current date and time.
    pub fn now() -> TimeNative {
        let utc = Local::now();
        let dt = bson::DateTime::from_millis(utc.timestamp_millis());
        Self {
            inner: dt.to_chrono().with_timezone(&Local).time()
        }
    }
}

#[cfg(test)]
mod test {
    use crate::types::TimeNative;

    #[test]
    fn test_ser_de(){
        let b=TimeNative::now();
        let bsons=bson::to_bson(&b).unwrap();
        let b_de:TimeNative = bson::from_bson(bsons).unwrap();
        assert_eq!(b,b_de);
    }
}