Result: Add expect_ variants of value() and release_value()

This commit is contained in:
apio 2022-12-04 12:32:34 +01:00
parent bed29e71af
commit cdbed6970a
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -105,6 +105,12 @@ template <typename T> class Result
return m_storage.fetch_reference(); 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) T value_or(T other)
{ {
if (has_value()) return m_storage.fetch_reference(); if (has_value()) return m_storage.fetch_reference();
@ -127,6 +133,15 @@ template <typename T> class Result
return move(item); 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() ~Result()
{ {
if (has_value()) m_storage.destroy(); if (has_value()) m_storage.destroy();
@ -177,6 +192,7 @@ template <typename T> class Result
fetch_reference().~T(); fetch_reference().~T();
} }
}; };
Storage m_storage; Storage m_storage;
int m_error; int m_error;
bool m_has_error; bool m_has_error;
@ -243,12 +259,24 @@ template <> class Result<void>
return; return;
} }
void expect_value(const char* reason)
{
expect(has_value(), reason);
return;
}
void release_value() void release_value()
{ {
expect(has_value(), "Result::release_value() called on a Result that holds an error"); expect(has_value(), "Result::release_value() called on a Result that holds an error");
return; return;
} }
void expect_release_value(const char* reason)
{
expect(has_value(), reason);
return;
}
private: private:
int m_error; int m_error;
bool m_has_error; bool m_has_error;
@ -262,5 +290,5 @@ template <> class Result<void>
({ \ ({ \
auto _expr_rc = (expr); \ auto _expr_rc = (expr); \
if (_expr_rc.has_error()) return _expr_rc.release_error(); \ 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"); \
}) })