From 7aa38d0b564907763c0fb9c11578369523e3c1a2 Mon Sep 17 00:00:00 2001 From: "Dirk-Jan C. Binnema" Date: Wed, 9 Aug 2023 20:13:12 +0300 Subject: [PATCH] option/result: add "unwrap" Sprinkle some more Rust on Option & Result --- lib/utils/mu-option.hh | 11 +++++++++++ lib/utils/mu-result.hh | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/utils/mu-option.hh b/lib/utils/mu-option.hh index 3ca683e0..32b1beea 100644 --- a/lib/utils/mu-option.hh +++ b/lib/utils/mu-option.hh @@ -21,6 +21,7 @@ #define MU_OPTION__ #include +#include #include namespace Mu { @@ -36,6 +37,16 @@ Some(T&& t) } constexpr auto Nothing = tl::nullopt; // 'None' is already taken. +template T +unwrap(Option&& res) +{ + if (!!res) + return std::move(res.value()); + else + throw std::runtime_error("failure is not an option"); +} + + /** * Maybe create a string from a const char pointer. * diff --git a/lib/utils/mu-result.hh b/lib/utils/mu-result.hh index c7d6aa30..46346ed5 100644 --- a/lib/utils/mu-result.hh +++ b/lib/utils/mu-result.hh @@ -106,8 +106,8 @@ Err(Error::Code code, GError **err, fmt::format_string frm, T&&... args) } -template -T unwrap(Result&& res) +template T +unwrap(Result&& res) { if (!!res) return std::move(res.value());