diff options
Diffstat (limited to 'utils.h')
-rw-r--r-- | utils.h | 35 |
1 files changed, 35 insertions, 0 deletions
@@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: MIT */ +/** + * utils.h - useful macros for compile-time magic + * + * Inspired by similar macros in the Linux Kernel. + * + * Copyright (c) 2023 - Yaroslav de la Peña Smirnov + */ +#ifndef CWARE_UTILS_H +#define CWARE_UTILS_H + +#include <stddef.h> + +#ifndef static_assert +#define static_assert(exp, msg) _Static_assert(exp, msg) +#endif + +#define same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) + +#define container_of(ptr, T, member) \ + ({ \ + static_assert(same_type(*(ptr), ((T *)0)->member) \ + || same_type(*(ptr), void), \ + "type mismatch in container_of()"); \ + (T *)((void *)(ptr)-offsetof(T, member)); \ + }) + +#define ARRAY_SIZE(arr) \ + ({ \ + static_assert(!same_type((arr), &(arr)[0]), \ + "variable is not an array"); \ + sizeof(arr) / sizeof(*arr); \ + }) + +#endif |