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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use std::any::{Any, type_name};
use std::fmt::Debug;
use std::ops::{Add, Deref, DerefMut};
use std::str::FromStr;
use std::time::SystemTime;
use rbson::{Bson, DateTime};
use rbson::spec::BinarySubtype;
use chrono::{Local, NaiveDateTime, Utc};
use serde::{Deserializer, Serializer};
use serde::de::Error;

/// Rbatis DateTime
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DateTimeNative {
    pub inner: chrono::NaiveDateTime,
}

impl From<rbson::DateTime> for DateTimeNative {
    fn from(arg: DateTime) -> Self {
        Self {
            inner: arg.to_chrono().with_timezone(&chrono::Local).naive_local(),
        }
    }
}

impl From<chrono::DateTime<Local>> for DateTimeNative {
    fn from(arg: chrono::DateTime<Local>) -> Self {
        DateTimeNative {
            inner: arg.naive_local()
        }
    }
}

impl From<&chrono::DateTime<Local>> for DateTimeNative {
    fn from(arg: &chrono::DateTime<Local>) -> Self {
        DateTimeNative {
            inner: arg.clone().naive_local()
        }
    }
}

impl serde::Serialize for DateTimeNative {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        struct FormatWrapped<'a, D: 'a> {
            inner: &'a D,
        }
        impl<'a, D: std::fmt::Debug> std::fmt::Display for FormatWrapped<'a, D> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                self.inner.fmt(f)
            }
        }
        use serde::ser::Error;
        if type_name::<S::Error>().eq("rbson::ser::error::Error") {
            return serializer.serialize_str(&format!("DateTimeNative({})", FormatWrapped { inner: &self }.to_string()));
        } else {
            return self.inner.serialize(serializer);
        }
    }
}

impl<'de> serde::Deserialize<'de> for DateTimeNative {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        match Bson::deserialize(deserializer)? {
            Bson::DateTime(date) => {
                return Ok(Self {
                    inner: date.to_chrono().with_timezone(&chrono::Local).naive_local(),
                });
            }
            Bson::String(s) => {
                if s.starts_with("DateTimeNative(") && s.ends_with(")") {
                    let inner_data = &s["DateTimeNative(".len()..(s.len() - 1)];
                    return Ok(Self {
                        inner: chrono::NaiveDateTime::from_str(inner_data).or_else(|e| Err(D::Error::custom(e.to_string())))?,
                    });
                } else {
                    return Ok(Self {
                        inner: chrono::NaiveDateTime::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 DateTimeNative {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        struct FormatWrapped<'a, D: 'a> {
            inner: &'a D,
        }
        impl<'a, D: std::fmt::Debug> std::fmt::Display for FormatWrapped<'a, D> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                self.inner.fmt(f)
            }
        }
        FormatWrapped { inner: &self.inner }.fmt(f)
    }
}

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

impl Deref for DateTimeNative {
    type Target = chrono::NaiveDateTime;

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

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


impl DateTimeNative {
    /// Returns a [`DateTime`] which corresponds to the current date and time.
    pub fn now() -> DateTimeNative {
        let dt = rbson::DateTime::now();
        Self {
            inner: dt.to_chrono().naive_local()
        }
    }

    /// create from str
    pub fn from_str(arg: &str) -> Result<Self, crate::error::Error> {
        let inner = chrono::NaiveDateTime::from_str(arg)?;
        Ok(Self {
            inner: inner
        })
    }
}

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

    #[test]
    fn test_native() {
        let dt = DateTimeNative::now();
        let s = rbson::to_bson(&dt).unwrap();
        let dt_new: DateTimeNative = rbson::from_bson(s).unwrap();
        println!("{},{}", dt.timestamp_millis(), dt_new.timestamp_millis());
        assert_eq!(dt, dt_new);
    }

    #[test]
    fn test_utc() {
        let dt = DateTimeNative::now();
        println!("{}", dt);
        let s = rbson::to_bson(&dt).unwrap();
        let dt_new: DateTimeNative = rbson::from_bson(s).unwrap();
        println!("{},{}", dt.timestamp_millis(), dt_new.timestamp_millis());
        assert_eq!(dt, dt_new);
    }

    #[test]
    fn test_decode() {
        let s = rbson::Bson::String("2015-09-18T23:56:04".to_string());
        let dt_new: DateTimeNative = rbson::from_bson(s).unwrap();
        println!("{},{}", 1442620564000i64, dt_new.timestamp_millis());
        assert_eq!(1442620564000i64, dt_new.timestamp_millis());
    }

    #[test]
    fn test_ser_de() {
        let b = DateTimeNative::now();
        let bsons = rbson::to_bson(&b).unwrap();
        println!("{:?}", bsons);
        let js = serde_json::to_value(&b).unwrap();
        println!("{:?}", js);
    }
}