]> git.ozlabs.org Git - ccan/blobdiff - ccan/ptrint/ptrint.h
ptrint: Module for encoding integers into void * pointers
[ccan] / ccan / ptrint / ptrint.h
diff --git a/ccan/ptrint/ptrint.h b/ccan/ptrint/ptrint.h
new file mode 100644 (file)
index 0000000..992e4b1
--- /dev/null
@@ -0,0 +1,34 @@
+/* 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>
+
+/*
+ * This is a deliberately incomplete type, because it should never be
+ * dereferenced - instead it marks pointer values which are actually
+ * encoding integers
+ */
+typedef struct ptrint ptrint_t;
+
+static inline ptrdiff_t ptr2int(const ptrint_t *p)
+{
+       /*
+        * ptrdiff_t is the right size by definition, but to avoid
+        * surprises we want a warning if the user can't fit at least
+        * a regular int in there
+        */
+       BUILD_ASSERT(sizeof(int) <= sizeof(ptrdiff_t));
+       return (const char *)p - (const char *)NULL;
+}
+
+static inline ptrint_t *int2ptr(ptrdiff_t i)
+{
+       return (ptrint_t *)((char *)NULL + i);
+}
+
+#endif /* CCAN_PTRINT_H */