diff --git a/include/sta/assert.hpp b/include/sta/assert.hpp new file mode 100644 index 0000000..e40ad0c --- /dev/null +++ b/include/sta/assert.hpp @@ -0,0 +1,95 @@ +/** + * @brief Assertion handling. + * + * Define `STA_ASSERT_ENABLE` in `` to enable. + * + * Defining `DEBUG` will automatically enable the module. + * Defining `NDEBUG` will always force module to be disabled. + * + * Both `assert_failed` and `assert_halt` provide weak definitions and + * can be overridden by the application. `assert_halt` is only called + * via the STA_HALT macro which can also be provided by the application. + * + * The default implementation of `assert_failed` uses `STA_DEBUG_PRINT` internally + * and will not generate any output if ` is disabled. + */ +#ifndef STA_ASSERT_HPP +#define STA_ASSERT_HPP + +#include + +#ifdef DEBUG +# ifndef STA_ASSERT_ENABLE +# define STA_ASSERT_ENABLE +# endif // !STA_ASSERT_ENABLE +#endif // DEBUG + +#ifdef NDEBUG +# ifdef STA_ASSERT_ENABLE +# undef STA_ASSERT_ENABLE +# endif // STA_ASSERT_ENABLE +#endif // NDEBUG + + +#ifdef STA_ASSERT_ENABLE + +#include +#include + + +namespace sta +{ + /** + * @brief Handle failed assertions. + * + * @param expr Asserted expression or message + * @param file File name + * @param line Line number + */ + void assert_failed(const char * expr, const char * file, uint32_t line); + /** + * @brief Stop execution. + */ + void assert_halt(); +} // namespace sta + + +// Use assert_halt if STA_HALT is not defined +# ifndef STA_HALT +# define STA_HALT() sta::assert_halt() +# endif // !STA_HALT + + +/** + * @brief Assert expression. + * + * @param expr Expression + */ +# define STA_ASSERT(expr) ((void)(!(expr) && (sta::assert_failed(#expr, __FILE__, __LINE__), 1) && (STA_HALT(), 1))) +/** + * @brief Assert expression. + * + * @param expr Expression + * @param msg Message shown on failure + */ +# define STA_ASSERT_MSG(expr, msg) ((void)(!(expr) && (sta::assert_failed(msg, __FILE__, __LINE__), 1) && (STA_HALT(), 1))) + +#else // !STA_ASSERT_ENABLE + +/** + * @brief Assert expression. + * + * @param expr Expression + */ +# define STA_ASSERT(expr, msg) ((void)0) +/** + * @brief Assert expression. + * + * @param expr Expression + * @param msg Message shown on failure + */ +# define STA_ASSERT_MSG(expr, msg) ((void)0) + +#endif // !STA_ASSERT_ENABLE + +#endif // STA_ASSERT_HPP diff --git a/src/assert.cpp b/src/assert.cpp new file mode 100644 index 0000000..c7e5805 --- /dev/null +++ b/src/assert.cpp @@ -0,0 +1,29 @@ +#include +#ifdef STA_ASSERT_ENABLE + +#include +#include + + +namespace sta +{ + STA_WEAK + void assert_failed(const char * expr, const char * file, uint32_t line) + { + // printf("%s:%d: Assertion failed: %s", file, line, expr) + STA_DEBUG_PRINT(file); + STA_DEBUG_PRINT(':'); + STA_DEBUG_PRINT(line); + STA_DEBUG_PRINT(": Assertion failed: "); + STA_DEBUG_PRINTLN(expr); + } + + STA_WEAK + void assert_halt() + { + while (true); + } +} // namespace sta + + +#endif // STA_ASSERT_ENABLE