From 1f087ce15c20ef57d468bb6b94d6e5263aa812cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=9Aliwak?= Date: Thu, 23 Sep 2021 16:26:10 +0200 Subject: [PATCH] Define an assertThrow() variant that allows providing the default message --- libsolutil/Assertions.h | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/libsolutil/Assertions.h b/libsolutil/Assertions.h index b143e6ed7..815a76290 100644 --- a/libsolutil/Assertions.h +++ b/libsolutil/Assertions.h @@ -27,6 +27,8 @@ #include +#include + namespace solidity::util { @@ -38,16 +40,32 @@ namespace solidity::util #define ETH_FUNC __func__ #endif -/// Assertion that throws an exception containing the given description if it is not met. -/// Use it as assertThrow(1 == 1, ExceptionType, "Mathematics is wrong."); -/// Do NOT supply an exception object as the second parameter. -#define assertThrow(_condition, _exceptionType, _description) \ +namespace assertions +{ + +inline std::string stringOrDefault(std::string _string, std::string _defaultString) +{ + // NOTE: Putting this in a function rather than directly in a macro prevents the string from + // being evaluated multiple times if it's not just a literal. + return (!_string.empty() ? _string : _defaultString); +} + +} + +/// Base macro that can be used to implement assertion macros. +/// Throws an exception containing the given description if the condition is not met. +/// Allows you to provide the default description for the case where the user of your macro does +/// not provide any. +/// The second parameter must be an exception class (rather than an instance). +#define assertThrowWithDefaultDescription(_condition, _exceptionType, _description, _defaultDescription) \ do \ { \ if (!(_condition)) \ ::boost::throw_exception( \ _exceptionType() << \ - ::solidity::util::errinfo_comment(_description) << \ + ::solidity::util::errinfo_comment( \ + ::solidity::util::assertions::stringOrDefault(_description, _defaultDescription) \ + ) << \ ::boost::throw_function(ETH_FUNC) << \ ::boost::throw_file(__FILE__) << \ ::boost::throw_line(__LINE__) \ @@ -55,4 +73,10 @@ namespace solidity::util } \ while (false) +/// Assertion that throws an exception containing the given description if it is not met. +/// Use it as assertThrow(1 == 1, ExceptionType, "Mathematics is wrong."); +/// The second parameter must be an exception class (rather than an instance). +#define assertThrow(_condition, _exceptionType, _description) \ + assertThrowWithDefaultDescription(_condition, _exceptionType, _description, "") + }