]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
shared: introduce uadd32_overflow() helper
authorEmil Velikov <emil.l.velikov@gmail.com>
Mon, 30 Sep 2024 20:06:14 +0000 (21:06 +0100)
committerLucas De Marchi <lucas.de.marchi@gmail.com>
Tue, 15 Oct 2024 17:35:38 +0000 (12:35 -0500)
We'll use it in the upcoming size_t variant.

Signed-off-by: Emil Velikov <emil.l.velikov@gmail.com>
Link: https://github.com/kmod-project/kmod/pull/169
Signed-off-by: Lucas De Marchi <lucas.de.marchi@gmail.com>
meson.build
shared/util.h
testsuite/test-util.c

index 1c87fe0ed02ad8b8c11198bab87a7614eeccb426..eb5cfadd76271db350cec5b8783c8cd066d84165 100644 (file)
@@ -49,6 +49,7 @@ endforeach
 _builtins = [
   ['__builtin_clz', '0', true],
   ['__builtin_types_compatible_p', 'int, int', true],
+  ['__builtin_uadd_overflow', '0U, 0U, (void*)0', false],
   ['__builtin_uaddl_overflow', '0UL, 0UL, (void*)0', false],
   ['__builtin_uaddll_overflow', '0ULL, 0ULL, (void*)0', false],
 ]
index 6fa4bf43c5cce5eb3500ca63201cbd385944a582..87c7279611e06ab8d744bd8b3c0bfed5708c55ce 100644 (file)
@@ -92,6 +92,16 @@ static inline void freep(void *p)
 }
 #define _cleanup_free_ _cleanup_(freep)
 
+static inline bool uadd32_overflow(uint32_t a, uint32_t b, uint32_t *res)
+{
+#if (HAVE___BUILTIN_UADD_OVERFLOW && __SIZEOF_INT__ == 4)
+       return __builtin_uadd_overflow(a, b, res);
+#else
+       *res = a + b;
+       return UINT32_MAX - a < b;
+#endif
+}
+
 static inline bool uadd64_overflow(uint64_t a, uint64_t b, uint64_t *res)
 {
 #if (HAVE___BUILTIN_UADDL_OVERFLOW && __SIZEOF_LONG__ == 8)
index ce246d3982563041e7e61b35c6c74381adbc6391..1f968606eecdf57d350eb8c5244b93341cce5f9d 100644 (file)
@@ -191,6 +191,23 @@ DEFINE_TEST(test_write_str_safe,
                },
        });
 
+static int test_uadd32_overflow(const struct test *t)
+{
+       uint32_t res;
+       bool overflow;
+
+       overflow = uadd32_overflow(UINT32_MAX - 1, 1, &res);
+       assert_return(!overflow, EXIT_FAILURE);
+       assert_return(res == UINT32_MAX, EXIT_FAILURE);
+
+       overflow = uadd32_overflow(UINT32_MAX, 1, &res);
+       assert_return(overflow, EXIT_FAILURE);
+
+       return EXIT_SUCCESS;
+}
+DEFINE_TEST(test_uadd32_overflow,
+           .description = "check implementation of uadd32_overflow()")
+
 static int test_uadd64_overflow(const struct test *t)
 {
        uint64_t res;