Created
November 27, 2024 03:16
-
-
Save ashaffah/7864a844fecea775e6ac36f799c0a8f0 to your computer and use it in GitHub Desktop.
chrono_datetime_option_as_bson_datetime_option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub mod chrono_datetime_option_as_bson_datetime_option { | |
use bson::{ Bson, DateTime }; | |
use chrono::{ DateTime as ChronoDateTime, Utc }; | |
use serde::{ Deserialize, Deserializer, Serialize, Serializer }; | |
use std::result::Result; | |
use serde::de::Error; | |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<ChronoDateTime<Utc>>, D::Error> | |
where D: Deserializer<'de> | |
{ | |
let bson = Bson::deserialize(deserializer)?; | |
match bson { | |
Bson::Null => Ok(None), | |
Bson::DateTime(dt) => Ok(Some(dt.to_chrono())), | |
_ => Err(D::Error::custom("expecting DateTime or Option<DateTime>")), | |
} | |
} | |
pub fn serialize<S: Serializer>( | |
val: &Option<ChronoDateTime<Utc>>, | |
serializer: S | |
) -> Result<S::Ok, S::Error> { | |
match val { | |
None => serializer.serialize_none(), | |
Some(val) => { | |
let datetime = DateTime::from_chrono(*val); | |
datetime.serialize(serializer) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Available on crate feature chrono-0_4 only.