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