memory_arena
Loading...
Searching...
No Matches
Modules | Files | Functions
Internal Implementation

Base group for internal implementation details. More...

+ Collaboration diagram for Internal Implementation:

Modules

 Arena Initialization Internals
 Internal helpers for arena setup and configuration.
 
 Arena Cleanup Internals
 Internal helpers for teardown and memory release.
 
 Arena Allocation Internals
 Internal helpers for memory allocation logic.
 
 Sub-Arena Internals
 Internal helpers for configuring sub-arenas.
 
 Arena Resize Internals
 Internal helpers for growing and shrinking memory buffers.
 
 Scratch Arena Internals
 Internal helpers and utilities for scratch arena pool management.
 

Files

file  arena_internal.c
 Internal utilities and metadata management for the Arena memory system.
 
file  arena_internal.h
 Internal utilities and helpers for arena memory management.
 

Functions

static size_t align_up (size_t value, size_t alignment)
 Align a value upwards to the nearest multiple of alignment.
 
static void * arena_alloc_buffer (size_t size)
 Allocate a zero-initialized memory buffer for the arena.
 
static t_arena * arena_alloc_struct (void)
 Allocate and zero-initialize a new arena struct.
 
static bool arena_finish_init (t_arena *arena, void *buffer, size_t size, bool allow_grow)
 Finalize the initialization of an arena with a provided buffer.
 
static bool arena_init_mutex (t_arena *arena)
 Initialize the mutex used for thread-safe arena operations.
 
bool arena_is_valid (const t_arena *arena)
 Check whether the given arena is in a valid, initialized state.
 
static void arena_log_and_teardown (t_arena **arena, const char *msg)
 Report an error, destroy the arena, and free its memory.
 
static void arena_reset_metadata (t_arena *arena)
 Reset all arena metadata fields to their default initial state.
 
static bool arena_set_allocated_buffer (t_arena *arena, size_t size)
 Allocate and assign a zero-initialized buffer to an arena.
 
static void arena_set_default_label (t_arena *arena, const char *fallback)
 Set a fallback debug label if none is set.
 
static bool arena_set_or_alloc_buffer (t_arena *arena, void *buffer, size_t size)
 Configure an arena's buffer by either assigning a user-provided region or allocating one internally.
 
static void arena_set_user_buffer (t_arena *arena, void *buffer, size_t size)
 Assign a user-provided buffer to an arena without taking ownership.
 
void arena_update_peak (t_arena *arena)
 Update the arena’s peak memory usage if the current usage exceeds it.
 
void arena_zero_metadata (t_arena *arena)
 Zero out and reset all debug/stats metadata associated with the arena.
 
size_t default_grow_cb (size_t current_size, size_t requested_size)
 Default growth policy callback for arena resizing.
 
static size_t next_power_of_two (size_t x)
 Return the next power of two greater than or equal to x.
 
static bool would_overflow_mul (size_t a, size_t b, size_t *result)
 Perform a checked multiplication of two size_t values.
 

Detailed Description

Base group for internal implementation details.

This group collects all static inline functions, helpers, and low-level logic used internally by the arena system. These are not part of the public API and may change at any time.

Function Documentation

◆ align_up()

static size_t align_up ( size_t  value,
size_t  alignment 
)
inlinestatic

#include <arena_math.h>

Align a value upwards to the nearest multiple of alignment.

Returns the smallest multiple of alignment that is greater than or equal to value. alignment must be a power of two.

Parameters
valueThe value to align.
alignmentThe alignment boundary (must be power of two).
Returns
The aligned value.
Note
This function is commonly used for computing aligned memory offsets.
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/allocation/arena_alloc.c.

Definition at line 52 of file arena_math.h.

53 {
54 return (value + alignment - 1) & ~(alignment - 1);
55 }

◆ arena_alloc_buffer()

static void * arena_alloc_buffer ( size_t  size)
inlinestatic

#include <arena_create.c>

Allocate a zero-initialized memory buffer for the arena.

This function wraps calloc to allocate a contiguous zeroed memory region of size bytes. It is used when the arena needs to allocate its own internal memory buffer (rather than relying on an external one provided by the user).

If allocation fails, the function reports the failure using arena_report_error.

Parameters
sizeThe number of bytes to allocate.
Returns
A pointer to the allocated memory buffer, or NULL if allocation fails.
Note
The buffer must be freed manually if the initialization of the arena fails.
See also
arena_create
arena_init
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 492 of file arena_create.c.

