kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

util.h (1147B)


      1 #ifndef KIT_UTIL_H
      2 #define KIT_UTIL_H
      3 
      4 /* Small generic helpers — alignment, min/max, array length, container_of.
      5  *
      6  * Header-only. Intended to be includable from any TU; depends only on
      7  * stddef.h (via core.h) for offsetof.
      8  *
      9  * Naming: short uppercase macros without prefix. The codebase is
     10  * freestanding (-ffreestanding) and core.h pulls in only stddef/stdint/
     11  * setjmp/stdarg, so MIN/MAX collisions with system headers don't occur. */
     12 
     13 #include <stddef.h>
     14 
     15 #include "core/core.h"
     16 
     17 #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))
     18 
     19 #define BIT(n) (1u << (n))
     20 
     21 #define MIN(a, b) ((a) < (b) ? (a) : (b))
     22 #define MAX(a, b) ((a) > (b) ? (a) : (b))
     23 #define CLAMP(x, lo, hi) ((x) < (lo) ? (lo) : (x) > (hi) ? (hi) : (x))
     24 
     25 #define IS_POW2(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))
     26 
     27 /* ALIGN_UP(v, a): round v up to a multiple of a. a must be a power of two.
     28  * Generic over u32/u64/size_t — operand promotion picks the wider type. */
     29 #define ALIGN_UP(v, a) (((v) + ((a) - 1)) & ~((a) - 1))
     30 #define ALIGN_DOWN(v, a) ((v) & ~((a) - 1))
     31 
     32 #define CONTAINER_OF(p, T, m) ((T*)((char*)(p) - offsetof(T, m)))
     33 
     34 #define UNUSED(x) ((void)(x))
     35 
     36 #endif