Last active
December 14, 2024 23:02
-
-
Save bitsycore/4b6fea729a427da6da222ed609af4ff8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <assert.h> | |
static_assert(sizeof(void*) == 8, "Pointer size must be 64 bits!"); | |
static_assert(sizeof(uint64_t) == 8, "uint64_t size must be 64 bits!"); | |
#define _INTERNAL_TPTR_PTR_MASK 0x0000FFFFFFFFFFFFULL | |
#define _INTERNAL_TPTR_FLAGS_MASK 0xFFFF000000000000ULL | |
#define TPTR(type) type##__tagged_ptr_ | |
#define DEFINE_TAGGED_PTR(type) typedef uint64_t type##__tagged_ptr_; | |
#define TPTR_CREATE(type, ptr, flags) (TPTR(type))((uint64_t)(ptr) & _INTERNAL_TPTR_PTR_MASK) | ((uint64_t)(flags) << 48); | |
#define TPTR_GET_PTR(type, tagged_ptr) ((type*)((tagged_ptr) & _INTERNAL_TPTR_PTR_MASK)) | |
#define TPTR_GET_FLAGS(tagged_ptr) ((uint16_t)(((tagged_ptr) & _INTERNAL_TPTR_FLAGS_MASK) >> 48)) | |
#define TPTR_SET_FLAGS(tagged_ptr, new_flags) (tagged_ptr) = ((tagged_ptr) & _INTERNAL_TPTR_PTR_MASK) | ((uint64_t)(new_flags) << 48); | |
#define TPTR_GET_DATA(type, tagged_ptr) (*TPTR_GET_PTR(type, tagged_ptr)) | |
// Define Type | |
DEFINE_TAGGED_PTR(int) | |
int main() { | |
int pointedData = 42; | |
uint16_t flags = 0xAABC; | |
// Create the tagged pointer | |
TPTR(int) tagged_ptr = TPTR_CREATE(int, &pointedData, flags); | |
// Print pointer and flags | |
printf("PTR : 0x%p\n", &pointedData); | |
printf("TPTR : 0x%p\n", (void *)tagged_ptr); | |
printf("TPTR->PTR : 0x%p\n", TPTR_GET_PTR(int, tagged_ptr)); | |
printf("TPTR->Flags : 0x%04X\n", TPTR_GET_FLAGS(tagged_ptr)); | |
printf("TPTR->Deref : %d\n", TPTR_GET_DATA(int, tagged_ptr)); | |
// Test Set Flags | |
uint16_t new_flags = 0x5A5A; | |
TPTR_SET_FLAGS(tagged_ptr, new_flags); | |
printf("Flags->TPTR : 0x%p\n", (void *)tagged_ptr); | |
printf("TPTR->Flags : 0x%04X\n", TPTR_GET_FLAGS(tagged_ptr)); | |
// Check | |
assert(TPTR_GET_PTR(int, tagged_ptr) == &pointedData); | |
assert(TPTR_GET_FLAGS(tagged_ptr) == new_flags); | |
assert(TPTR_GET_DATA(int, tagged_ptr) == 42); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment