Add no discard to hb_result_t so that it must be used when returned.

- Also adds a helper to convert containers with in_error() into a hb_result_t's.
This commit is contained in:
Garret Rieger committed 2026-09-02 16:30:59 -06:00
1 parent eca9f9f910
commit 9d25eeab63
2 files changed
+33 -2

No files matched your search

+12 -2
View File
@@ -73,7 +73,7 @@ static inline constexpr hb_result_err_t<E&&> Err (E&& e)
}
template <typename T, typename E>
struct hb_result_t
struct HB_NODISCARD hb_result_t
{
private:
union
@@ -295,7 +295,7 @@ struct hb_result_t
// Partial specialization for void
template <typename E>
struct hb_result_t<void, E>
struct HB_NODISCARD hb_result_t<void, E>
{
private:
union
@@ -389,6 +389,16 @@ struct hb_result_t<void, E>
new (std::addressof (err_)) E (std::move(e));
}
// V is any class which has an in_error() method. This checks the result
// of in_error() and returns either Ok() or Err(error_value).
template<typename V>
static hb_result_t<void, E> from(const V& fallible, E error_value) {
if (fallible.in_error()) {
return Err(error_value);
}
return Ok();
}
bool is_ok () const { return is_ok_; }
bool is_err () const { return !is_ok_; }
explicit operator bool () const { return is_ok (); }
+21
View File
@@ -501,6 +501,26 @@ static void test_return_moves_from_local ()
}
}
struct in_error_t {
bool successful;
in_error_t(bool s) : successful(s) {}
bool in_error() const {
return !successful;
}
};
static void test_from () {
in_error_t has_error(false);
in_error_t no_error(true);
result<void> r = result<void>::from(has_error, ERR_B);
hb_always_assert(r.is_err());
hb_always_assert(r.error() == ERR_B);
r = result<void>::from(no_error, ERR_B);
hb_always_assert(!r.is_err());
}
int main ()
{
test_ok_basic ();
@@ -514,6 +534,7 @@ int main ()
test_error_interception ();
test_move_only_types ();
test_return_moves_from_local ();
test_from();
return 0;
}