Derive-C
Loading...
Searching...
No Matches
math.h
Go to the documentation of this file.
1#pragma once
2
3#include <stdint.h>
4#include <stdlib.h>
5
7
8static INLINE CONST size_t next_power_of_2(size_t x) {
9 if (x == 0)
10 return 1;
11 x--;
12 x |= x >> 1;
13 x |= x >> 2;
14 x |= x >> 4;
15 x |= x >> 8;
16 x |= x >> 16;
17#if SIZE_MAX > 0xFFFFFFFF
18 x |= x >> 32; // For 64-bit platforms
19#endif
20 return x + 1;
21}
22
23static bool INLINE CONST is_power_of_2(size_t x) { return x != 0 && (x & (x - 1)) == 0; }
24
25static size_t INLINE CONST modulus_power_of_2_capacity(size_t index, size_t capacity) {
26 ASSUME(is_power_of_2(capacity));
27 // NOTE: If we know capacity is a power of 2, we can reduce the cost of 'index + 1 % capacity'
28 return index & (capacity - 1);
29}
30
31static bool INLINE CONST is_aligned_pow2_exp(const void* ptr, unsigned exp) {
32 uintptr_t const mask = (1U << exp) - 1;
33 return (((uintptr_t)ptr) & mask) == 0;
34}
#define CONST
Definition macros.h:12
#define INLINE
Definition macros.h:8
#define ASSUME(expr,...)
Definition macros.h:62
static bool INLINE CONST is_aligned_pow2_exp(const void *ptr, unsigned exp)
Definition math.h:31
static INLINE CONST size_t next_power_of_2(size_t x)
Definition math.h:8
static size_t INLINE CONST modulus_power_of_2_capacity(size_t index, size_t capacity)
Definition math.h:25
static bool INLINE CONST is_power_of_2(size_t x)
Definition math.h:23