Concept
Data structures are often aligned in memory to the word size. On 32 bit machines, this often results in the two least significant bits containing no information (as they have to be zero, due to this alignment). In many cases gaining two bits of information storage in RAM is all you need. In these case, pointer tagging can come in handy.
The tricky part is however to get this working portable on all architectures, possibly even on 8 bit machines that have no alignment requirements. This utility provides helpers to enforce alignment requirements for all platforms, so that pointer tagging can be used everywhere.
Usage
uint32_t bar;
} foo_t;
void isr_callback(void *data) {
work_on_data(ptr, tag);
}
int main(void) {
foo_t data;
uint8_t tag = 3;
void *ptr_and_tag =
ptrtag(&data, tag);
init_isr(params, isr_callback, ptr_and_tag);
}
|
#define | PTRTAG __attribute__((aligned(4))) |
| Pointers to data marked with this attribute will be tag-able. More...
|
|
|
static void * | ptrtag (void *ptr, uint8_t tag) |
| Create a tagged pointer. More...
|
|
static void * | ptrtag_ptr (void *tagged_ptr) |
| Extract the original pointer from a tagged pointer. More...
|
|
static uint8_t | ptrtag_tag (void *tagged_ptr) |
| Extract the tag from a tagged pointer. More...
|
|
◆ PTRTAG
#define PTRTAG __attribute__((aligned(4))) |
Pointers to data marked with this attribute will be tag-able.
This will ensure a minimum alignment of 4 bytes
Definition at line 77 of file ptrtag.h.
◆ ptrtag()
static void* ptrtag |
( |
void * |
ptr, |
|
|
uint8_t |
tag |
|
) |
| |
|
inlinestatic |
Create a tagged pointer.
- Parameters
-
ptr | Pointer to tag |
tag | Tag to add |
- Returns
- Tagged pointer encoding both
ptr
and tag
- Precondition
ptr
points to data marked with PTRTAG
-
tag
contains a two bit value (its numeric value 0, 1, 2, or 3)
Expect assertions blowing up when the preconditions are not met.
Definition at line 90 of file ptrtag.h.
◆ ptrtag_ptr()
static void* ptrtag_ptr |
( |
void * |
tagged_ptr | ) |
|
|
inlinestatic |
Extract the original pointer from a tagged pointer.
- Parameters
-
tagged_ptr | The tagged pointer to extract the original pointer from |
- Returns
- The original "un-tagged" pointer encoded in
tagged_ptr
Definition at line 103 of file ptrtag.h.
◆ ptrtag_tag()
static uint8_t ptrtag_tag |
( |
void * |
tagged_ptr | ) |
|
|
inlinestatic |
Extract the tag from a tagged pointer.
- Parameters
-
tagged_ptr | The tagged pointer to extract the original pointer from |
- Returns
- The tag encoded into
tagged_ptr
Definition at line 115 of file ptrtag.h.