ptrtag.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2020 Otto-von-Guericke-Universität Magdeburg
3  *
4  * This file is subject to the terms and conditions of the GNU Lesser General
5  * Public License v2.1. See the file LICENSE in the top level directory for more
6  * details.
7  */
8 
61 #ifndef PTRTAG_H
62 #define PTRTAG_H
63 
64 #include <assert.h>
65 #include <inttypes.h>
66 #include <stdint.h>
67 
68 #ifdef __cplusplus
69 extern "C" {
70 #endif
71 
77 #define PTRTAG __attribute__((aligned(4)))
78 
90 static inline void * ptrtag(void *ptr, uint8_t tag)
91 {
92  uintptr_t tmp = (uintptr_t)ptr;
93  /* ensure ptr is aligned to four bytes and tag fits in two bits */
94  assert((tag < 4) && !(tmp & 0x3));
95  return (void *)(tmp | tag);
96 }
97 
103 static inline void * ptrtag_ptr(void *tagged_ptr)
104 {
105  uintptr_t tagged = (uintptr_t)tagged_ptr;
106  const uintptr_t mask = 0x3;
107  return (void *)(tagged & (~mask));
108 }
109 
115 static inline uint8_t ptrtag_tag(void *tagged_ptr)
116 {
117  uintptr_t tagged = (uintptr_t)tagged_ptr;
118  return tagged & 0x3;
119 }
120 
121 #ifdef __cplusplus
122 }
123 #endif
124 
125 #endif /* PTRTAG_H */
126 
assert
#define assert(cond)
abort the program if assertion is false
Definition: assert.h:104
assert.h
POSIX.1-2008 compliant version of the assert macro.
ptrtag_tag
static uint8_t ptrtag_tag(void *tagged_ptr)
Extract the tag from a tagged pointer.
Definition: ptrtag.h:115
ptrtag_ptr
static void * ptrtag_ptr(void *tagged_ptr)
Extract the original pointer from a tagged pointer.
Definition: ptrtag.h:103
ptrtag
static void * ptrtag(void *ptr, uint8_t tag)
Create a tagged pointer.
Definition: ptrtag.h:90
inttypes.h
Adds include for missing inttype definitions.