From 21c2d8bd98c85db43425ce3874dfb57783b18594 Mon Sep 17 00:00:00 2001 From: Ali Mohammad Pur Date: Fri, 9 Dec 2022 20:14:06 +0330 Subject: [PATCH] AK: Add a Optional::value_or_lazy_evaluated(constructor_function) API This allows the user to avoid constructing the default value if the optional already contains a value. This is used by the Jakt runtime. --- AK/Optional.h | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/AK/Optional.h b/AK/Optional.h index 2620498fe7..59b1dd1013 100644 --- a/AK/Optional.h +++ b/AK/Optional.h @@ -227,6 +227,38 @@ public: return move(fallback); } + template + [[nodiscard]] ALWAYS_INLINE T value_or_lazy_evaluated(Callback callback) const + { + if (m_has_value) + return value(); + return callback(); + } + + template + [[nodiscard]] ALWAYS_INLINE Optional value_or_lazy_evaluated_optional(Callback callback) const + { + if (m_has_value) + return value(); + return callback(); + } + + template + [[nodiscard]] ALWAYS_INLINE ErrorOr try_value_or_lazy_evaluated(Callback callback) const + { + if (m_has_value) + return value(); + return TRY(callback()); + } + + template + [[nodiscard]] ALWAYS_INLINE ErrorOr> try_value_or_lazy_evaluated_optional(Callback callback) const + { + if (m_has_value) + return value(); + return TRY(callback()); + } + ALWAYS_INLINE T const& operator*() const { return value(); } ALWAYS_INLINE T& operator*() { return value(); } @@ -424,6 +456,38 @@ public: return {}; } + template + [[nodiscard]] ALWAYS_INLINE T value_or_lazy_evaluated(Callback callback) const + { + if (m_pointer != nullptr) + return value(); + return callback(); + } + + template + [[nodiscard]] ALWAYS_INLINE Optional value_or_lazy_evaluated_optional(Callback callback) const + { + if (m_pointer != nullptr) + return value(); + return callback(); + } + + template + [[nodiscard]] ALWAYS_INLINE ErrorOr try_value_or_lazy_evaluated(Callback callback) const + { + if (m_pointer != nullptr) + return value(); + return TRY(callback()); + } + + template + [[nodiscard]] ALWAYS_INLINE ErrorOr> try_value_or_lazy_evaluated_optional(Callback callback) const + { + if (m_pointer != nullptr) + return value(); + return TRY(callback()); + } + template()(declval())), auto IsErrorOr = IsSpecializationOf, typename OptionalType = Optional>> ALWAYS_INLINE Conditional, OptionalType> map(F&& mapper) {