[PATCH v3 3/9] lib: Introduce macros for bit operations

Jani Nikula jani at nikula.org
Thu Oct 23 21:40:25 PDT 2014


On Oct 23, 2014 3:31 PM, "Austin Clements" <aclements at csail.mit.edu> wrote:
>
> These macros help clarify basic bit-twiddling code and are written to
> be robust against C undefined behavior of shift operators.
> ---
>  lib/message.cc        |  6 +++---
>  lib/notmuch-private.h | 11 +++++++++++
>  2 files changed, 14 insertions(+), 3 deletions(-)
>
> diff --git a/lib/message.cc b/lib/message.cc
> index 38bc929..55d2ff6 100644
> --- a/lib/message.cc
> +++ b/lib/message.cc
> @@ -869,7 +869,7 @@ notmuch_bool_t
>  notmuch_message_get_flag (notmuch_message_t *message,
>                           notmuch_message_flag_t flag)
>  {
> -    return message->flags & (1 << flag);
> +    return NOTMUCH_TEST_BIT (message->flags, flag);
>  }
>
>  void
> @@ -877,9 +877,9 @@ notmuch_message_set_flag (notmuch_message_t *message,
>                           notmuch_message_flag_t flag, notmuch_bool_t
enable)
>  {
>      if (enable)
> -       message->flags |= (1 << flag);
> +       NOTMUCH_SET_BIT (&message->flags, flag);
>      else
> -       message->flags &= ~(1 << flag);
> +       NOTMUCH_CLEAR_BIT (&message->flags, flag);
>  }
>
>  time_t
> diff --git a/lib/notmuch-private.h b/lib/notmuch-private.h
> index 36cc12b..7250291 100644
> --- a/lib/notmuch-private.h
> +++ b/lib/notmuch-private.h
> @@ -63,6 +63,17 @@ NOTMUCH_BEGIN_DECLS
>  #define STRNCMP_LITERAL(var, literal) \
>      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)))

bit should be in braces in the above, like valp.

Jani.

> +
>  #define unused(x) x __attribute__ ((unused))
>
>  #ifdef __cplusplus
> --
> 2.1.0
>
> _______________________________________________
> notmuch mailing list
> notmuch at notmuchmail.org
> http://notmuchmail.org/mailman/listinfo/notmuch
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://notmuchmail.org/pipermail/notmuch/attachments/20141024/21122ff7/attachment.html>


More information about the notmuch mailing list