[ccan] [PATCH] ptrint: Module for encoding integers into void * pointers
Rusty Russell
rusty at rustcorp.com.au
Tue May 26 10:05:31 AEST 2015
David Gibson <david at gibson.dropbear.id.au> writes:
> For callbacks which need a void * context pointer in the general case,
> there are often simpler cases where an integer would suffice. These are
> often handled by casting the integer into a pointer, rather than having
> to allocate that integer somewhere.
>
> This adds a module with some helpers for this. It has some advantages over
> direct casts:
> * It uses pointer arithmetic against NULL instead of casts which should
> make it more portable, even to weird platforms with odd representations
> for NULL. I don't know the C standard well enough to know if it's
> totally portalbe though.
> * In particular it means that the truth value of the pointer
> representation matches that of the encoded integer.
> * The conversion functions are inlines providing more type safety than
> raw casts.
>
> Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
This looks good!
One typo fix.
I wonder if an undeclared 'struct ptrint' would be better than void *
here? Perhaps a bit more self-documenting for typesafe_cb users,
and AFAICT no change to your default void * use case.
BTW, I think it's OK if you just add modules yourself. But of course I
should start sending my modules to the list before dropping them in
CCAN, too.
Thanks,
Rusty.
> diff --git a/ccan/ptrint/ptrint.h b/ccan/ptrint/ptrint.h
> new file mode 100644
> index 0000000..fc68a57
> --- /dev/null
> +++ b/ccan/ptrint/ptrint.h
> @@ -0,0 +1,27 @@
> +/* CC0 (Public domain) - see LICENSE file for details */
> +#ifndef CCAN_PTRINT_H
> +#define CCAN_PTRINT_H
> +
> +#include "config.h"
> +
> +#include <stddef.h>
> +
> +#include <ccan/build_assert/build_assert.h>
> +
> +static inline ptrdiff_t ptr2int(const void *p)
> +{
> + /*
> + * ptrdiff_t is the right size by definition, but to avoid
> + * suprises we want a warning if the user can't fit at least a
surprises
Cheers,
Rusty.
More information about the ccan
mailing list