From: Alejandro Colomar Date: Sun, 7 Jan 2024 00:00:45 +0000 (+0100) Subject: lib/cast.h: const_cast(): Add macro for dropping 'const' X-Git-Tag: 4.15.0-rc1~23 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=e9fc8fc7ef3ed69fcccc4eef0d13f193a3bde7cc;p=thirdparty%2Fshadow.git 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 --- 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