From cdbed6970a08670b601187a4dc824da9ab74aa24 Mon Sep 17 00:00:00 2001 From: apio Date: Sun, 4 Dec 2022 12:32:34 +0100 Subject: [PATCH] Result: Add expect_ variants of value() and release_value() --- luna/Result.h | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/luna/Result.h b/luna/Result.h index ed99a04b..297fdec1 100644 --- a/luna/Result.h +++ b/luna/Result.h @@ -105,6 +105,12 @@ template class Result return m_storage.fetch_reference(); } + T expect_value(const char* reason) + { + expect(has_value(), reason); + return m_storage.fetch_reference(); + } + T value_or(T other) { if (has_value()) return m_storage.fetch_reference(); @@ -127,6 +133,15 @@ template class Result return move(item); } + T expect_release_value(const char* reason) + { + expect(has_value(), reason); + T item = m_storage.fetch_reference(); + m_has_value = false; + m_storage.destroy(); + return move(item); + } + ~Result() { if (has_value()) m_storage.destroy(); @@ -177,6 +192,7 @@ template class Result fetch_reference().~T(); } }; + Storage m_storage; int m_error; bool m_has_error; @@ -243,12 +259,24 @@ template <> class Result return; } + void expect_value(const char* reason) + { + expect(has_value(), reason); + return; + } + void release_value() { expect(has_value(), "Result::release_value() called on a Result that holds an error"); return; } + void expect_release_value(const char* reason) + { + expect(has_value(), reason); + return; + } + private: int m_error; bool m_has_error; @@ -262,5 +290,5 @@ template <> class Result ({ \ auto _expr_rc = (expr); \ if (_expr_rc.has_error()) return _expr_rc.release_error(); \ - _expr_rc.release_value(); \ + _expr_rc.expect_release_value("sanity check failed: has_error() returned false, yet result has no value"); \ })