]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/cast.h: const_cast(): Add macro for dropping 'const'
authorAlejandro Colomar <alx@kernel.org>
Sun, 7 Jan 2024 00:00:45 +0000 (01:00 +0100)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 26 Jan 2024 08:40:10 +0000 (09:40 +0100)
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: <https://software.codidact.com/posts/286575/287345#answer-287345>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/cast.h [new file with mode: 0644]

index 0254977bc2fc8f6f565530f4baad63d18b6057f3..b5de79c57e817001b5bf708f99a4e8917de518c1 100644 (file)
@@ -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 (file)
index 0000000..9229528
--- /dev/null
@@ -0,0 +1,21 @@
+// SPDX-FileCopyrightText: 2022-2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#ifndef SHADOW_INCLUDE_LIB_CAST_H_
+#define SHADOW_INCLUDE_LIB_CAST_H_
+
+
+#include <config.h>
+
+#include "must_be.h"
+
+
+#define const_cast(T, p)                                                      \
+({                                                                            \
+       static_assert(is_same_type(typeof(&*(p)), const T), "");              \
+       (T) (p);                                                              \
+})
+
+
+#endif  // include guard