493{
494 void* buffer = calloc(1, size);
495 if (!buffer)
496 arena_report_error(NULL, "arena_create failed: buffer allocation of %zu bytes failed", size);
497 return buffer;
498}
void arena_report_error(t_arena *arena, const char *fmt,...)
Report an error from an arena using its configured error callback.

References arena_report_error().

◆ arena_alloc_struct()

static t_arena * arena_alloc_struct ( void  )
inlinestatic

#include <arena_create.c>

Allocate and zero-initialize a new arena struct.

This internal helper allocates memory for a t_arena structure using calloc, which ensures all fields are zero-initialized. This guarantees a clean slate before any initialization logic is applied, helping avoid undefined behavior from stale data.

On failure, the function returns NULL. The calling function is responsible for handling the failure and cleaning up if needed.

This function does not allocate the memory buffer used for allocations— it only handles the control structure itself.

Returns
Pointer to a newly allocated t_arena, or NULL on failure.
See also
arena_create
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 426 of file arena_create.c.

427{
428 return (t_arena*) calloc(1, sizeof(t_arena));
429}
The main memory arena structure used for fast allocation.

◆ arena_finish_init()

static bool arena_finish_init ( t_arena *  arena,
void *  buffer,
size_t  size,
bool  allow_grow 
)
inlinestatic

#include <arena_create.c>

Finalize the initialization of an arena with a provided buffer.

This internal helper is used to complete the setup of an arena after a memory buffer has been successfully allocated.

The function performs the following:

  • Resets the arena's internal state via arena_reset_metadata.
  • Sets the buffer, size, and ownership flag.
  • Initializes flags for growth and destruction status.
  • Initializes the mutex (if thread safety is enabled).
  • Generates a unique debug ID for the arena.

If mutex initialization fails, the buffer is freed immediately to avoid memory leaks and the function returns false. Ownership of the arena structure itself remains with the caller.

Parameters
arenaPointer to the arena being initialized.
bufferPre-allocated memory buffer for arena use.
sizeSize of the memory buffer in bytes.
allow_growWhether the arena may grow dynamically if full.
Returns
true on success, false if mutex setup failed.
See also
arena_create
arena_init
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 640 of file arena_create.c.

641{
643 arena->buffer = (uint8_t*) buffer;
644 arena->size = size;
645 atomic_store_explicit(&arena->owns_buffer, true, memory_order_release);
646 atomic_store_explicit(&arena->can_grow, allow_grow, memory_order_release);
647 atomic_store_explicit(&arena->is_destroying, false, memory_order_release);
648
649 if (!arena_init_mutex(arena))
650 {
651 free(buffer);
652 return false;
653 }
654 arena_generate_id(arena);
655 return true;
656}
void arena_generate_id(t_arena *arena)
Generate a unique debug ID for an arena.
static void arena_reset_metadata(t_arena *arena)
Reset all arena metadata fields to their default initial state.
static bool arena_init_mutex(t_arena *arena)
Initialize the mutex used for thread-safe arena operations.

References arena_generate_id(), arena_init_mutex(), and arena_reset_metadata().

◆ arena_init_mutex()

static bool arena_init_mutex ( t_arena *  arena)
inlinestatic

#include <arena_create.c>

Initialize the mutex used for thread-safe arena operations.

If ARENA_ENABLE_THREAD_SAFE is defined, this function sets up a recursive pthread_mutex_t for the arena, enabling safe concurrent access to mutable fields like offset or marker stack state.

It uses PTHREAD_MUTEX_RECURSIVE to allow nested locks within the same thread, which is necessary for safe usage patterns like reentrant allocators or hooks.

On failure during any part of mutex attribute or lock initialization, it logs a detailed error and returns false. The caller is expected to clean up on failure.

If thread safety is not enabled at compile time, the function is a no-op that always returns true.

Parameters
arenaPointer to the arena for which the mutex should be initialized.
Returns
true on success, false if mutex setup failed.
See also
arena_finish_init
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 585 of file arena_create.c.

