From e9fc8fc7ef3ed69fcccc4eef0d13f193a3bde7cc Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Sun, 7 Jan 2024 01:00:45 +0100 Subject: [PATCH] lib/cast.h: const_cast(): Add macro for dropping 'const' Uses of this macro indicate a code smell, but in some cases, libc functions require breaking const correctness. Use this macro to wrap casts in such cases, so that we limit the danger of the cast. It only permits discarding const. Discarding any other qualifiers, or doing other type changes should result in a compile-time error. Link: Signed-off-by: Alejandro Colomar --- lib/Makefile.am | 1 + lib/cast.h | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 lib/cast.h diff --git a/lib/Makefile.am b/lib/Makefile.am index 0254977bc..b5de79c57 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -37,6 +37,7 @@ libshadow_la_SOURCES = \ basename.c \ bit.c \ bit.h \ + cast.h \ chkname.c \ chkname.h \ chowndir.c \ diff --git a/lib/cast.h b/lib/cast.h new file mode 100644 index 000000000..9229528d0 --- /dev/null +++ b/lib/cast.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2022-2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_CAST_H_ +#define SHADOW_INCLUDE_LIB_CAST_H_ + + +#include + +#include "must_be.h" + + +#define const_cast(T, p) \ +({ \ + static_assert(is_same_type(typeof(&*(p)), const T), ""); \ + (T) (p); \ +}) + + +#endif // include guard -- 2.47.2