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
pub use prost::{self, DecodeError, EncodeError, Message};
pub use prost_types::{Any, Timestamp};

use super::{Error, NamedMessage};

pub trait ProstTimestampExt {
    fn to_chrono_datetime(&self) -> chrono::DateTime<chrono::Utc>;

    fn to_timestamp_nanos(&self) -> u64 {
        self.to_chrono_datetime().timestamp_nanos() as u64
    }
}

impl ProstTimestampExt for Timestamp {
    fn to_chrono_datetime(&self) -> chrono::DateTime<chrono::Utc> {
        crate::time::timestamp_parts_to_datetime(self.seconds, self.nanos)
    }
}

pub trait ProstDateTimeExt {
    fn to_proto_timestamp(&self) -> Timestamp;
}

impl ProstDateTimeExt for chrono::DateTime<chrono::Utc> {
    fn to_proto_timestamp(&self) -> Timestamp {
        Timestamp {
            seconds: self.timestamp(),
            nanos: self.timestamp_subsec_nanos() as i32,
        }
    }
}

pub trait ProstMessageExt {
    fn encode_to_vec(&self) -> Vec<u8>;
}

impl<M> ProstMessageExt for M
where
    M: Message,
{
    fn encode_to_vec(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        self.encode(&mut buf).expect("Couldn't encode into Vec");
        buf
    }
}

pub trait ProstAnyPackMessageExt {
    fn pack_to_any(&self) -> Result<Any, Error>;

    fn pack_to_stepan_any(&self) -> Result<protobuf::well_known_types::Any, Error>;
}

impl<M> ProstAnyPackMessageExt for M
where
    M: Message + NamedMessage,
{
    fn pack_to_any(&self) -> Result<Any, Error> {
        let mut buf = Vec::new();
        self.encode(&mut buf)?;

        Ok(Any {
            type_url: format!("type.googleapis.com/{}", M::full_name()),
            value: buf,
        })
    }

    fn pack_to_stepan_any(&self) -> Result<protobuf::well_known_types::Any, Error> {
        let any = self.pack_to_any()?;

        Ok(protobuf::well_known_types::Any {
            type_url: any.type_url,
            value: any.value,
            ..Default::default()
        })
    }
}