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};
45
46inline Error from_c(md_err_t e) noexcept { return static_cast<Error>(e); }
47inline md_err_t to_c(Error e) noexcept { return static_cast<md_err_t>(e); }
48
49inline std::string_view to_string(Error e) noexcept { return md_err_str(to_c(e)); }
50
52template <class T>
53using Result = std::expected<T, Error>;
54
55// Turn a C status into a Result, mapping MD_OK to the provided value.
56template <class T>
57inline Result<T> ok_or(md_err_t e, T value) {
58 if (e != MD_OK) return std::unexpected(from_c(e));
59 return value;
60}
61
62inline Result<void> check(md_err_t e) {
63 if (e != MD_OK) return std::unexpected(from_c(e));
64 return {};
65}
66
67} // namespace moddef
68
69#endif // MODDEF_ERROR_HPP
Blocking register-level transport.
Definition transport.hpp:28
Definition device.hpp:28
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:53
Result< void > check(md_err_t e)
Definition error.hpp:62
md_err_t to_c(Error e) noexcept
Definition error.hpp:47
Result< T > ok_or(md_err_t e, T value)
Definition error.hpp:57
std::string_view to_string(Error e) noexcept
Definition error.hpp:49
Error from_c(md_err_t e) noexcept
Definition error.hpp:46