wsutil: Rename ws_return_ptr_if_null() macro

Rename to ws_return_val_if_null() because the name needs to be more
generic to indicate it should be used to return any kind of value,
not just pointers.

Increase the log level to something more appropriate because failing
any of these checks is considered to be a programming error.

Add the faulty variable name to the output message.

Add the macro ws_return_val_if_zero() for completeness.
This commit is contained in:
João Valverde 2021-11-12 11:14:39 +00:00
parent 6587debb3b
commit 6630fd5260
2 changed files with 26 additions and 9 deletions

View File

@ -179,7 +179,7 @@ bytes_to_hexstr(char *out, const guint8 *ad, size_t len)
{
size_t i;
ws_return_ptr_if_null(ad, NULL);
ws_return_val_if_null(ad, NULL);
for (i = 0; i < len; i++)
out = byte_to_hex(out, ad[i]);
@ -199,7 +199,7 @@ bytes_to_hexstr_punct(char *out, const guint8 *ad, size_t len, char punct)
{
size_t i;
ws_return_ptr_if_null(ad, NULL);
ws_return_val_if_null(ad, NULL);
out = byte_to_hex(out, ad[0]);
for (i = 1; i < len; i++) {

View File

@ -12,33 +12,50 @@
#include <wsutil/wslog.h>
#include <wsutil/wmem/wmem.h>
#define ws_warn_zero_len() ws_warning("Zero length passed to %s", __func__)
/*
* These macros can be used as an alternative to ws_assert() to
* assert some condition on function arguments. This must only be used
* to catch programming errors, in situations where an assertion is
* appropriate. And it should only be used if failing the condition
* doesn't necessarily lead to an inconsistent state for the program.
*
* It is possible to set the fatal log level to "critical" to abort
* execution for debugging purposes, if one of these checks fail.
*/
#define ws_warn_null_ptr() ws_warning("Null pointer passed to %s", __func__)
#define ws_warn_zero_len(var) ws_critical("Zero length '%s' passed to %s()", var, __func__)
#define ws_warn_null_ptr(var) ws_critical("Null pointer '%s' passed to %s()", var, __func__)
#define ws_return_str_if_zero(scope, len) \
do { \
if (!(len)) { \
ws_warn_zero_len(); \
ws_warn_zero_len(#len); \
return wmem_strdup(scope, "(zero length)"); \
} \
} while (0)
#define ws_return_str_if_null(scope, ptr) \
do { \
if (!(ptr)) { \
ws_warn_null_ptr(); \
ws_warn_null_ptr(#ptr); \
return wmem_strdup(scope, "(null pointer)"); \
} \
} while (0)
#define ws_return_val_if_zero(len, val) \
do { \
if (!(len)) { \
ws_warn_zero_len(#len); \
return (val); \
} \
} while (0)
#define ws_return_ptr_if_null(ptr, val) \
#define ws_return_val_if_null(ptr, val) \
do { \
if (!(ptr)) { \
ws_warn_null_ptr(); \
ws_warn_null_ptr(#ptr); \
return (val); \
} \
} while (0)