586{
587#ifdef ARENA_ENABLE_THREAD_SAFE
588 pthread_mutexattr_t attr;
589 if (pthread_mutexattr_init(&attr) != 0)
590 goto fail;
591 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0)
592 goto fail_attr;
593 if (pthread_mutex_init(&arena->lock, &attr) != 0)
594 goto fail_attr;
595 pthread_mutexattr_destroy(&attr);
596 arena->use_lock = true;
597 return true;
598fail_attr:
599 pthread_mutexattr_destroy(&attr);
600fail:
601 arena_report_error(NULL, "arena_create failed: mutex setup failed");
602 return false;
603#else
604 (void) arena;
605 return true;
606#endif
607}

References arena_report_error().

◆ arena_is_valid()

bool arena_is_valid ( const t_arena *  arena)

#include <arena_internal.h>

Check whether the given arena is in a valid, initialized state.

Check whether an arena is in a valid state.

Parameters
arenaPointer to the arena to check.
Returns
true if the arena is valid, false otherwise.

This function verifies the structural integrity of a t_arena instance. It ensures:

  • The arena pointer is not NULL.
  • The buffer pointer is initialized.
  • The size is non-zero and the current offset does not exceed the size.

This is useful for defensive checks before performing operations on an arena.

Parameters
arenaPointer to the arena to validate.
Returns
true if the arena is valid, false otherwise.
Note
This function does not verify internal metadata such as mutex state or hooks.
See also
arena_init

Definition at line 150 of file arena_internal.c.

151{
152 if (!arena)
153 return false;
154 if (!arena->buffer)
155 return false;
156 if (arena->size == 0 || arena->offset > arena->size)
157 return false;
158 return true;
159}

◆ arena_log_and_teardown()

static void arena_log_and_teardown ( t_arena **  arena,
const char *  msg 
)
inlinestatic

#include <arena_create.c>

Report an error, destroy the arena, and free its memory.

This helper is used to cleanly handle failure paths in arena creation or initialization. It prints a formatted error message using arena_report_error, then proceeds to safely destroy the arena and free the t_arena structure via arena_destroy() and arena_delete().

If the arena pointer is NULL or points to NULL, only the error is logged and no cleanup is performed. This guards against double-frees or null dereferences.

Parameters
arenaA pointer to a pointer to a t_arena structure. May be NULL.
msgA formatted error message passed to arena_report_error.
Note
This function assumes ownership of the arena and will leave the pointer invalid.
See also
arena_create
arena_init
arena_report_error
arena_destroy
arena_delete
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 458 of file arena_create.c.

459{
460 if (!arena || !*arena)
461 {
462 arena_report_error(NULL, "%s", msg);
463 return;
464 }
465 arena_report_error(*arena, "%s", msg);
466 arena_destroy(*arena);
467 arena_delete(arena);
468}
void arena_destroy(t_arena *arena)
void arena_delete(t_arena **arena)

References arena_delete(), arena_destroy(), and arena_report_error().

◆ arena_reset_metadata()

static void arena_reset_metadata ( t_arena *  arena)
inlinestatic

#include <arena_create.c>

Reset all arena metadata fields to their default initial state.

This function clears the entire t_arena structure's internal metadata, ensuring a clean and consistent base before the arena is initialized.

It performs the following actions:

  • Nullifies the memory buffer and resets size/offset tracking.
  • Clears the marker stack and parent reference.
  • Sets the default grow callback and debug error handler.
  • Clears all debug metadata and hook pointers.
  • Resets all internal statistics via arena_stats_reset.
  • Initializes atomic flags like owns_buffer, can_grow, and is_destroying.
  • Disables locking if thread safety is enabled.

This function must be called before using or reinitializing the arena. It is designed to avoid stale data and ensure safe concurrent visibility.

Parameters
arenaPointer to the arena to reset.
Note
This function does not free or allocate memory. It only resets metadata.
See also
arena_finish_init
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 530 of file arena_create.c.

531{
532 arena->buffer = NULL;
533 arena->size = 0;
534 arena->offset = 0;
535 arena->marker_stack_top = 0;
536 memset(arena->marker_stack, 0, sizeof(arena->marker_stack));
537 arena->parent_ref = NULL;
538
539 arena->grow_cb = default_grow_cb;
540 arena->debug.error_cb = arena_default_error_callback;
541 arena->debug.error_context = NULL;
542 arena->debug.label = NULL;
543
544 arena->hooks.hook_cb = NULL;
545 arena->hooks.context = NULL;
546
547 arena_stats_reset(&arena->stats);
548
549 atomic_store_explicit(&arena->owns_buffer, false, memory_order_release);
550 atomic_store_explicit(&arena->can_grow, false, memory_order_release);
551 atomic_store_explicit(&arena->is_destroying, false, memory_order_release);
552
553#ifdef ARENA_ENABLE_THREAD_SAFE
554 arena->use_lock = false;
555#endif
556}
void arena_default_error_callback(const char *msg, void *ctx)
Default fallback error callback (prints to stderr).
size_t default_grow_cb(size_t current_size, size_t requested_size)
Default growth policy callback for arena resizing.
void arena_stats_reset(t_arena_stats *stats)
Reset the given statistics structure to zero.

