From cb1a40859029f33184355475e51fec95afb79a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yaroslav=20de=20la=20Pe=C3=B1a=20Smirnov?= Date: Sat, 22 Jul 2023 03:03:09 +0300 Subject: init Just some C wares; hmap, list, optional, unit tests. --- utils.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 utils.h (limited to 'utils.h') diff --git a/utils.h b/utils.h new file mode 100644 index 0000000..cb7d795 --- /dev/null +++ b/utils.h @@ -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 + +#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 -- cgit v1.2.3