option/result: add "unwrap"

Sprinkle some more Rust on Option & Result
This commit is contained in:
Dirk-Jan C. Binnema 2023-08-09 20:13:12 +03:00
parent 04219b55f7
commit 7aa38d0b56
2 changed files with 13 additions and 2 deletions

View File

@ -21,6 +21,7 @@
#define MU_OPTION__ #define MU_OPTION__
#include <tl/optional.hpp> #include <tl/optional.hpp>
#include <stdexcept>
#include <string> #include <string>
namespace Mu { namespace Mu {
@ -36,6 +37,16 @@ Some(T&& t)
} }
constexpr auto Nothing = tl::nullopt; // 'None' is already taken. constexpr auto Nothing = tl::nullopt; // 'None' is already taken.
template<typename T> T
unwrap(Option<T>&& 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. * Maybe create a string from a const char pointer.
* *

View File

@ -106,8 +106,8 @@ Err(Error::Code code, GError **err, fmt::format_string<T...> frm, T&&... args)
} }
template<typename T> template<typename T> T
T unwrap(Result<T>&& res) unwrap(Result<T>&& res)
{ {
if (!!res) if (!!res)
return std::move(res.value()); return std::move(res.value());