Skip to content

Commit c026777

Browse files
committed
impl Default for &MyMessage
Simply return MyMessage::default_instance()
1 parent f2e9b25 commit c026777

4 files changed

Lines changed: 41 additions & 1 deletion

File tree

protobuf-codegen/src/code_writer.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,19 @@ impl<'a> CodeWriter<'a> {
163163
where
164164
F: Fn(&mut CodeWriter),
165165
{
166-
self.expr_block(&format!("impl {} for {}", tr.as_ref(), ty.as_ref()), cb);
166+
self.impl_args_for_block(&[], tr.as_ref(), ty.as_ref(), cb);
167+
}
168+
169+
pub fn impl_args_for_block<F>(&mut self, args: &[&str], tr: &str, ty: &str, cb: F)
170+
where
171+
F: Fn(&mut CodeWriter),
172+
{
173+
let args_str = if args.is_empty() {
174+
"".to_owned()
175+
} else {
176+
format!("<{}>", args.join(", "))
177+
};
178+
self.expr_block(&format!("impl{} {} for {}", args_str, tr, ty), cb);
167179
}
168180

169181
pub fn unsafe_impl(&mut self, what: &str, for_what: &str) {

protobuf-codegen/src/message.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,14 @@ impl<'a> MessageGen<'a> {
414414
});
415415
}
416416

417+
fn write_impl_default_for_amp(&self, w: &mut CodeWriter) {
418+
w.impl_args_for_block(&["'a"], "::std::default::Default", &format!("&'a {}", self.type_name), |w| {
419+
w.def_fn(&format!("default() -> &'a {}", self.type_name), |w| {
420+
w.write_line(&format!("<{} as ::protobuf::Message>::default_instance()", self.type_name));
421+
});
422+
});
423+
}
424+
417425
fn write_dummy_impl_partial_eq(&self, w: &mut CodeWriter) {
418426
w.impl_for_block("::std::cmp::PartialEq", &self.type_name, |w| {
419427
w.def_fn("eq(&self, _: &Self) -> bool", |w| {
@@ -426,6 +434,9 @@ impl<'a> MessageGen<'a> {
426434
pub fn write(&self, w: &mut CodeWriter) {
427435
self.write_struct(w);
428436

437+
w.write_line("");
438+
self.write_impl_default_for_amp(w);
439+
429440
if !self.supports_derive_partial_eq() {
430441
w.write_line("");
431442
self.write_dummy_impl_partial_eq(w);
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
use super::test_default_pb::*;
2+
3+
#[test]
4+
fn test_default_for_amp_message() {
5+
let none: Option<&TestDefault> = None;
6+
assert_eq!(0, none.unwrap_or_default().get_i());
7+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
syntax = "proto2";
2+
3+
import "rustproto.proto";
4+
option (rustproto.generate_accessors_all) = true;
5+
6+
package test_default;
7+
8+
message TestDefault {
9+
optional int32 i = 1;
10+
}

0 commit comments

Comments
 (0)