Implement operator!= using a distinct symbol from operator==

This commit is contained in:
David Tolnay 2020-11-27 16:47:30 -08:00
parent ec9b4ba0a6
commit a6f3b6f4ec
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 33 additions and 5 deletions

View File

@ -360,6 +360,15 @@ fn write_struct_operator_decls<'a>(out: &mut OutFile<'a>, strct: &'a Struct) {
"bool {}(const {1} &, const {1} &) noexcept;",
link_name, strct.name.cxx,
);
if !derive::contains(&strct.derives, Trait::Eq) {
let link_name = mangle::operator(&strct.name, "__operator_ne");
writeln!(
out,
"bool {}(const {1} &, const {1} &) noexcept;",
link_name, strct.name.cxx,
);
}
}
out.end_block(Block::ExternC);
@ -373,22 +382,28 @@ fn write_struct_operators<'a>(out: &mut OutFile<'a>, strct: &'a Struct) {
out.set_namespace(&strct.name.namespace);
if derive::contains(&strct.derives, Trait::PartialEq) {
let link_name = mangle::operator(&strct.name, "__operator_eq");
out.next_section();
writeln!(
out,
"bool {0}::operator==(const {0} &rhs) const noexcept {{",
strct.name.cxx,
);
let link_name = mangle::operator(&strct.name, "__operator_eq");
writeln!(out, " return {}(*this, rhs);", link_name);
writeln!(out, "}}");
out.next_section();
writeln!(
out,
"bool {0}::operator!=(const {0} &rhs) const noexcept {{",
strct.name.cxx,
);
writeln!(out, " return !(*this == rhs);");
if derive::contains(&strct.derives, Trait::Eq) {
writeln!(out, " return !(*this == rhs);");
} else {
let link_name = mangle::operator(&strct.name, "__operator_ne");
writeln!(out, " return {}(*this, rhs);", link_name);
}
writeln!(out, "}}");
}
}

View File

@ -164,17 +164,29 @@ fn expand_struct_operators(strct: &Struct) -> TokenStream {
for derive in &strct.derives {
let span = derive.span;
match derive.what {
Trait::PartialEq => operators.extend({
Trait::PartialEq => {
let link_name = mangle::operator(&strct.name, "__operator_eq");
let local_name = format_ident!("__operator_eq_{}", strct.name.rust);
quote_spanned! {span=>
operators.extend(quote_spanned! {span=>
#[doc(hidden)]
#[export_name = #link_name]
extern "C" fn #local_name(lhs: &#ident, rhs: &#ident) -> bool {
*lhs == *rhs
}
});
if !derive::contains(&strct.derives, Trait::Eq) {
let link_name = mangle::operator(&strct.name, "__operator_ne");
let local_name = format_ident!("__operator_ne_{}", strct.name.rust);
operators.extend(quote_spanned! {span=>
#[doc(hidden)]
#[export_name = #link_name]
extern "C" fn #local_name(lhs: &#ident, rhs: &#ident) -> bool {
*lhs != *rhs
}
});
}
}),
}
_ => {}
}
}

View File

@ -20,6 +20,7 @@ pub mod ffi {
z: usize,
}
#[derive(PartialEq)]
struct SharedString {
msg: String,
}