Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement prost::Message for google.protobuf.Timestamp #1172

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
}
Loading