[libc-commits] [libc] 42e2946 - [libc][NFC] add arrow operator to optional

Michael Jones via libc-commits libc-commits at lists.llvm.org
Wed Aug 10 14:47:09 PDT 2022


Author: Michael Jones
Date: 2022-08-10T14:47:04-07:00
New Revision: 42e2946f51e33b64906a73f6fccbebad2e2fd44f

URL: https://github.com/llvm/llvm-project/commit/42e2946f51e33b64906a73f6fccbebad2e2fd44f
DIFF: https://github.com/llvm/llvm-project/commit/42e2946f51e33b64906a73f6fccbebad2e2fd44f.diff

LOG: [libc][NFC] add arrow operator to optional

Reviewed By: sivachandra

Differential Revision: https://reviews.llvm.org/D131610

Added: 
    

Modified: 
    libc/src/__support/CPP/optional.h
    libc/test/src/__support/CPP/optional_test.cpp

Removed: 
    


################################################################################
diff  --git a/libc/src/__support/CPP/optional.h b/libc/src/__support/CPP/optional.h
index 43b6c78de2a5..dd054a50f223 100644
--- a/libc/src/__support/CPP/optional.h
+++ b/libc/src/__support/CPP/optional.h
@@ -74,6 +74,10 @@ template <class T> class optional {
   constexpr T &operator*() & { return Storage.StoredValue; }
 
   constexpr const T &operator*() const & { return Storage.StoredValue; }
+
+  constexpr T *operator->() { return &Storage.StoredValue; }
+
+  constexpr const T *operator->() const { return &Storage.StoredValue; }
 };
 } // namespace cpp
 } // namespace __llvm_libc

diff  --git a/libc/test/src/__support/CPP/optional_test.cpp b/libc/test/src/__support/CPP/optional_test.cpp
index f13f931f7041..24d383e5bd0f 100644
--- a/libc/test/src/__support/CPP/optional_test.cpp
+++ b/libc/test/src/__support/CPP/optional_test.cpp
@@ -12,15 +12,19 @@
 using __llvm_libc::cpp::nullopt;
 using __llvm_libc::cpp::optional;
 
-// This has clase has two properties for testing:
-// 1) No default constructor
-// 2) A non-trivial destructor with an observable side-effect
+// This class has three properties for testing:
+// 1) No default constructor.
+// 2) A non-trivial destructor with an observable side-effect.
+// 3) Functions that can be called explicitly.
 class Contrived {
   int *_a;
 
 public:
   Contrived(int *a) : _a(a) {}
   ~Contrived() { (*_a)++; }
+
+  int get_a() { return *_a; }
+  void inc_a() { (*_a)++; }
 };
 
 TEST(LlvmLibcOptionalTest, Tests) {
@@ -59,4 +63,16 @@ TEST(LlvmLibcOptionalTest, Tests) {
   ASSERT_FALSE(Trivial5.has_value());
   optional<int> Trivial6 = Trivial5;
   ASSERT_FALSE(Trivial6.has_value());
+
+  // Test operator->
+  int arrow_num = 5;
+  optional<Contrived> arrow_test(&arrow_num);
+  ASSERT_TRUE(arrow_test.has_value());
+  ASSERT_EQ(arrow_test->get_a(), arrow_num);
+  arrow_num = 10;
+  ASSERT_EQ(arrow_test->get_a(), arrow_num);
+  arrow_test->inc_a();
+  ASSERT_EQ(arrow_test->get_a(), arrow_num);
+  ASSERT_EQ(arrow_num, 11);
+  arrow_test.reset();
 }


        


More information about the libc-commits mailing list