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