References arena_default_error_callback(), arena_stats_reset(), and default_grow_cb().

◆ arena_set_allocated_buffer()

static bool arena_set_allocated_buffer ( t_arena *  arena,
size_t  size 
)
inlinestatic

#include <arena_create.c>

Allocate and assign a zero-initialized buffer to an arena.

This function is used internally when no user-supplied buffer is provided during arena_init_with_buffer. It dynamically allocates a memory region of the requested size using calloc, stores the resulting buffer and size into the arena, and marks the arena as the owner of the buffer so it can be freed on destruction.

If the memory allocation fails, the function logs a formatted error using arena_report_error and returns false.

Parameters
arenaPointer to the arena receiving the allocated buffer.
sizeNumber of bytes to allocate.
Returns
true if allocation and assignment succeeded, false on failure.
See also
arena_set_or_alloc_buffer
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 682 of file arena_create.c.

683{
684 void* buffer = calloc(1, size);
685 if (!buffer)
686 {
687 arena_report_error(NULL, "arena_init_with_buffer: malloc for %zu bytes failed", size);
688 return false;
689 }
690 arena->buffer = (uint8_t*) buffer;
691 arena->size = size;
692 atomic_store_explicit(&arena->owns_buffer, true, memory_order_release);
693 return true;
694}

References arena_report_error().

◆ arena_set_default_label()

static void arena_set_default_label ( t_arena *  arena,
const char *  fallback 
)
inlinestatic

#include <arena_create.c>

Set a fallback debug label if none is set.

This internal utility ensures that an arena has a human-readable label for debugging and error reporting. If the arena->debug.label is NULL, it assigns the provided fallback label.

Labels are used in logs and diagnostic tools to identify arenas more easily, especially in multi-arena systems or when visualizing memory usage.

This function is used during initialization, after clearing metadata.

Parameters
arenaPointer to the arena structure to label.
fallbackThe default label to assign if no label is already set.
Note
This does not copy the string; it simply sets the pointer. The fallback string must remain valid for the arena’s lifetime.
See also
arena_create
arena_init
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 398 of file arena_create.c.

399{
400 if (!arena->debug.label)
401 arena->debug.label = fallback;
402}

◆ arena_set_or_alloc_buffer()

static bool arena_set_or_alloc_buffer ( t_arena *  arena,
void *  buffer,
size_t  size 
)
inlinestatic

#include <arena_create.c>

Configure an arena's buffer by either assigning a user-provided region or allocating one internally.

This helper determines whether to allocate memory or use an existing buffer based on the parameters:

  • If buffer is NULL and size > 0, it allocates a new zeroed buffer using calloc.
  • Otherwise, it sets the arena's buffer to the provided memory region.

In both cases, it updates the owns_buffer flag accordingly to ensure proper cleanup behavior in arena_destroy(). This function helps unify buffer configuration logic in arena_init_with_buffer, reducing duplication and clarifying intent.

Parameters
arenaPointer to the arena to configure.
bufferPointer to the caller-supplied memory buffer (can be NULL).
sizeSize (in bytes) of the buffer.
Returns
true on success, false if memory allocation failed.
See also
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 750 of file arena_create.c.

751{
752 if (!buffer && size > 0)
753 return arena_set_allocated_buffer(arena, size);
754
755 arena_set_user_buffer(arena, buffer, size);
756 return true;
757}
static void arena_set_user_buffer(t_arena *arena, void *buffer, size_t size)
Assign a user-provided buffer to an arena without taking ownership.
static bool arena_set_allocated_buffer(t_arena *arena, size_t size)
Allocate and assign a zero-initialized buffer to an arena.

References arena_set_allocated_buffer(), and arena_set_user_buffer().

◆ arena_set_user_buffer()

