Bindgen Debug impl for tag unions

This commit is contained in:
Richard Feldman 2022-05-11 10:46:45 -04:00
parent a74c7c3009
commit 749e4b25c7
No known key found for this signature in database
GPG Key ID: 7E4127D1E4241798
2 changed files with 62 additions and 0 deletions

View File

@ -503,6 +503,53 @@ fn write_tag_union(
writeln!(buf, "impl Copy for {} {{}}\n", name)?;
}
// The Debug impl for the tag union
{
write!(
buf,
indoc!(
r#"
impl core::fmt::Debug for {} {{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {{
f.write_str("{}::")?;
unsafe {{
match self.tag {{
"#
),
name, name
)?;
write_impl_tags(
4,
tags.iter(),
&discriminant_name,
buf,
|tag_name, opt_payload_id| {
if opt_payload_id.is_some() {
format!(
r#"f.debug_tuple("{}").field(&self.variant.{}).finish(),"#,
tag_name, tag_name
)
} else {
format!(r#"f.write_str("{}"),"#, tag_name)
}
},
)?;
writeln!(
buf,
indoc!(
r#"
}}
}}
}}
}}
"#
),
)?;
}
Ok(())
}

View File

@ -348,6 +348,21 @@ fn tag_union_aliased() {
}
}
impl core::fmt::Debug for MyTagUnion {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("MyTagUnion::")?;
unsafe {
match self.tag {
tag_MyTagUnion::Bar => f.debug_tuple("Bar").field(&self.variant.Bar).finish(),
tag_MyTagUnion::Baz => f.write_str("Baz"),
tag_MyTagUnion::Blah => f.debug_tuple("Blah").field(&self.variant.Blah).finish(),
tag_MyTagUnion::Foo => f.debug_tuple("Foo").field(&self.variant.Foo).finish(),
}
}
}
}
"#
)
);