Arbutils/src/Ensure.hpp

76 lines
4.7 KiB
C++
Raw Normal View History

2020-09-24 18:40:21 +00:00
/** @file */
#include "ErrorHelpers.hpp"
2020-03-22 10:14:47 +00:00
/// \defgroup Ensure Ensure
/// \brief A set of ensure macros.
2020-03-22 10:14:47 +00:00
#ifndef NO_ENSURE
/// @brief Ensures an expression is true. Throws an exception if the assertion fails.
/// @ingroup Ensure
#define Ensure(expr) \
2020-03-22 11:20:39 +00:00
if (!(expr)) { \
throw ArbUt::__ErrorHelpers::CreateEnsureError(#expr, std::source_location::current()); \
2020-03-22 11:02:02 +00:00
}
2020-09-24 18:40:21 +00:00
#define EnsureEquals(a, b) \
if ((a) != (b)) { \
std::stringstream error_ss; \
error_ss << a << " was not equal to " << b; \
throw ArbUt::__ErrorHelpers::CreateEnsureError(error_ss.str().c_str(), std::source_location::current()); \
}
#define EnsureGreater(a, b) \
if ((a) <= (b)) { \
std::stringstream error_ss; \
error_ss << a << " was not equal to " << b; \
throw ArbUt::__ErrorHelpers::CreateEnsureError(error_ss.str().c_str(), std::source_location::current()); \
}
#define EnsureGreaterOrEquals(a, b) \
if ((a) < (b)) { \
std::stringstream error_ss; \
error_ss << a << " was not equal to " << b; \
throw ArbUt::__ErrorHelpers::CreateEnsureError(error_ss.str().c_str(), std::source_location::current()); \
}
#define EnsureLess(a, b) \
if ((a) >= (b)) { \
std::stringstream error_ss; \
error_ss << a << " was not equal to " << b; \
throw ArbUt::__ErrorHelpers::CreateEnsureError(error_ss.str().c_str(), std::source_location::current()); \
}
#define EnsureLessOrEquals(a, b) \
if ((a) > (b)) { \
std::stringstream error_ss; \
error_ss << a << " was not equal to " << b; \
throw ArbUt::__ErrorHelpers::CreateEnsureError(error_ss.str().c_str(), std::source_location::current()); \
}
/// @brief Ensures an expression is true for a range. The value in the range can be retrieved using ``item``.
/// @ingroup Ensure
#define EnsureForEach(iterator, assertion) \
2020-04-28 14:55:00 +00:00
{ \
2020-09-24 18:40:21 +00:00
for (auto item : (iterator)) \
Ensure(assertion) \
2020-04-28 14:55:00 +00:00
}
2020-03-22 10:14:47 +00:00
#else
// Ensure is empty if NO_ENSURE is defined.
#define Ensure(expr) ;
#define EnsureEquals(a, b) ;
#define EnsureGreater(a, b) ;
#define EnsureGreaterOrEquals(a, b) ;
#define EnsureLess(a, b) ;
#define EnsureLessOrEquals(a, b) ;
#define EnsureForEach(iterator, assertion) ;
2020-03-22 10:14:47 +00:00
#endif
/// @brief Ensures a pointer is not null.
/// @ingroup Ensure
#define EnsureNotNull(value) Ensure((value) != nullptr)
/// @brief Ensures a range is not null.
/// @ingroup Ensure
#define EnsureAllNotNull(iterator) EnsureForEach(iterator, item != nullptr)