From 626812ff966a58fc5f233bbe5d4cdacc32a8db4f Mon Sep 17 00:00:00 2001 From: Owen Avery Date: Tue, 16 Sep 2025 19:31:39 -0400 Subject: gccrs: Improve FFIOpt Also fixes https://github.com/Rust-GCC/gccrs/issues/4171. gcc/rust/ChangeLog: * ast/rust-fmt.h (class FFIOpt): Adjust internal structure to match a repr(C) rust enum. libgrust/ChangeLog: * libformat_parser/src/lib.rs (struct FFIOpt): Likewise and remove some now-redundant methods. Signed-off-by: Owen Avery --- libgrust/libformat_parser/src/lib.rs | 84 ++++-------------------------------- 1 file changed, 8 insertions(+), 76 deletions(-) (limited to 'libgrust/libformat_parser') diff --git a/libgrust/libformat_parser/src/lib.rs b/libgrust/libformat_parser/src/lib.rs index 049403db0b7..efb5d00f678 100644 --- a/libgrust/libformat_parser/src/lib.rs +++ b/libgrust/libformat_parser/src/lib.rs @@ -83,87 +83,19 @@ pub mod ffi { } } - #[repr(C)] - pub struct FFIOpt { - val: MaybeUninit, - is_some: bool - } - - impl Clone for FFIOpt - where - T: Clone - { - fn clone(&self) -> Self { - match self.get_opt_ref() { - Some(r) => FFIOpt::new_val(r.clone()), - None => FFIOpt::new_none() - } - } - } - - impl PartialEq for FFIOpt - where - T: PartialEq - { - fn eq(&self, other: &Self) -> bool { - match (self.get_opt_ref(), other.get_opt_ref()) { - (Some(a), Some(b)) => a.eq(b), - _ => false - } - } - } - - impl Eq for FFIOpt - where - T: Eq - {} - - impl Drop for FFIOpt - { - fn drop(&mut self) { - if self.is_some { - unsafe { std::ptr::drop_in_place(self.val.as_mut_ptr()) } - } - } + // https://github.com/rust-lang/rfcs/blob/master/text/2195-really-tagged-unions.md + #[repr(u8)] + #[derive(Copy, Clone, PartialEq, Eq)] + pub enum FFIOpt { + Some(T), + None } impl IntoFFI> for Option { fn into_ffi(self) -> FFIOpt { match self { - Some(v) => FFIOpt::new_val(v), - None => FFIOpt::new_none() - } - } - } - - impl FFIOpt { - pub fn new_val(v: T) -> Self { - FFIOpt { - val: MaybeUninit::new(v), - is_some: true - } - } - - pub fn new_none() -> Self { - FFIOpt { - val: MaybeUninit::uninit(), - is_some: false - } - } - - pub fn get_opt_ref(&self) -> Option<&T> { - if self.is_some { - Some(unsafe {&*self.val.as_ptr()}) - } else { - None - } - } - - pub fn get_opt_ref_mut(&mut self) -> Option<&mut T> { - if self.is_some { - Some(unsafe {&mut *self.val.as_mut_ptr()}) - } else { - None + Some(v) => FFIOpt::Some(v), + None => FFIOpt::None } } } -- cgit v1.2.3