aboutsummaryrefslogtreecommitdiff
path: root/utils.h
blob: cb7d795915a8f347d3a667af2a28ca0fe4a1770f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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