moddef-cpp
Idiomatic C++ runtime for ModDef
Loading...
Searching...
No Matches
error.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2
11#ifndef MODDEF_ERROR_HPP
12#define MODDEF_ERROR_HPP
13
14#include <expected>
15#include <string_view>
16
17extern "C" {
18#include "moddef/err.h"
19}
20
21namespace moddef {
22
25enum class Error : int {
26 Ok = MD_OK,
27 Transport = MD_ERR_TRANSPORT,
28 Parse = MD_ERR_PARSE,
29 NotFound = MD_ERR_NOT_FOUND,
30 ShortRead = MD_ERR_SHORT_READ,
31 Buffer = MD_ERR_BUFFER,
32 UnresolvedRef = MD_ERR_UNRESOLVED_REF,
33 ZeroScaleDenominator = MD_ERR_ZERO_SCALE_DEN,
34 ComposedBase = MD_ERR_COMPOSED_BASE,
35 NotWritable = MD_ERR_NOT_WRITABLE,
36 WrongType = MD_ERR_WRONG_TYPE,
37 Unsupported = MD_ERR_UNSUPPORTED,
38 ConstraintMin = MD_ERR_CONSTRAINT_MIN,
39 ConstraintMax = MD_ERR_CONSTRAINT_MAX,
40 ConstraintStep = MD_ERR_CONSTRAINT_STEP,
41 ConstraintAllowed = MD_ERR_CONSTRAINT_ALLOWED,
42 Discovery = MD_ERR_DISCOVERY,
43 Unavailable = MD_ERR_UNAVAILABLE,
44 CommandNotFound = MD_ERR_COMMAND_NOT_FOUND,
45 ParamMissing = MD_ERR_PARAM_MISSING,
46 PollTimeout = MD_ERR_POLL_TIMEOUT,
47 StepReference = MD_ERR_STEP_REF,
48};
49
50inline Error from_c(md_err_t e) noexcept { return static_cast<Error>(e); }
51inline md_err_t to_c(Error e) noexcept { return static_cast<md_err_t>(e); }
52
53inline std::string_view to_string(Error e) noexcept { return md_err_str(to_c(e)); }
54
56template <class T>
57using Result = std::expected<T, Error>;
58
59// Turn a C status into a Result, mapping MD_OK to the provided value.
60template <class T>
61inline Result<T> ok_or(md_err_t e, T value) {
62 if (e != MD_OK) return std::unexpected(from_c(e));
63 return value;
64}
65
66inline Result<void> check(md_err_t e) {
67 if (e != MD_OK) return std::unexpected(from_c(e));
68 return {};
69}
70
71} // namespace moddef
72
73#endif // MODDEF_ERROR_HPP
Blocking register-level transport.
Definition transport.hpp:28
Definition command.hpp:35
Error
Strongly typed mirror of md_err_t (same underlying values, so casts are free in both directions).
Definition error.hpp:25
std::expected< T, Error > Result
The canonical result type across the API; Result<void> for actions.
Definition error.hpp:57
Result< void > check(md_err_t e)
Definition error.hpp:66
md_err_t to_c(Error e) noexcept
Definition error.hpp:51
Result< T > ok_or(md_err_t e, T value)
Definition error.hpp:61
std::string_view to_string(Error e) noexcept
Definition error.hpp:53
Error from_c(md_err_t e) noexcept
Definition error.hpp:50