Sane C++ Libraries
C++ Platform Abstraction Libraries
Result.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "Compiler.h" // SC_LANGUAGE_LIKELY
5namespace SC
6{
9
11struct [[nodiscard]] Result
12{
14 const char* message;
17 explicit constexpr Result(bool result) : message(result ? nullptr : "Unspecified Error") {}
18
23 template <int numChars>
24 static constexpr Result Error(const char (&msg)[numChars])
25 {
26 return Result(msg);
27 }
28
33 static constexpr Result FromStableCharPointer(const char* msg) { return Result(msg); }
34
36 constexpr operator bool() const { return message == nullptr; }
37
38 private:
39 explicit constexpr Result(const char* message) : message(message) {}
40};
42} // namespace SC
43
46
48#define SC_TRY(expression) \
49 { \
50 if (auto _exprResConv = SC::Result(expression)) \
51 SC_LANGUAGE_LIKELY \
52 { \
53 (void)0; \
54 } \
55 else \
56 { \
57 return _exprResConv; \
58 } \
59 }
60
62#define SC_TRY_MSG(expression, failedMessage) \
63 if (not(expression)) \
64 SC_LANGUAGE_UNLIKELY \
65 { \
66 return SC::Result::Error(failedMessage); \
67 }
68
70#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:12
static constexpr Result Error(const char(&msg)[numChars])
Constructs an Error from a pointer to an ASCII string literal.
Definition: Result.h:24
static constexpr Result FromStableCharPointer(const char *msg)
Constructs an Error from a pointer to an ascii string.
Definition: Result.h:33
constexpr Result(bool result)
Build a Result object from a boolean.
Definition: Result.h:17
const char * message
If == nullptr then Result is valid. If != nullptr it's the reason of the error.
Definition: Result.h:14