Arbutils/src/Ensure.hpp

86 lines
5.2 KiB
C++

/** @file */
#include "ErrorHelpers.hpp"
/// \defgroup Ensure Ensure
/// \brief A set of ensure macros.
#ifndef NO_ENSURE
/// @brief Ensures an expression is true. Throws an exception if the assertion fails.
/// @ingroup Ensure
#define Ensure(expr) \
if (!(expr)) { \
throw ArbUt::__ErrorHelpers::CreateEnsureError(#expr, std::source_location::current()); \
}
/// @brief Ensures two expressions are equal. Throws an exception if the assertion fails.
/// @ingroup Ensure
#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()); \
}
/// @brief Ensures a is greater than b. Throws an exception if the assertion fails.
/// @ingroup Ensure
#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()); \
}
/// @brief Ensures a is greater or equals to b. Throws an exception if the assertion fails.
/// @ingroup Ensure
#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()); \
}
/// @brief Ensures a is less than b. Throws an exception if the assertion fails.
/// @ingroup Ensure
#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()); \
}
/// @brief Ensures a is less than or equals to b. Throws an exception if the assertion fails.
/// @ingroup Ensure
#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) \
{ \
for (auto item : (iterator)) \
Ensure(assertion) \
}
#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) ;
#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)