[gcc r14-7596] gccrs: Improve Optional<T&> implementation

Arthur Cohen cohenarthur@gcc.gnu.org
Tue Jan 16 17:43:46 GMT 2024


https://gcc.gnu.org/g:122f519ceb12a142983dd381d3a42058a11fce22

commit r14-7596-g122f519ceb12a142983dd381d3a42058a11fce22
Author: Owen Avery <powerboat9.gamer@gmail.com>
Date:   Fri May 12 03:05:03 2023 -0400

    gccrs: Improve Optional<T&> implementation
    
    gcc/rust/ChangeLog:
    
            * util/rust-optional.h
            (class Optional<T&>): Use pointers internally.
    
    Signed-off-by: Owen Avery <powerboat9.gamer@gmail.com>

Diff:
---
 gcc/rust/util/rust-optional.h | 59 +++++++------------------------------------
 1 file changed, 9 insertions(+), 50 deletions(-)

diff --git a/gcc/rust/util/rust-optional.h b/gcc/rust/util/rust-optional.h
index 25662568eb4..3b3f110b773 100644
--- a/gcc/rust/util/rust-optional.h
+++ b/gcc/rust/util/rust-optional.h
@@ -171,48 +171,16 @@ public:
 template <typename T> class Optional<T &>
 {
 private:
-  struct Empty
-  {
-  };
+  T *inner;
 
-  enum Kind
-  {
-    Some,
-    None
-  } kind;
-
-  union Content
-  {
-    Empty empty;
-    T *value;
-
-    Content () = default;
-  } content;
-
-  Optional<T &> (Kind kind, Content content) : kind (kind), content (content) {}
+  Optional (T *inner) : inner (inner) {}
 
 public:
-  Optional (const Optional &other) = default;
-  Optional (Optional &&other) = default;
-  Optional &operator= (Optional &&other) = default;
-
-  static Optional<T &> some (T &value)
-  {
-    Content content;
-    content.value = &value;
+  static Optional<T &> some (T &value) { return Optional (&value); }
 
-    return Optional (Kind::Some, content);
-  }
-
-  static Optional<T &> none ()
-  {
-    Content content;
-    content.empty = Empty ();
+  static Optional<T &> none () { return Optional (nullptr); }
 
-    return Optional (Kind::None, content);
-  }
-
-  bool is_some () const { return kind == Kind::Some; }
+  bool is_some () const { return inner; }
   bool is_none () const { return !is_some (); }
 
   // FIXME: Can we factor this in a single class?
@@ -230,28 +198,19 @@ public:
   T *operator-> () { return &get (); }
   const T *operator-> () const { return &get (); }
 
-  const T &get () const
+  T &get () const
   {
     rust_assert (is_some ());
 
-    return *content.value;
-  }
-
-  T &get ()
-  {
-    rust_assert (is_some ());
-
-    return *content.value;
+    return *inner;
   }
 
   T &take ()
   {
     rust_assert (is_some ());
 
-    auto to_return = std::move (content.value);
-
-    content.empty = Empty ();
-    kind = Kind::None;
+    T *to_return = inner;
+    inner = nullptr;
 
     return *to_return;
   }


More information about the Gcc-cvs mailing list