static void arena_set_user_buffer ( t_arena *  arena,
void *  buffer,
size_t  size 
)
inlinestatic

#include <arena_create.c>

Assign a user-provided buffer to an arena without taking ownership.

This function sets up the arena's buffer and size fields using a buffer provided by the caller. It does not allocate or copy memory — it simply stores the pointer and size, and marks the arena as not owning the buffer. This means the buffer will not be freed when the arena is destroyed.

It is typically used when initializing or reinitializing an arena that operates over pre-allocated memory regions, such as stack memory or memory-mapped regions.

Parameters
arenaPointer to the arena being configured.
bufferPointer to the caller-supplied buffer.
sizeSize (in bytes) of the buffer.
See also
arena_set_or_alloc_buffer
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c.

Definition at line 719 of file arena_create.c.

720{
721 arena->buffer = (uint8_t*) buffer;
722 arena->size = size;
723 atomic_store_explicit(&arena->owns_buffer, false, memory_order_release);
724}

◆ arena_update_peak()

void arena_update_peak ( t_arena *  arena)

#include <arena_internal.h>

Update the arena’s peak memory usage if the current usage exceeds it.

Update the peak usage metric of the arena.

Parameters
arenaPointer to the arena to update.
Returns
void

This internal function updates the peak_usage statistic in the arena if the current offset exceeds the previously recorded peak. This metric reflects the highest memory usage observed since the arena was initialized or last reset.

It uses locking to ensure thread-safe updates in concurrent environments.

Parameters
arenaPointer to the arena whose peak usage should be updated.
Note
This function is typically called after a successful allocation or reallocation.
See also
arena_commit_allocation
update_realloc_stats
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/allocation/arena_alloc.c, and /home/toonsa/myProjects/memoryArena/srcs/core/allocation/arena_realloc_last.c.

Definition at line 118 of file arena_internal.c.

119{
120 ARENA_LOCK(arena);
121 if (arena->offset > arena->stats.peak_usage)
122 arena->stats.peak_usage = arena->offset;
123 ARENA_UNLOCK(arena);
124}
#define ARENA_UNLOCK(arena)
#define ARENA_LOCK(arena)
Acquire the mutex lock if thread safety is enabled.

References ARENA_LOCK, and ARENA_UNLOCK.

◆ arena_zero_metadata()

void arena_zero_metadata ( t_arena *  arena)

#include <arena_internal.h>

Zero out and reset all debug/stats metadata associated with the arena.

Reset all metadata fields in an arena to their default values.

Parameters
arenaPointer to the arena to zero.
Returns
void

This function clears all metadata inside a t_arena structure, preparing it for safe reinitialization. It does not free or allocate memory, but resets all fields related to memory layout, statistics, growth policies, debugging, and hooks.

Specifically, it:

  • Sets the buffer pointer, size, and offset to zero.
  • Resets ownership and growth flags atomically.
  • Clears growth callback and parent references.
  • Resets all statistical counters via arena_stats_reset().
  • Clears debug fields including ID, label, and error context.
  • Resets hook-related pointers.

Use this when:

  • Preparing an arena for reuse.
  • Initializing a static or pre-allocated arena.
Parameters
arenaPointer to the t_arena structure to reset.
Note
This does not destroy any allocated memory. It should typically be called before initializing the arena with a new or reused buffer.
See also
arena_stats_reset
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_cleanup.c.

Definition at line 241 of file arena_internal.c.

242{
243 arena->buffer = NULL;
244 arena->size = 0;
245 arena->offset = 0;
246
247 atomic_store_explicit(&arena->owns_buffer, false, memory_order_release);
248 atomic_store_explicit(&arena->can_grow, false, memory_order_release);
249
250 arena->grow_cb = NULL;
251 arena->parent_ref = NULL;
252
253 arena_stats_reset(&arena->stats);
254
255 memset(arena->debug.id, 0, ARENA_ID_LEN);
256 arena->debug.label = NULL;
257 arena->debug.error_cb = NULL;
258 arena->debug.error_context = NULL;
259 arena->debug.subarena_counter = 0;
260
261 arena->hooks.hook_cb = NULL;
262 arena->hooks.context = NULL;
263}
#define ARENA_ID_LEN
Max characters for arena ID strings.
Definition arena_config.h:6

References ARENA_ID_LEN, and arena_stats_reset().

◆ default_grow_cb()

