From fe7d095647756c7d0e5060965efaaa96505470eb Mon Sep 17 00:00:00 2001 From: ridiculousfish Date: Sun, 16 Oct 2022 15:40:33 -0700 Subject: [PATCH] Add maybe_t::value_or This enables getting the value or returning the passed-in value. This is helpful for "default if none." --- src/fish_tests.cpp | 9 +++++++++ src/maybe.h | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/src/fish_tests.cpp b/src/fish_tests.cpp index f29bca3c7..28c38bd37 100644 --- a/src/fish_tests.cpp +++ b/src/fish_tests.cpp @@ -6435,6 +6435,10 @@ void test_maybe() { do_test(std::is_copy_assignable>::value == false); do_test(std::is_copy_constructible>::value == false); + // We can construct a maybe_t from noncopyable things. + maybe_t nmt{make_unique(42)}; + do_test(**nmt == 42); + maybe_t c1{"abc"}; maybe_t c2 = c1; do_test(c1.value() == "abc"); @@ -6442,6 +6446,11 @@ void test_maybe() { c2 = c1; do_test(c1.value() == "abc"); do_test(c2.value() == "abc"); + + do_test(c2.value_or("derp") == "abc"); + do_test(c2.value_or("derp") == "abc"); + c2.reset(); + do_test(c2.value_or("derp") == "derp"); } void test_layout_cache() { diff --git a/src/maybe.h b/src/maybe.h index bfcb4c83f..e48a07972 100644 --- a/src/maybe.h +++ b/src/maybe.h @@ -209,6 +209,14 @@ class maybe_t : private maybe_detail::conditionally_copyable_t { // Transfer the value to the caller. T acquire() { return impl_.acquire(); } + // Return (a copy of) our value, or the given value if we are empty. + T value_or(T v) const { + if (this->has_value()) { + return this->value(); + } + return v; + } + // Clear the value. void reset() { impl_.reset(); }