Created
February 20, 2023 16:17
-
-
Save ImTheSquid/b5f34c39c5c4a7760b3917c394b9ec07 to your computer and use it in GitHub Desktop.
Option<chrono::DateTime<Utc>> to Option<bson::DateTime> serialization and deserialization
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::Utc; | |
use serde::{Deserialize, Deserializer, Serialize, Serializer}; | |
use std::result::Result; | |
use serde::de::Error; | |
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<chrono::DateTime<Utc>>, D::Error> | |
where | |
D: Deserializer<'de>, | |
{ | |
match Bson::deserialize(deserializer)? { | |
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<chrono::DateTime<Utc>>, | |
serializer: S, | |
) -> Result<S::Ok, S::Error> { | |
match val { | |
None => None::<DateTime>.serialize(serializer), | |
Some(val) => { | |
let datetime = DateTime::from_chrono(val.to_owned()); | |
datetime.serialize(serializer) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment