Skip to content

Commit

Permalink
impl Default for &MyMessage
Browse files Browse the repository at this point in the history
Simply return MyMessage::default_instance()
  • Loading branch information
stepancheg committed Mar 5, 2019
1 parent f2e9b25 commit c026777
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
14 changes: 13 additions & 1 deletion protobuf-codegen/src/code_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,19 @@ impl<'a> CodeWriter<'a> {
where
F: Fn(&mut CodeWriter),
{
self.expr_block(&format!("impl {} for {}", tr.as_ref(), ty.as_ref()), cb);
self.impl_args_for_block(&[], tr.as_ref(), ty.as_ref(), cb);
}

pub fn impl_args_for_block<F>(&mut self, args: &[&str], tr: &str, ty: &str, cb: F)
where
F: Fn(&mut CodeWriter),
{
let args_str = if args.is_empty() {
"".to_owned()
} else {
format!("<{}>", args.join(", "))
};
self.expr_block(&format!("impl{} {} for {}", args_str, tr, ty), cb);
}

pub fn unsafe_impl(&mut self, what: &str, for_what: &str) {
Expand Down
11 changes: 11 additions & 0 deletions protobuf-codegen/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,14 @@ impl<'a> MessageGen<'a> {
});
}

fn write_impl_default_for_amp(&self, w: &mut CodeWriter) {
w.impl_args_for_block(&["'a"], "::std::default::Default", &format!("&'a {}", self.type_name), |w| {
w.def_fn(&format!("default() -> &'a {}", self.type_name), |w| {
w.write_line(&format!("<{} as ::protobuf::Message>::default_instance()", self.type_name));
});
});
}

fn write_dummy_impl_partial_eq(&self, w: &mut CodeWriter) {
w.impl_for_block("::std::cmp::PartialEq", &self.type_name, |w| {
w.def_fn("eq(&self, _: &Self) -> bool", |w| {
Expand All @@ -426,6 +434,9 @@ impl<'a> MessageGen<'a> {
pub fn write(&self, w: &mut CodeWriter) {
self.write_struct(w);

w.write_line("");
self.write_impl_default_for_amp(w);

if !self.supports_derive_partial_eq() {
w.write_line("");
self.write_dummy_impl_partial_eq(w);
Expand Down
7 changes: 7 additions & 0 deletions protobuf-test/src/common/v2/test_default.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use super::test_default_pb::*;

#[test]
fn test_default_for_amp_message() {
let none: Option<&TestDefault> = None;
assert_eq!(0, none.unwrap_or_default().get_i());
}
10 changes: 10 additions & 0 deletions protobuf-test/src/common/v2/test_default_pb.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
syntax = "proto2";

import "rustproto.proto";
option (rustproto.generate_accessors_all) = true;

package test_default;

message TestDefault {
optional int32 i = 1;
}

0 comments on commit c026777

Please sign in to comment.