lib: Introduce macros for bit operations

These macros help clarify basic bit-twiddling code and are written to
be robust against C undefined behavior of shift operators.
This commit is contained in:
Austin Clements 2014-10-24 08:49:15 -04:00 committed by David Bremner
parent d9f5da00bb
commit d99491f274
2 changed files with 14 additions and 3 deletions

View file

@ -869,7 +869,7 @@ notmuch_bool_t
notmuch_message_get_flag (notmuch_message_t *message, notmuch_message_get_flag (notmuch_message_t *message,
notmuch_message_flag_t flag) notmuch_message_flag_t flag)
{ {
return message->flags & (1 << flag); return NOTMUCH_TEST_BIT (message->flags, flag);
} }
void void
@ -877,9 +877,9 @@ notmuch_message_set_flag (notmuch_message_t *message,
notmuch_message_flag_t flag, notmuch_bool_t enable) notmuch_message_flag_t flag, notmuch_bool_t enable)
{ {
if (enable) if (enable)
message->flags |= (1 << flag); NOTMUCH_SET_BIT (&message->flags, flag);
else else
message->flags &= ~(1 << flag); NOTMUCH_CLEAR_BIT (&message->flags, flag);
} }
time_t time_t

View file

@ -63,6 +63,17 @@ NOTMUCH_BEGIN_DECLS
#define STRNCMP_LITERAL(var, literal) \ #define STRNCMP_LITERAL(var, literal) \
strncmp ((var), (literal), sizeof (literal) - 1) strncmp ((var), (literal), sizeof (literal) - 1)
/* Robust bit test/set/reset macros */
#define NOTMUCH_TEST_BIT(val, bit) \
(((bit) < 0 || (bit) >= CHAR_BIT * sizeof (unsigned long long)) ? 0 \
: !!((val) & (1ull << (bit))))
#define NOTMUCH_SET_BIT(valp, bit) \
(((bit) < 0 || (bit) >= CHAR_BIT * sizeof (unsigned long long)) ? *(valp) \
: (*(valp) |= (1ull << (bit))))
#define NOTMUCH_CLEAR_BIT(valp, bit) \
(((bit) < 0 || (bit) >= CHAR_BIT * sizeof (unsigned long long)) ? *(valp) \
: (*(valp) &= ~(1ull << (bit))))
#define unused(x) x __attribute__ ((unused)) #define unused(x) x __attribute__ ((unused))
#ifdef __cplusplus #ifdef __cplusplus