Skip to content

Commit e25ab6d

Browse files
committed
Implement prost::Message for google.protobuf.Timestamp
Fixes tokio-rs#1171
1 parent 7968f90 commit e25ab6d

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

prost-build/src/config.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@ impl Config {
382382
/// types, and instead generate Protobuf well-known types from their `.proto` definitions.
383383
pub fn compile_well_known_types(&mut self) -> &mut Self {
384384
self.prost_types = false;
385+
self.extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp");
385386
self
386387
}
387388

prost-types/src/timestamp.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,3 +427,50 @@ mod tests {
427427
}
428428
}
429429
}
430+
431+
impl prost::Message for Timestamp {
432+
fn encode_raw<B>(&self, buf: &mut B)
433+
where
434+
B: bytes::BufMut,
435+
{
436+
if self.seconds != 0 {
437+
prost::encoding::int64::encode(1, &self.seconds, buf);
438+
}
439+
if self.nanos != 0 {
440+
prost::encoding::int32::encode(2, &self.nanos, buf);
441+
}
442+
}
443+
444+
fn merge_field<B>(
445+
&mut self,
446+
tag: u32,
447+
wire_type: prost::encoding::WireType,
448+
buf: &mut B,
449+
ctx: prost::encoding::DecodeContext,
450+
) -> Result<(), prost::DecodeError>
451+
where
452+
B: bytes::Buf,
453+
{
454+
match tag {
455+
1 => prost::encoding::int64::merge(wire_type, &mut self.seconds, buf, ctx),
456+
2 => prost::encoding::int32::merge(wire_type, &mut self.nanos, buf, ctx),
457+
_ => prost::encoding::skip_field(wire_type, tag, buf, ctx),
458+
}
459+
}
460+
461+
fn encoded_len(&self) -> usize {
462+
let mut len = 0;
463+
if self.seconds != 0 {
464+
len += prost::encoding::int64::encoded_len(1, &self.seconds);
465+
}
466+
if self.nanos != 0 {
467+
len += prost::encoding::int32::encoded_len(2, &self.nanos);
468+
}
469+
len
470+
}
471+
472+
fn clear(&mut self) {
473+
self.seconds = 0;
474+
self.nanos = 0;
475+
}
476+
}

tests/src/well_known_types.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,21 @@ mod include {
6969
"/wellknown_include/wellknown_include.rs"
7070
));
7171
}
72+
73+
#[test]
74+
fn test_prost_message_for_timestamp() {
75+
use prost::Message;
76+
77+
let timestamp = ::prost_types::Timestamp {
78+
seconds: 100,
79+
nanos: 42,
80+
};
81+
82+
let mut buf = Vec::new();
83+
timestamp.encode(&mut buf).expect("Failed to encode Timestamp");
84+
85+
let decoded_timestamp = ::prost_types::Timestamp::decode(&buf[..])
86+
.expect("Failed to decode Timestamp");
87+
88+
assert_eq!(timestamp, decoded_timestamp, "Encoded and decoded Timestamp should be equal");
89+
}

0 commit comments

Comments
 (0)