exocore_protos/
stepan.rs

1use chrono::{DateTime, Utc};
2use protobuf::{
3    well_known_types::{any::Any, timestamp::Timestamp},
4    MessageFull,
5};
6
7use super::Error;
8
9pub trait StepanTimestampExt {
10    fn to_chrono_datetime(&self) -> chrono::DateTime<chrono::Utc>;
11}
12
13impl StepanTimestampExt for Timestamp {
14    fn to_chrono_datetime(&self) -> DateTime<Utc> {
15        crate::time::timestamp_parts_to_datetime(self.seconds, self.nanos)
16    }
17}
18
19pub trait StepanDateTimeExt {
20    fn to_proto_timestamp(&self) -> Timestamp;
21}
22
23impl StepanDateTimeExt for chrono::DateTime<Utc> {
24    fn to_proto_timestamp(&self) -> Timestamp {
25        Timestamp {
26            seconds: self.timestamp(),
27            nanos: self.timestamp_subsec_nanos() as i32,
28            ..Default::default()
29        }
30    }
31}
32
33pub trait StepanMessageExt {
34    fn pack_to_any(&self) -> Result<Any, Error>;
35}
36
37impl<M> StepanMessageExt for M
38where
39    M: MessageFull,
40{
41    fn pack_to_any(&self) -> Result<Any, Error> {
42        let mut any = Any::new();
43        any.type_url = format!("type.googleapis.com/{}", M::descriptor().name(),);
44        any.value = self.write_to_bytes()?;
45        Ok(any)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn timestamp_conversion() {
55        let now = Utc::now();
56
57        let ts = now.to_proto_timestamp();
58        let dt = ts.to_chrono_datetime();
59
60        assert_eq!(dt, now);
61    }
62}