Skip to content

Commit

Permalink
Adds bitwise and debug utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
simondevenish committed Nov 20, 2024
1 parent ac5e737 commit e6afa30
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
51 changes: 51 additions & 0 deletions include/allocx/allocx_bitwise.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#ifndef ALLOCX_BITWISE_UTILS_H
#define ALLOCX_BITWISE_UTILS_H

#include "allocx_core_types.h"

// Get the Nth bit of a value
#define ALLOCX_BIT(n) (1U << (n))

// Check if the Nth bit is set
#define ALLOCX_IS_BIT_SET(value, n) (((value) & ALLOCX_BIT(n)) != 0)

// Set the Nth bit
#define ALLOCX_SET_BIT(value, n) ((value) |= ALLOCX_BIT(n))

// Clear the Nth bit
#define ALLOCX_CLEAR_BIT(value, n) ((value) &= ~ALLOCX_BIT(n))

// Toggle the Nth bit
#define ALLOCX_TOGGLE_BIT(value, n) ((value) ^= ALLOCX_BIT(n))

// Generate a mask with the first N bits set
#define ALLOCX_MASK(n) ((1U << (n)) - 1)

// Extract a bitfield
#define ALLOCX_EXTRACT_FIELD(value, shift, mask) (((value) >> (shift)) & (mask))

// Insert a value into a bitfield
#define ALLOCX_INSERT_FIELD(value, field, shift, mask) \
(((value) & ~((mask) << (shift))) | (((field) & (mask)) << (shift)))

// Check if a value is a power of two
#define ALLOCX_IS_POWER_OF_TWO(value) ((value) && !((value) & ((value)-1)))

// Round up to the nearest power of two
#define ALLOCX_ROUND_UP_POWER_OF_TWO(value) \
(1ULL << (64 - __builtin_clzll((value)-1)))

// Round down to the nearest power of two
#define ALLOCX_ROUND_DOWN_POWER_OF_TWO(value) \
(1ULL << (__builtin_clzll(value) - (ALLOCX_IS_POWER_OF_TWO(value) ? 0 : 1)))

// Count the number of set bits (population count)
#define ALLOCX_COUNT_BITS(value) __builtin_popcountll(value)

// Find the position of the highest set bit (zero-based)
#define ALLOCX_HIGHEST_BIT_POSITION(value) (63 - __builtin_clzll(value))

// Find the position of the lowest set bit (zero-based)
#define ALLOCX_LOWEST_BIT_POSITION(value) (__builtin_ctzll(value))

#endif // ALLOCX_BITWISE_UTILS_H
24 changes: 24 additions & 0 deletions include/allocx/allocx_debug.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#ifndef ALLOCX_DEBUG_H
#define ALLOCX_DEBUG_H

#include <stdio.h>

// Debug Logging
#ifdef ALLOCX_DEBUG
#define ALLOCX_LOG(fmt, ...) fprintf(stderr, "[ALLOCX] " fmt "\n", ##__VA_ARGS__)
#else
#define ALLOCX_LOG(fmt, ...)
#endif

// Memory Dump
#define ALLOCX_DUMP_MEMORY(ptr, size) \
do { \
fprintf(stderr, "[ALLOCX] Memory Dump (size=%zu):\n", size); \
for (usize i = 0; i < (size); ++i) { \
fprintf(stderr, "%02x ", ((unsigned char*)(ptr))[i]); \
if ((i + 1) % 16 == 0) fprintf(stderr, "\n"); \
} \
fprintf(stderr, "\n"); \
} while (0)

#endif // ALLOCX_DEBUG_H

0 comments on commit e6afa30

Please sign in to comment.