Derive-C
Loading...
Searching...
No Matches
math.h
Go to the documentation of this file.
1#pragma once
2
3#include <stdbool.h>
4#include <stdint.h>
5#include <stdlib.h>
6
9
10// JUSTIFY: Macro rather than function
11// - So this can be used in static asserts
12#define DC_MATH_IS_POWER_OF_2(x) ((x) != 0 && ((x) & ((x) - 1)) == 0)
13
14#ifdef __cplusplus
15
16 #include <bit>
17 #include <type_traits>
18
19namespace dc::math {
20
21template <typename T> constexpr unsigned msb_index(T x) noexcept {
22 static_assert(std::is_unsigned_v<T>, "DC_MATH_MSB_INDEX requires an unsigned integer type");
23
24 if (x == 0) {
25 return 0U;
26 }
27
28 constexpr unsigned bits = sizeof(T) * 8U;
29 return bits - 1U - std::countl_zero(x);
30}
31
32} // namespace dc::math
33
34 #define DC_MATH_MSB_INDEX(x) ::dc::math::msb_index(x)
35
36#else /* C */
37
38 #define DC_MATH_MSB_INDEX(x) \
39 ((x) == 0 ? 0 \
40 : _Generic((x), \
41 uint8_t: (7u - __builtin_clz((uint32_t)((x)) << 24)), \
42 uint16_t: (15u - __builtin_clz((uint32_t)((x)) << 16)), \
43 uint32_t: (31u - __builtin_clz((uint32_t)(x))), \
44 uint64_t: (63u - __builtin_clzll((uint64_t)(x)))))
45
46#endif /* __cplusplus */
47
49 if (x == 0)
50 return 1;
51 x--;
52 x |= x >> 1;
53 x |= x >> 2;
54 x |= x >> 4;
55 x |= x >> 8;
56 x |= x >> 16;
57#if SIZE_MAX > 0xFFFFFFFF
58 x |= x >> 32; // For 64-bit platforms
59#endif
60 return x + 1;
61}
62
64 size_t capacity) {
66 return index & (capacity - 1);
67}
68
69static bool DC_INLINE DC_CONST dc_math_is_aligned_pow2_exp(const void* ptr, unsigned exp) {
70 uintptr_t const mask = (1U << exp) - 1;
71 return (((uintptr_t)ptr) & mask) == 0;
72}
#define DC_INLINE
Definition attributes.h:3
#define DC_CONST
Definition attributes.h:4
static size_t capacity()
Definition template.h:66
#define DC_MATH_IS_POWER_OF_2(x)
Definition math.h:12
static DC_INLINE DC_CONST size_t dc_math_next_power_of_2(size_t x)
Definition math.h:48
static bool DC_INLINE DC_CONST dc_math_is_aligned_pow2_exp(const void *ptr, unsigned exp)
Definition math.h:69
static size_t DC_INLINE DC_CONST dc_math_modulus_power_of_2_capacity(size_t index, size_t capacity)
Definition math.h:63
#define DC_ASSUME(expr,...)
Definition panic.h:56