size_t default_grow_cb ( size_t  current_size,
size_t  requested_size 
)

#include <arena_internal.h>

Default growth policy callback for arena resizing.

Default growth strategy for arenas that support dynamic resizing.

Computes the next size for an arena that needs to grow. The result is typically a geometric increase (e.g., 2x rule), optionally adjusted to accommodate the requested size.

Parameters
current_sizeThe current buffer size of the arena.
requested_sizeThe size that triggered the growth.
Returns
A new size value suitable for reallocation.

This function computes a new arena size when a memory allocation request exceeds the current capacity. The growth strategy works as follows:

  • If the current size is 0, it starts with a base size of 64 bytes.
  • It ensures no overflow occurs when adding current_size + requested_size.
  • It then doubles the size repeatedly until the new size is sufficient to satisfy the allocation.
  • If doubling is not enough (due to near SIZE_MAX), it falls back to a minimal sufficient size.

This strategy offers exponential growth (geometric progression) to minimize reallocations and fragmentation.

Parameters
current_sizeCurrent size of the arena in bytes.
requested_sizeAdditional memory needed for the new allocation.
Returns
The new size in bytes, large enough to accommodate the request. Returns SIZE_MAX on overflow.
Note
You can override this behavior by assigning a custom function to arena->grow_cb. For example, use a fixed increment strategy instead of exponential growth if your use case favors more predictable memory sizing or tighter control over memory usage:
arena->grow_cb = [](size_t current, size_t required) {
return current + required + 128; // Fixed buffer with 128-byte padding
};

Reasons to use a custom strategy:

  • You are working in a memory-constrained environment (e.g., embedded systems).
  • You want deterministic memory usage patterns.
  • You have prior knowledge of allocation patterns and want to tune growth granularity.
See also
arena_grow
arena_init_with_buffer
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/arena_create.c, and /home/toonsa/myProjects/memoryArena/srcs/core/arena_resize.c.

Definition at line 78 of file arena_internal.c.

79{
80 size_t new_size = current_size > 0 ? current_size : 64;
81
82 if (requested_size > SIZE_MAX - current_size)
83 return SIZE_MAX;
84
85 const size_t needed = current_size + requested_size;
86
87 while (new_size < needed && new_size <= SIZE_MAX / 2)
88 new_size *= 2;
89
90 if (new_size < needed)
91 new_size = needed;
92
93 return new_size;
94}

◆ next_power_of_two()

static size_t next_power_of_two ( size_t  x)
inlinestatic

#include <arena_math.h>

Return the next power of two greater than or equal to x.

If x is already a power of two, it is returned unchanged. If x is zero, the function returns 1.

This is implemented using bitwise operations for speed and portability.

Parameters
xThe input value.
Returns
The next power of two ≥ x.

Definition at line 116 of file arena_math.h.

117 {
118 if (x == 0)
119 return 1;
120 --x;
121 x |= x >> 1;
122 x |= x >> 2;
123 x |= x >> 4;
124 x |= x >> 8;
125 x |= x >> 16;
126#if SIZE_MAX > UINT32_MAX
127 x |= x >> 32;
128#endif
129 return x + 1;
130 }

◆ would_overflow_mul()

static bool would_overflow_mul ( size_t  a,
size_t  b,
size_t *  result 
)
inlinestatic

#include <arena_math.h>

Perform a checked multiplication of two size_t values.

Computes a * b and stores the result in *result. If the multiplication would overflow SIZE_MAX, the function returns true and does not modify *result.

If the platform supports __builtin_mul_overflow, it will be used for fast hardware-checked overflow detection. Otherwise, a portable fallback is used.

Parameters
aFirst operand.
bSecond operand.
resultOutput pointer to store the product if safe.
Returns
true if the multiplication would overflow, false otherwise.
Note
This function ensures safe allocation size computations in arena logic.
Examples
/home/toonsa/myProjects/memoryArena/srcs/core/allocation/arena_calloc.c.

Definition at line 79 of file arena_math.h.

80 {
81#if defined(__has_builtin)
82#if __has_builtin(__builtin_mul_overflow)
83 return __builtin_mul_overflow(a, b, result);
84#endif
85#endif
86
87 if (a == 0 || b == 0)
88 {
89 *result = 0;
90 return false;
91 }
92 if (a > SIZE_MAX / b)
93 {
94 return true;
95 }
96 *result = a * b;
97 return false;
98 }