]> git.ozlabs.org Git - ccan/blob - ccan/ptrint/ptrint.h
ptrint: ptr2int and int2ptr are constant functions
[ccan] / ccan / ptrint / ptrint.h
1 /* CC0 (Public domain) - see LICENSE file for details */
2 #ifndef CCAN_PTRINT_H
3 #define CCAN_PTRINT_H
4
5 #include "config.h"
6
7 #include <stddef.h>
8
9 #include <ccan/build_assert/build_assert.h>
10 #include <ccan/compiler/compiler.h>
11
12 /*
13  * This is a deliberately incomplete type, because it should never be
14  * dereferenced - instead it marks pointer values which are actually
15  * encoding integers
16  */
17 typedef struct ptrint ptrint_t;
18
19 CONST_FUNCTION static inline ptrdiff_t ptr2int(const ptrint_t *p)
20 {
21         /*
22          * ptrdiff_t is the right size by definition, but to avoid
23          * surprises we want a warning if the user can't fit at least
24          * a regular int in there
25          */
26         BUILD_ASSERT(sizeof(int) <= sizeof(ptrdiff_t));
27         return (const char *)p - (const char *)NULL;
28 }
29
30 CONST_FUNCTION static inline ptrint_t *int2ptr(ptrdiff_t i)
31 {
32         return (ptrint_t *)((char *)NULL + i);
33 }
34
35 #endif /* CCAN_PTRINT_H */