diff --git a/src/hb-result.hh b/src/hb-result.hh index 9c85bfc9d..81743b453 100644 --- a/src/hb-result.hh +++ b/src/hb-result.hh @@ -73,7 +73,7 @@ static inline constexpr hb_result_err_t Err (E&& e) } template -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 -struct hb_result_t +struct HB_NODISCARD hb_result_t { private: union @@ -389,6 +389,16 @@ struct hb_result_t 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 + static hb_result_t 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 (); } diff --git a/src/test-result.cc b/src/test-result.cc index d5d41aed3..572be0309 100644 --- a/src/test-result.cc +++ b/src/test-result.cc @@ -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 r = result::from(has_error, ERR_B); + hb_always_assert(r.is_err()); + hb_always_assert(r.error() == ERR_B); + r = result::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; }