Sane C++ Libraries
C++ Platform Abstraction Libraries
Result.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4namespace SC
5{
8
10struct [[nodiscard]] Result
11{
13 const char* message;
16 explicit constexpr Result(bool result) : message(result ? nullptr : "Unspecified Error") {}
17
22 template <int numChars>
23 static constexpr Result Error(const char (&msg)[numChars])
24 {
25 return Result(msg);
26 }
27
32 static constexpr Result FromStableCharPointer(const char* msg) { return Result(msg); }
33
35 constexpr operator bool() const { return message == nullptr; }
36
37 private:
38 explicit constexpr Result(const char* message) : message(message) {}
39};
41} // namespace SC
42
45
47#define SC_TRY(expression) \
48 { \
49 if (auto _exprResConv = SC::Result(expression)) \
50 SC_LANGUAGE_LIKELY \
51 { \
52 (void)0; \
53 } \
54 else \
55 { \
56 return _exprResConv; \
57 } \
58 }
59
61#define SC_TRY_MSG(expression, failedMessage) \
62 if (not(expression)) \
63 SC_LANGUAGE_UNLIKELY \
64 { \
65 return SC::Result::Error(failedMessage); \
66 }
67
69#define SC_TRUST_RESULT(expression) SC_ASSERT_RELEASE(expression)
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition: Result.h:11
static constexpr Result Error(const char(&msg)[numChars])
Constructs an Error from a pointer to an ASCII string literal.
Definition: Result.h:23
static constexpr Result FromStableCharPointer(const char *msg)
Constructs an Error from a pointer to an ascii string.
Definition: Result.h:32
constexpr Result(bool result)
Build a Result object from a boolean.
Definition: Result.h:16
const char * message
If == nullptr then Result is valid. If != nullptr it's the reason of the error.
Definition: Result.h:13