mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
Add Result<>, to use with/complement Error
An operation often has two pieces of underlying information: * the data returned as a result from that operation * an error that occurred while retrieving that data Merely returning the data is not good enough. Result<> allows exposing both the data, and the underlying error, and forces (via clang's consumable attribute) you to check for the error before you try to access the data.
This commit is contained in:
parent
7dd25141cd
commit
a82c60b22a
Notes:
sideshowbarker
2024-07-19 12:58:51 +09:00
Author: https://github.com/rburchell Commit: https://github.com/SerenityOS/serenity/commit/a82c60b22a7 Pull-request: https://github.com/SerenityOS/serenity/pull/385
1 changed files with 78 additions and 0 deletions
78
AK/Result.h
Normal file
78
AK/Result.h
Normal file
|
@ -0,0 +1,78 @@
|
|||
#pragma once
|
||||
|
||||
#include <AK/Assertions.h>
|
||||
#include <AK/Platform.h>
|
||||
#include <AK/Optional.h>
|
||||
|
||||
namespace AK {
|
||||
|
||||
template<typename T, typename E>
|
||||
class CONSUMABLE(unknown) Result {
|
||||
public:
|
||||
RETURN_TYPESTATE(unknown)
|
||||
Result(const T& res)
|
||||
: m_result(res)
|
||||
{}
|
||||
|
||||
RETURN_TYPESTATE(unknown)
|
||||
Result(const E& error)
|
||||
: m_error(error)
|
||||
{
|
||||
}
|
||||
|
||||
RETURN_TYPESTATE(unknown)
|
||||
Result(const T& res, const E& error)
|
||||
: m_result(res)
|
||||
, m_error(error)
|
||||
{
|
||||
}
|
||||
|
||||
RETURN_TYPESTATE(unknown)
|
||||
Result(Result&& other)
|
||||
: m_result(move(other.m_result))
|
||||
, m_error(move(other.m_error))
|
||||
{
|
||||
}
|
||||
|
||||
RETURN_TYPESTATE(unknown)
|
||||
Result(Result& other)
|
||||
: m_result(other.m_result)
|
||||
, m_error(other.m_error)
|
||||
{
|
||||
}
|
||||
|
||||
CALLABLE_WHEN("unknown", "consumed")
|
||||
~Result()
|
||||
{}
|
||||
|
||||
CALLABLE_WHEN(consumed)
|
||||
T& unwrap() {
|
||||
return m_result.value();
|
||||
}
|
||||
|
||||
CALLABLE_WHEN(consumed)
|
||||
E& error() {
|
||||
return m_error.value();
|
||||
}
|
||||
|
||||
bool has_error() const {
|
||||
return m_error.has_value();
|
||||
}
|
||||
bool has_value() const {
|
||||
return m_result.has_value();
|
||||
}
|
||||
|
||||
SET_TYPESTATE(consumed)
|
||||
bool failed() const {
|
||||
return m_error.value().failed();
|
||||
}
|
||||
|
||||
private:
|
||||
Optional<T> m_result;
|
||||
Optional<E> m_error;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
using AK::Result;
|
||||
|
Loading…
Reference in a new issue