More efficient implementation of rfl::Result (#102)

This commit is contained in:
liuzicheng1987
2024-05-19 20:55:13 +02:00
committed by GitHub
parent 6bb95ff09b
commit 579ec6e919
2 changed files with 178 additions and 175 deletions
+172 -169
View File
@@ -1,6 +1,8 @@
#ifndef RFL_RESULT_HPP_
#define RFL_RESULT_HPP_
#include <array>
#include <iostream>
#include <optional>
#include <ranges>
#include <span>
@@ -11,6 +13,7 @@
#include <variant>
#include <vector>
#include "internal/is_array.hpp"
#include "internal/to_std_array.hpp"
namespace rfl {
@@ -39,35 +42,47 @@ template <class T>
class Result {
static_assert(!std::is_same<T, Error>(), "The result type cannot be Error.");
using TOrErr = std::array<unsigned char, std::max(sizeof(T), sizeof(Error))>;
public:
using Type = T;
Result(const T& _val) : t_or_err_(_val) {}
Result(const T& _val) : success_(true) { new (&get_t()) T(_val); }
Result(T&& _val) noexcept : t_or_err_(std::move(_val)) {}
Result(T&& _val) noexcept : success_(true) {
new (&get_t()) T(std::move(_val));
}
Result(const Error& _err) : t_or_err_(_err) {}
Result(const Error& _err) : success_(false) { new (&get_err()) Error(_err); }
Result(Error&& _err) noexcept : t_or_err_(std::move(_err)) {}
Result(Error&& _err) noexcept : success_(false) {
new (&get_err()) Error(std::move(_err));
}
Result(Result<T>&& _other) noexcept = default;
Result(Result<T>&& _other) noexcept : success_(_other.success_) {
move_from_other(_other);
}
Result(const Result<T>& _other) = default;
Result(const Result<T>& _other) : success_(_other.success_) {
copy_from_other(_other);
}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Result(Result<U>&& _other)
: t_or_err_(std::forward<Result<U>>(_other)
.transform([](U&& _u) { return T(std::forward<U>(_u)); })
.t_or_err_) {}
Result(Result<U>&& _other) : success_(_other && true) {
auto temp = std::forward<Result<U>>(_other).transform(
[](U&& _u) { return T(std::forward<U>(_u)); });
move_from_other(temp);
}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Result(const Result<U>& _other)
: t_or_err_(
_other.transform([](const U& _u) { return T(_u); }).t_or_err_) {}
Result(const Result<U>& _other) : success_(_other && true) {
auto temp = _other.transform([](const U& _u) { return T(_u); });
move_from_other(temp);
}
~Result() = default;
~Result() { destroy(); }
/// Returns Result<U>, if successful and error otherwise.
/// Inspired by .and(...) in the Rust std::result type.
@@ -82,18 +97,11 @@ class Result {
auto and_then(const F& _f) {
/// Result_U is expected to be of type Result<U>.
using Result_U = typename std::invoke_result<F, T>::type;
const auto handle_variant =
[&]<class TOrError>(TOrError&& _t_or_err) -> Result_U {
if constexpr (!std::is_same<std::remove_cvref_t<TOrError>, Error>()) {
return _f(std::forward<TOrError>(_t_or_err));
} else {
return std::forward<TOrError>(_t_or_err);
}
};
return std::visit(handle_variant,
std::forward<std::variant<T, Error>>(t_or_err_));
if (success_) {
return Result_U(_f(std::forward<T>(get_t())));
} else {
return Result_U(std::forward<Error>(get_err()));
}
}
/// Monadic operation - F must be a function of type T -> Result<U>.
@@ -101,107 +109,95 @@ class Result {
auto and_then(const F& _f) const {
/// Result_U is expected to be of type Result<U>.
using Result_U = typename std::invoke_result<F, T>::type;
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> Result_U {
if constexpr (!std::is_same<TOrError, Error>()) {
return _f(_t_or_err);
} else {
return _t_or_err;
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return Result_U(_f(get_t()));
} else {
return Result_U(get_err());
}
}
/// Results types can be iterated over, which even make it possible to use
/// them within a std::range.
T* begin() noexcept {
const auto get_ptr =
[this]<class TOrError>(const TOrError& _t_or_err) -> T* {
if constexpr (!std::is_same<TOrError, Error>()) {
return &_t_or_err;
} else {
return nullptr;
}
};
return std::visit(get_ptr, t_or_err_);
if (success_) {
return &get_t();
} else {
return nullptr;
}
}
/// Results types can be iterated over, which even make it possible to use
/// them within a std::range.
const T* begin() const noexcept {
const auto get_ptr =
[this]<class TOrError>(const TOrError& _t_or_err) -> const T* {
if constexpr (!std::is_same<TOrError, Error>()) {
return &_t_or_err;
} else {
return nullptr;
}
};
return std::visit(get_ptr, t_or_err_);
if (success_) {
return &get_t();
} else {
return nullptr;
}
}
/// Results types can be iterated over, which even make it possible to use
/// them within a std::range.
T* end() noexcept {
const auto get_ptr =
[this]<class TOrError>(const TOrError& _t_or_err) -> T* {
if constexpr (!std::is_same<TOrError, Error>()) {
return &_t_or_err + 1;
} else {
return nullptr;
}
};
return std::visit(get_ptr, t_or_err_);
if (success_) {
return &get_t() + 1;
} else {
return nullptr;
}
}
/// Results types can be iterated over, which even make it possible to use
/// them within a std::range.
const T* end() const noexcept {
const auto get_ptr =
[]<class TOrError>(const TOrError& _t_or_err) -> const T* {
if constexpr (!std::is_same<TOrError, Error>()) {
return &_t_or_err + 1;
} else {
return nullptr;
}
};
return std::visit(get_ptr, t_or_err_);
if (success_) {
return &get_t() + 1;
} else {
return nullptr;
}
}
/// Returns an std::optional<error> if this does in fact contain an error
/// or std::nullopt otherwise.
std::optional<Error> error() const noexcept {
const auto get_err =
[]<class TOrError>(const TOrError& _t_or_err) -> std::optional<Error> {
if constexpr (!std::is_same<TOrError, Error>()) {
return std::nullopt;
} else {
return _t_or_err;
}
};
return std::visit(get_err, t_or_err_);
if (success_) {
return std::nullopt;
} else {
return get_err();
}
}
/// Returns true if the result contains a value, false otherwise.
operator bool() const noexcept {
return !std::holds_alternative<Error>(t_or_err_);
}
operator bool() const noexcept { return success_; }
/// Allows access to the underlying value. Careful: Will result in undefined
/// behavior, if the result contains an error.
T& operator*() { return *std::get_if<T>(&t_or_err_); }
T& operator*() noexcept { return get_t(); }
/// Allows read access to the underlying value. Careful: Will result in
/// undefined behavior, if the result contains an error.
const T& operator*() const { return *std::get_if<T>(&t_or_err_); }
const T& operator*() const noexcept { return get_t(); }
/// Assigns the underlying object.
Result<T>& operator=(const Result<T>& _other) = default;
Result<T>& operator=(const Result<T>& _other) {
if (this == &_other) {
return *this;
}
destroy();
success_ = _other.success_;
copy_from_other(_other);
return *this;
}
/// Assigns the underlying object.
Result<T>& operator=(Result<T>&& _other) = default;
Result<T>& operator=(Result<T>&& _other) noexcept {
if (this == &_other) {
return *this;
}
destroy();
success_ = _other.success_;
move_from_other(_other);
return *this;
}
/// Assigns the underlying object.
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
@@ -216,31 +212,22 @@ class Result {
/// Result<T>.
template <class F>
Result<T> or_else(const F& _f) {
const auto handle_variant =
[&]<class TOrError>(TOrError&& _t_or_err) -> Result<T> {
if constexpr (std::is_same<std::remove_cvref_t<TOrError>, Error>()) {
return _f(std::forward<Error>(_t_or_err));
} else {
return std::forward<T>(_t_or_err);
}
};
return std::visit(handle_variant,
std::forward<std::variant<T, Error>>(t_or_err_));
if (success_) {
return std::forward<T>(get_t());
} else {
return _f(std::forward<Error>(get_err()));
}
}
/// Expects a function that takes of type Error -> Result<T> and returns
/// Result<T>.
template <class F>
Result<T> or_else(const F& _f) const {
const auto handle_variant =
[&_f]<class TOrError>(const TOrError& _t_or_err) -> Result<T> {
if constexpr (std::is_same<TOrError, Error>()) {
return _f(_t_or_err);
} else {
return _t_or_err;
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return get_t();
} else {
return _f(get_err());
}
}
/// Returns the value contained if successful or the provided result r if
@@ -255,18 +242,11 @@ class Result {
auto transform(const F& _f) {
/// Result_U is expected to be of type Result<U>.
using U = typename std::invoke_result<F, T>::type;
const auto handle_variant =
[&]<class TOrError>(TOrError&& _t_or_err) -> rfl::Result<U> {
if constexpr (!std::is_same<std::remove_cvref_t<TOrError>, Error>()) {
return _f(std::forward<TOrError>(_t_or_err));
} else {
return std::forward<TOrError>(_t_or_err);
}
};
return std::visit(handle_variant,
std::forward<std::variant<T, Error>>(t_or_err_));
if (success_) {
return rfl::Result<U>(_f(std::forward<T>(get_t())));
} else {
return rfl::Result<U>(std::forward<Error>(get_err()));
}
}
/// Functor operation - F must be a function of type T -> U.
@@ -274,75 +254,98 @@ class Result {
auto transform(const F& _f) const {
/// Result_U is expected to be of type Result<U>.
using U = typename std::invoke_result<F, T>::type;
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> rfl::Result<U> {
if constexpr (!std::is_same<TOrError, Error>()) {
return _f(_t_or_err);
} else {
return _t_or_err;
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return rfl::Result<U>(_f(get_t()));
} else {
return rfl::Result<U>(get_err());
}
}
/// Returns the value if the result does not contain an error, throws an
/// exceptions if not. Similar to .unwrap() in Rust.
T value() {
const auto handle_variant = [&]<class TOrError>(TOrError& _t_or_err) -> T {
if constexpr (!std::is_same<TOrError, Error>()) {
return std::forward<T>(_t_or_err);
} else {
throw std::runtime_error(_t_or_err.what());
}
};
return std::visit(handle_variant, t_or_err_);
T& value() {
if (success_) {
return get_t();
} else {
throw std::runtime_error(get_err().what());
}
}
/// Returns the value if the result does not contain an error, throws an
/// exceptions if not. Similar to .unwrap() in Rust.
const T& value() const {
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> const T& {
if constexpr (!std::is_same<TOrError, Error>()) {
return _t_or_err;
} else {
throw std::runtime_error(_t_or_err.what());
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return get_t();
} else {
throw std::runtime_error(get_err().what());
}
}
/// Returns the value or a default.
T value_or(T&& _default) noexcept {
const auto handle_variant = [&]<class TOrError>(TOrError&& _t_or_err) -> T {
using Type = std::remove_cvref_t<TOrError>;
if constexpr (!std::is_same<Type, Error>()) {
return std::forward<T>(_t_or_err);
} else {
return std::forward<T>(_default);
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return std::forward<T>(get_t());
} else {
return std::forward<T>(_default);
}
}
/// Returns the value or a default.
T value_or(const T& _default) const noexcept {
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> T {
if constexpr (!std::is_same<TOrError, Error>()) {
return _t_or_err;
} else {
return _default;
}
};
return std::visit(handle_variant, t_or_err_);
if (success_) {
return get_t();
} else {
return _default;
}
}
private:
/// The underlying variant, can either be T or Error.
std::variant<T, Error> t_or_err_;
void copy_from_other(const Result<T>& _other) {
if (success_) {
new (&get_t()) T(_other.get_t());
} else {
new (&get_err()) Error(_other.get_err());
}
}
void destroy() {
if (success_) {
if constexpr (std::is_destructible_v<T> /*&& !internal::is_array_v<T>*/) {
get_t().~T();
}
} else {
get_err().~Error();
}
}
T& get_t() noexcept { return *(reinterpret_cast<T*>(t_or_err_.data())); }
const T& get_t() const noexcept {
return *(reinterpret_cast<const T*>(t_or_err_.data()));
}
Error& get_err() noexcept {
return *(reinterpret_cast<Error*>(t_or_err_.data()));
}
const Error& get_err() const noexcept {
return *(reinterpret_cast<const Error*>(t_or_err_.data()));
}
void move_from_other(Result<T>& _other) {
if (success_) {
new (&get_t()) T(std::move(_other.get_t()));
} else {
new (&get_err()) Error(std::move(_other.get_err()));
}
}
private:
/// Signifies whether this was a success.
bool success_;
/// The underlying data, can either be T or Error.
alignas(std::max(alignof(T), alignof(Error))) TOrErr t_or_err_;
};
} // namespace rfl
+6 -6
View File
@@ -27,17 +27,15 @@ class ViewReader {
template <size_t _i = 0>
void read(const std::string_view& _name, const InputVarType& _var) const {
if constexpr (_i < size_) {
constexpr auto current_name =
std::tuple_element_t<_i, typename ViewType::Fields>::name();
using OriginalType =
typename std::tuple_element_t<_i, typename ViewType::Fields>::Type;
using FieldType = std::tuple_element_t<_i, typename ViewType::Fields>;
using OriginalType = std::remove_cvref_t<typename FieldType::Type>;
using CurrentType =
std::remove_cvref_t<std::remove_pointer_t<OriginalType>>;
constexpr auto current_name = FieldType::name();
if (!std::get<_i>(*found_) && _name == current_name) {
auto res = Parser<R, W, CurrentType, ProcessorsType>::read(*r_, _var);
if (res) {
if constexpr (std::is_pointer_v<OriginalType> ||
internal::is_array_v<OriginalType>) {
if constexpr (std::is_pointer_v<OriginalType>) {
move_to(rfl::get<_i>(*view_), &(*res));
} else {
rfl::get<_i>(*view_) = *res;
@@ -100,6 +98,8 @@ class ViewReader {
!std::is_array_v<Target>) {
::new (_t) Target(std::move(*_s));
} else if constexpr (internal::is_array_v<Source>) {
static_assert(std::is_array_v<Target>,
"Expected target to be a c-array.");
for (size_t i = 0; i < _s->arr_.size(); ++i) {
move_to(&((*_t)[i]), &(_s->arr_[i]));
}