memory_arena
Loading...
Searching...
No Matches
arena_math.h
Go to the documentation of this file.
1
22#ifndef ARENA_MATH_H
23#define ARENA_MATH_H
24
25#include <stdbool.h>
26#include <stddef.h>
27#include <stdint.h>
28
29#ifdef __cplusplus
30extern "C"
31{
32#endif
33
52 static inline size_t align_up(size_t value, size_t alignment)
53 {
54 return (value + alignment - 1) & ~(alignment - 1);
55 }
56
79 static inline bool would_overflow_mul(size_t a, size_t b, size_t* result)
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 }
99
116 static inline size_t next_power_of_two(size_t x)
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 }
131
132#ifdef __cplusplus
133}
134#endif
135
136#endif // ARENA_MATH_H
static bool would_overflow_mul(size_t a, size_t b, size_t *result)
Perform a checked multiplication of two size_t values.
Definition arena_math.h:79
static size_t align_up(size_t value, size_t alignment)
Align a value upwards to the nearest multiple of alignment.
Definition arena_math.h:52
static size_t next_power_of_two(size_t x)
Return the next power of two greater than or equal to x.
Definition arena_math.h:116