Skip to content

Commit

Permalink
Implement prost::Message for google.protobuf.Timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
younes-io committed Oct 19, 2024
1 parent 7968f90 commit e25ab6d
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions prost-build/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ impl Config {
/// types, and instead generate Protobuf well-known types from their `.proto` definitions.
pub fn compile_well_known_types(&mut self) -> &mut Self {
self.prost_types = false;
self.extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp");
self
}

Expand Down
47 changes: 47 additions & 0 deletions prost-types/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,3 +427,50 @@ mod tests {
}
}
}

impl prost::Message for Timestamp {
fn encode_raw<B>(&self, buf: &mut B)
where
B: bytes::BufMut,
{
if self.seconds != 0 {
prost::encoding::int64::encode(1, &self.seconds, buf);
}
if self.nanos != 0 {
prost::encoding::int32::encode(2, &self.nanos, buf);
}
}

fn merge_field<B>(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut B,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError>
where
B: bytes::Buf,
{
match tag {
1 => prost::encoding::int64::merge(wire_type, &mut self.seconds, buf, ctx),
2 => prost::encoding::int32::merge(wire_type, &mut self.nanos, buf, ctx),
_ => prost::encoding::skip_field(wire_type, tag, buf, ctx),
}
}

fn encoded_len(&self) -> usize {
let mut len = 0;
if self.seconds != 0 {
len += prost::encoding::int64::encoded_len(1, &self.seconds);
}
if self.nanos != 0 {
len += prost::encoding::int32::encoded_len(2, &self.nanos);
}
len
}

fn clear(&mut self) {
self.seconds = 0;
self.nanos = 0;
}
}
18 changes: 18 additions & 0 deletions tests/src/well_known_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,21 @@ mod include {
"/wellknown_include/wellknown_include.rs"
));
}

#[test]
fn test_prost_message_for_timestamp() {
use prost::Message;

let timestamp = ::prost_types::Timestamp {
seconds: 100,
nanos: 42,
};

let mut buf = Vec::new();
timestamp.encode(&mut buf).expect("Failed to encode Timestamp");

let decoded_timestamp = ::prost_types::Timestamp::decode(&buf[..])
.expect("Failed to decode Timestamp");

assert_eq!(timestamp, decoded_timestamp, "Encoded and decoded Timestamp should be equal");
}

0 comments on commit e25ab6d

Please sign in to comment.