feat(Functional): add compact Status, ErrorKind/ErrorCode, bounded chains, and Adapters (M-FUNCTIONAL-02)

This commit is contained in:
faumaray committed 2026-11-24 02:45:17 +03:00
1 parent 284d9635b5
commit 7f3395cb74
4 files changed
+556 -14

No files matched your search

+131
View File
@@ -0,0 +1,131 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cerrno>
#include <concepts>
#include <cstring>
#include <exception>
#include <expected>
#include <functional>
#include <new>
#include <optional>
#include <string>
#include <system_error>
#include <type_traits>
#include <utility>
namespace Void::Result
{
namespace Detail
{
template <typename T> struct is_expected_type : std::false_type {};
template <typename T, typename E>
struct is_expected_type<std::expected<T, E>> : std::true_type {};
template <typename T>
inline constexpr bool is_expected_v =
is_expected_type<std::remove_cvref_t<T>>::value;
} // namespace Detail
/// Convert `std::expected<T, E>` into `Result<T>` by invoking `map_error`
/// only on the error path. Supports `void` and move-only value types.
template <typename T, typename E, typename Map>
requires std::invocable<Map, E> &&
std::convertible_to<std::invoke_result_t<Map, E>, Error>
[[nodiscard]] constexpr Result<T> adapt(std::expected<T, E> exp,
Map&& map_error)
{
if (exp.has_value()) {
if constexpr (std::is_void_v<T>) {
return {};
} else {
return Result<T>{std::move(*exp)};
}
}
return Failure<Error>{static_cast<Error>(
std::invoke(std::forward<Map>(map_error), std::move(exp).error()))};
}
/// Invoke `fn()`, catching only exceptions accepted by
/// `map_exception(std::exception_ptr) -> std::optional<Error>`.
/// `std::bad_alloc` and unrecognized exceptions ALWAYS propagate.
template <typename F, typename Map>
requires std::invocable<F> &&
std::invocable<Map, std::exception_ptr> &&
std::convertible_to<
std::invoke_result_t<Map, std::exception_ptr>,
std::optional<Error>>
[[nodiscard]] auto try_invoke(F&& fn, Map&& map_exception)
{
using Raw = std::invoke_result_t<F>;
using Out = std::conditional_t<Detail::is_expected_v<Raw>, Raw,
Result<Raw>>;
try {
if constexpr (std::is_void_v<Raw>) {
std::invoke(std::forward<F>(fn));
return Out{};
} else if constexpr (Detail::is_expected_v<Raw>) {
return std::invoke(std::forward<F>(fn));
} else {
return Out{std::invoke(std::forward<F>(fn))};
}
} catch (const std::bad_alloc&) {
throw;
} catch (...) {
std::optional<Error> mapped = std::invoke(
std::forward<Map>(map_exception), std::current_exception());
if (mapped.has_value()) {
return Out{std::unexpected{std::move(*mapped)}};
}
throw;
}
}
/// Map a POSIX errno value into a classified Error carrying `std::error_code`.
[[nodiscard]] inline Error from_errno(int errnum, std::string message = {})
{
ErrorKind kind = ErrorKind::io;
switch (errnum) {
case EINVAL:
case EDOM:
case ERANGE: kind = ErrorKind::invalid_argument; break;
case ENOENT:
case ESRCH: kind = ErrorKind::not_found; break;
case EEXIST:
case EALREADY:
case EBUSY: kind = ErrorKind::conflict; break;
case ECANCELED: kind = ErrorKind::cancelled; break;
case ETIMEDOUT: kind = ErrorKind::timeout; break;
case EAGAIN:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
kind = ErrorKind::overloaded;
break;
case ENOSPC:
case ENOMEM:
case EMFILE:
case ENFILE: kind = ErrorKind::exhausted; break;
case ENOSYS:
case ENOTSUP:
#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP
case EOPNOTSUPP:
#endif
kind = ErrorKind::unsupported;
break;
case EILSEQ:
case EPROTO:
case EBADMSG: kind = ErrorKind::corrupt; break;
default: kind = ErrorKind::io; break;
}
if (message.empty()) {
message = std::strerror(errnum);
}
return Error{
Status{kind, ErrorCode{kSystemErrorDomain, errnum}},
std::move(message),
std::error_code{errnum, std::generic_category()}};
}
} // namespace Void::Result
+231 -14
View File
@@ -1,36 +1,222 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
namespace Void::Result
{
/// Machine-readable classification shared across Void modules (C-02).
enum class ErrorKind : std::uint8_t {
invalid_argument = 0,
not_found,
conflict,
cancelled,
timeout,
overloaded,
unsupported,
io,
corrupt,
exhausted,
internal
};
[[nodiscard]] constexpr std::string_view
to_string(ErrorKind kind) noexcept
{
switch (kind) {
case ErrorKind::invalid_argument: return "invalid_argument";
case ErrorKind::not_found: return "not_found";
case ErrorKind::conflict: return "conflict";
case ErrorKind::cancelled: return "cancelled";
case ErrorKind::timeout: return "timeout";
case ErrorKind::overloaded: return "overloaded";
case ErrorKind::unsupported: return "unsupported";
case ErrorKind::io: return "io";
case ErrorKind::corrupt: return "corrupt";
case ErrorKind::exhausted: return "exhausted";
case ErrorKind::internal: return "internal";
}
return "internal";
}
/// Explicit module error-domain identifiers. Domain 0 is reserved for
/// generic cross-module status values; domains are never assigned by
/// hashing type names.
inline constexpr std::uint32_t kGenericErrorDomain = 0;
inline constexpr std::uint32_t kCoreErrorDomain = 1;
inline constexpr std::uint32_t kMemoryErrorDomain = 2;
inline constexpr std::uint32_t kMathErrorDomain = 3;
inline constexpr std::uint32_t kTimeErrorDomain = 4;
inline constexpr std::uint32_t kBinaryErrorDomain = 5;
inline constexpr std::uint32_t kDataErrorDomain = 6;
inline constexpr std::uint32_t kAsyncErrorDomain = 7;
inline constexpr std::uint32_t kIoErrorDomain = 8;
inline constexpr std::uint32_t kStorageErrorDomain = 9;
inline constexpr std::uint32_t kSystemErrorDomain = 10;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
std::int32_t value{0};
[[nodiscard]] constexpr bool
operator==(const ErrorCode&) const noexcept = default;
};
/// Compact, allocation-free failure descriptor suitable for low-memory and
/// Memory-layer error paths.
struct Status {
ErrorKind kind{ErrorKind::internal};
ErrorCode code{};
[[nodiscard]] constexpr bool
operator==(const Status&) const noexcept = default;
};
inline constexpr std::size_t kDefaultMaxErrorFrames = 16;
inline constexpr std::size_t kDefaultMaxErrorMessageBytes = 1024;
inline constexpr std::size_t kDefaultMaxFormattedErrorBytes = 16 * 1024;
namespace Detail
{
inline void bound_message(std::string& msg, bool& truncated) noexcept
{
constexpr std::string_view suffix = "...[truncated]";
if (msg.size() <= kDefaultMaxErrorMessageBytes) {
return;
}
truncated = true;
const std::size_t keep =
kDefaultMaxErrorMessageBytes > suffix.size()
? kDefaultMaxErrorMessageBytes - suffix.size()
: 0;
msg.resize(keep);
try {
msg.append(suffix);
} catch (...) {
// Preserve noexcept guarantee on bounded shrink.
}
}
} // namespace Detail
/// Default error type for Void::Result::Result<T, E>.
///
/// An Error carries a free-form `message` and an optional chained
/// `cause`. New context layers can be added with `with_context()`,
/// which returns a new Error whose `cause` is the previous error —
/// useful for "loading config: parsing line 42: invalid number".
///
/// Errors are cheap to copy (the cause chain is shared via
/// shared_ptr).
/// An Error carries a machine-readable `Status`, an optional
/// `std::error_code`, a bounded human-readable `message`, and an optional
/// shared immutable `cause` chain capped at `kDefaultMaxErrorFrames` (16).
/// Constructing from `Status` performs zero heap allocations.
class Error
{
public:
Error() = default;
Error() noexcept = default;
explicit Error(Status status) noexcept : m_status(status) {}
Error(Status status, std::string message,
std::error_code sys = {}) noexcept
: m_status(status), m_system_code(sys),
m_message(std::move(message))
{
Detail::bound_message(m_message, m_truncated);
}
Error(ErrorKind kind, std::string message, ErrorCode code = {},
std::error_code sys = {}) noexcept
: Error(Status{kind, code}, std::move(message), sys)
{
}
explicit Error(std::string message) noexcept
: m_message(std::move(message))
{
Detail::bound_message(m_message, m_truncated);
}
Error(std::string message, Error cause)
: m_message(std::move(message)),
m_cause(std::make_shared<Error>(std::move(cause)))
: m_status(cause.m_status), m_system_code(cause.m_system_code),
m_message(std::move(message)), m_truncated(cause.m_truncated)
{
Detail::bound_message(m_message, m_truncated);
if (cause.m_depth < kDefaultMaxErrorFrames) {
m_depth = cause.m_depth + 1;
m_cause = std::make_shared<Error>(std::move(cause));
return;
}
// Exceeded frame budget: keep newest intermediate frames and
// pin the root frame at the tail so root classification/context
// is never lost.
std::vector<const Error*> chain;
chain.reserve(cause.m_depth);
for (const Error* cur = &cause; cur != nullptr;
cur = cur->m_cause.get()) {
chain.push_back(cur);
}
m_truncated = true;
std::shared_ptr<Error> tail =
std::make_shared<Error>(Error{*chain.back(), true});
const std::size_t keep_middle =
kDefaultMaxErrorFrames >= 2 ? kDefaultMaxErrorFrames - 2 : 0;
const std::size_t available_middle =
chain.size() > 1 ? chain.size() - 1 : 0;
const std::size_t take = std::min(keep_middle, available_middle);
for (std::size_t idx = take; idx > 0; --idx) {
auto node = std::make_shared<Error>(
Error{*chain[idx - 1], true});
node->m_cause = tail;
node->m_depth = tail->m_depth + 1;
node->m_truncated = true;
tail = std::move(node);
}
m_cause = std::move(tail);
m_depth = m_cause->m_depth + 1;
}
Error(const Error&) = default;
Error(Error&&) noexcept = default;
Error& operator=(const Error&) = default;
Error& operator=(Error&&) noexcept = default;
~Error() noexcept
{
std::shared_ptr<const Error> cur = std::move(m_cause);
while (cur && cur.use_count() == 1) {
auto mutable_cur = std::const_pointer_cast<Error>(cur);
auto next = std::move(mutable_cur->m_cause);
cur = std::move(next);
}
}
[[nodiscard]] Status status() const noexcept { return m_status; }
[[nodiscard]] ErrorKind kind() const noexcept
{
return m_status.kind;
}
[[nodiscard]] ErrorCode code() const noexcept
{
return m_status.code;
}
[[nodiscard]] std::error_code system_code() const noexcept
{
return m_system_code;
}
[[nodiscard]] std::size_t depth() const noexcept { return m_depth; }
[[nodiscard]] bool truncated() const noexcept
{
return m_truncated;
}
[[nodiscard]] const std::string& message() const noexcept
@@ -45,7 +231,7 @@ namespace Void::Result
}
/// Returns a new Error whose message is `ctx` and whose cause
/// is *this.
/// is *this, preserving root Status and system_code.
[[nodiscard]] Error with_context(std::string ctx) const&
{
return Error{std::move(ctx), *this};
@@ -56,24 +242,55 @@ namespace Void::Result
return Error{std::move(ctx), std::move(*this)};
}
/// Render the full cause chain as
/// Render the cause chain as
/// "outer\n caused by: middle\n caused by: inner"
/// bounded by `kDefaultMaxFormattedErrorBytes`.
[[nodiscard]] std::string format() const
{
std::string out = m_message;
std::string out =
m_message.empty() ? std::string{to_string(m_status.kind)}
: m_message;
const Error* cur = m_cause.get();
while (cur != nullptr) {
out += "\n caused by: ";
out += cur->m_message;
out += cur->m_message.empty()
? to_string(cur->m_status.kind)
: std::string_view{cur->m_message};
if (out.size() >= kDefaultMaxFormattedErrorBytes) {
break;
}
cur = cur->m_cause.get();
}
if (m_truncated) {
out += "\n [truncated: diagnostic limits applied]";
}
if (out.size() > kDefaultMaxFormattedErrorBytes) {
constexpr std::string_view suffix = "\n...[truncated]";
const std::size_t keep =
kDefaultMaxFormattedErrorBytes > suffix.size()
? kDefaultMaxFormattedErrorBytes - suffix.size()
: 0;
out.resize(keep);
out.append(suffix);
}
return out;
}
private:
Error(const Error& other, bool /*detach_cause*/)
: m_status(other.m_status), m_system_code(other.m_system_code),
m_message(other.m_message), m_depth(1),
m_truncated(other.m_truncated)
{
}
Status m_status{};
std::error_code m_system_code{};
std::string m_message;
std::shared_ptr<const Error> m_cause;
std::size_t m_depth{1};
bool m_truncated{false};
};
} // namespace Void::Result
+16
View File
@@ -37,6 +37,22 @@ namespace Void::Result
return Failure<Error>{Error{std::move(message)}};
}
/// Zero-allocation Failure factory from a compact Status.
[[nodiscard]] inline Failure<Error> fail(Status status) noexcept
{
return Failure<Error>{Error{status}};
}
/// Failure factory carrying explicit ErrorKind, message, and optional codes.
[[nodiscard]] inline Failure<Error> fail(ErrorKind kind,
std::string message,
ErrorCode code = {},
std::error_code sys = {})
{
return Failure<Error>{
Error{kind, std::move(message), code, sys}};
}
/// Convenience factory for a failed Result with an arbitrary E.
/// Constrained so string-like types resolve to the `std::string`
/// overload above (otherwise a literal `"..."` deduces E to a char
+178
View File
@@ -0,0 +1,178 @@
#include <Void/Functional/Adapters.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cerrno>
#include <cstddef>
#include <exception>
#include <expected>
#include <memory>
#include <new>
#include <optional>
#include <stdexcept>
#include <string>
#include <type_traits>
Void::Testing::Test compact_status_is_noexcept_and_empty_message()
{
constexpr Void::Result::Status st{
Void::Result::ErrorKind::overloaded,
Void::Result::ErrorCode{Void::Result::kAsyncErrorDomain, 42}};
static_assert(std::is_nothrow_constructible_v<Void::Result::Error,
Void::Result::Status>);
static_assert(std::is_nothrow_move_constructible_v<Void::Result::Error>);
static_assert(noexcept(Void::Result::fail(st)));
Void::Result::Error err{st};
auto r = Void::Result::fail(st);
Void::Testing::expect(err.kind() == Void::Result::ErrorKind::overloaded);
Void::Testing::expect(err.code() == st.code);
Void::Testing::expect(err.message().empty());
Void::Testing::expect(err.cause() == nullptr);
Void::Testing::expect(!err.truncated());
Void::Testing::expect(r.error().kind() ==
Void::Result::ErrorKind::overloaded);
}
Void::Testing::Test context_chain_caps_at_16_and_preserves_root()
{
Void::Result::Error err{
Void::Result::ErrorKind::not_found, "root missing file",
Void::Result::ErrorCode{Void::Result::kSystemErrorDomain, ENOENT},
std::error_code{ENOENT, std::generic_category()}};
for (int i = 1; i <= 19; ++i) {
err = std::move(err).with_context("layer_" + std::to_string(i));
}
Void::Testing::expect_eq(err.depth(),
Void::Result::kDefaultMaxErrorFrames);
Void::Testing::expect(err.truncated());
Void::Testing::expect(err.kind() == Void::Result::ErrorKind::not_found);
Void::Testing::expect_eq(err.code().domain,
Void::Result::kSystemErrorDomain);
Void::Testing::expect_eq(err.code().value, ENOENT);
Void::Testing::expect_eq(err.system_code().value(), ENOENT);
Void::Testing::expect_eq(err.message(), std::string{"layer_19"});
const Void::Result::Error* tail = &err;
std::size_t count = 1;
while (tail->cause() != nullptr) {
tail = tail->cause().get();
++count;
}
Void::Testing::expect_eq(count, Void::Result::kDefaultMaxErrorFrames);
Void::Testing::expect_eq(tail->message(), std::string{"root missing file"});
const std::string rendered = err.format();
Void::Testing::expect(rendered.find("root missing file") !=
std::string::npos);
Void::Testing::expect(rendered.find("[truncated:") != std::string::npos);
}
Void::Testing::Test message_and_format_bounds_enforced()
{
std::string huge(3000, 'x');
Void::Result::Error single{Void::Result::ErrorKind::invalid_argument,
std::move(huge)};
Void::Testing::expect(single.truncated());
Void::Testing::expect(single.message().size() <=
Void::Result::kDefaultMaxErrorMessageBytes);
Void::Testing::expect(single.message().ends_with("...[truncated]"));
// Build a 16-frame chain of 1 KiB messages to check total formatted cap
// (~16+ KiB > kDefaultMaxFormattedErrorBytes).
std::string chunk(1000, 'y');
Void::Result::Error chain{Void::Result::ErrorKind::corrupt, chunk};
for (int i = 0; i < 16; ++i) {
chain = std::move(chain).with_context(chunk);
}
const std::string formatted = chain.format();
Void::Testing::expect(formatted.size() <=
Void::Result::kDefaultMaxFormattedErrorBytes);
}
Void::Testing::Test adapt_handles_move_only_void_and_skips_mapper_on_ok()
{
bool mapper_called = false;
auto ok_ptr = Void::Result::adapt(
std::expected<std::unique_ptr<int>, int>{std::make_unique<int>(99)},
[&](int) {
mapper_called = true;
return Void::Result::Error{"bad"};
});
Void::Testing::expect(!mapper_called);
Void::Testing::expect(ok_ptr.has_value() && **ok_ptr == 99);
auto err_void = Void::Result::adapt(
std::expected<void, int>{std::unexpected{7}}, [&](int v) {
mapper_called = true;
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"code " + std::to_string(v)};
});
Void::Testing::expect(mapper_called);
Void::Testing::expect(!err_void.has_value());
Void::Testing::expect(err_void.error().kind() ==
Void::Result::ErrorKind::invalid_argument);
}
Void::Testing::Test try_invoke_maps_known_and_rethrows_unknown_and_bad_alloc()
{
auto map_known = [](std::exception_ptr ep)
-> std::optional<Void::Result::Error> {
try {
std::rethrow_exception(ep);
} catch (const std::invalid_argument& ex) {
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, ex.what()};
} catch (...) {
return std::nullopt;
}
};
auto mapped = Void::Result::try_invoke(
[]() -> int { throw std::invalid_argument{"bad arg"}; }, map_known);
Void::Testing::expect(!mapped.has_value());
Void::Testing::expect(mapped.error().kind() ==
Void::Result::ErrorKind::invalid_argument);
bool rethrew_unknown = false;
try {
(void)Void::Result::try_invoke(
[]() -> void { throw std::runtime_error{"unhandled"}; }, map_known);
} catch (const std::runtime_error&) {
rethrew_unknown = true;
}
Void::Testing::expect(rethrew_unknown);
bool rethrew_bad_alloc = false;
auto catch_all_mapper = [](std::exception_ptr)
-> std::optional<Void::Result::Error> {
return Void::Result::Error{"should not catch bad_alloc"};
};
try {
(void)Void::Result::try_invoke(
[]() -> int { throw std::bad_alloc{}; }, catch_all_mapper);
} catch (const std::bad_alloc&) {
rethrew_bad_alloc = true;
}
Void::Testing::expect(rethrew_bad_alloc);
}
Void::Testing::Test from_errno_maps_categories()
{
const auto nf = Void::Result::from_errno(ENOENT);
Void::Testing::expect(nf.kind() == Void::Result::ErrorKind::not_found);
Void::Testing::expect_eq(nf.system_code().value(), ENOENT);
const auto to = Void::Result::from_errno(ETIMEDOUT, "socket wait");
Void::Testing::expect(to.kind() == Void::Result::ErrorKind::timeout);
Void::Testing::expect_eq(to.message(), std::string{"socket wait"});
const auto ex = Void::Result::from_errno(ENOSPC);
Void::Testing::expect(ex.kind() == Void::Result::ErrorKind::exhausted);
}