]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/typetraits.h: Add macros that give information about a type
authorAlejandro Colomar <alx@kernel.org>
Fri, 1 Dec 2023 23:16:49 +0000 (00:16 +0100)
committerAlejandro Colomar <alx@kernel.org>
Sat, 29 Jun 2024 18:00:18 +0000 (20:00 +0200)
In the case of is_unsigned() and is_signed(), the natural thing would be
to compare to 0:

#define is_unsigned(x)  (((typeof(x)) -1) > 0)
#define is_signed(x)    (((typeof(x)) -1) < 0)

However, that would trigger -Wtype-limits, so we compare against 1,
which silences that, and does the same job.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/typetraits.h [new file with mode: 0644]

index adcd9fbf9ceb1dac50f6f7188de37ff22165dcfe..b5f601a6b4b4df72f174d513f6175bebafadeb9c 100644 (file)
@@ -164,6 +164,7 @@ libshadow_la_SOURCES = \
        time/day_to_str.c \
        time/day_to_str.h \
        ttytype.c \
+       typetraits.h \
        tz.c \
        ulimit.c \
        user_busy.c \
diff --git a/lib/typetraits.h b/lib/typetraits.h
new file mode 100644 (file)
index 0000000..47bd30d
--- /dev/null
@@ -0,0 +1,46 @@
+// SPDX-FileCopyrightText: 2022-2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#ifndef SHADOW_INCLUDE_LIB_TYPETRAITS_H_
+#define SHADOW_INCLUDE_LIB_TYPETRAITS_H_
+
+
+#include <config.h>
+
+#include "sizeof.h"
+
+
+#define is_unsigned(x)                                                        \
+(                                                                             \
+       (typeof(x)) -1 > 1                                                    \
+)
+
+#define is_signed(x)                                                          \
+(                                                                             \
+       (typeof(x)) -1 < 1                                                    \
+)
+
+
+#define stype_max(T)                                                          \
+(                                                                             \
+       (T) (((((T) 1 << (WIDTHOF(T) - 2)) - 1) << 1) + 1)                    \
+)
+
+#define utype_max(T)                                                          \
+(                                                                             \
+       (T) -1                                                                \
+)
+
+#define type_max(T)                                                           \
+(                                                                             \
+       (T) (is_signed(T) ? stype_max(T) : utype_max(T))                      \
+)
+
+#define type_min(T)                                                           \
+(                                                                             \
+       (T) ~type_max(T)                                                      \
+)
+
+
+#endif  // include guard