[ccan] [PATCH] ptrint: Module for encoding integers into void * pointers

David Gibson david at gibson.dropbear.id.au
Tue May 26 22:57:35 AEST 2015


On Tue, May 26, 2015 at 09:35:31AM +0930, Paul 'Rusty' Russell wrote:
> 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.

Yeah, I was thinking about that, but got a bit bogged down in working
out where it would and wouldn't warn.

> 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.

So, I was planning to add it myself, but was hoping for at least some
review or comment first :).


> 
> 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

Fixed, ta.

-- 
David Gibson			| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you.  NOT _the_ _other_
				| _way_ _around_!
http://www.ozlabs.org/~dgibson
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 819 bytes
Desc: not available
URL: <http://lists.ozlabs.org/pipermail/ccan/attachments/20150526/4581ba9e/attachment.sig>


More information about the ccan mailing list