aboutsummaryrefslogtreecommitdiff
path: root/lib/libc/stdbit/stdc_leading_zeros.c
diff options
context:
space:
mode:
authorRobert Clausecker <fuz@FreeBSD.org>2025-11-18 17:32:53 +0000
committerRobert Clausecker <fuz@FreeBSD.org>2026-01-01 20:51:52 +0000
commit275c11b7ccffffb8faf31fb0fb98e99ea5b413da (patch)
tree39f4419eb06133ca36f70bade4a26d89564b97f7 /lib/libc/stdbit/stdc_leading_zeros.c
parent325b327ff7d7ece7646058c4d42f087c026c9d08 (diff)
libc: implement C23 <stdbit.h> functions
This new header complies with ISO/IEC 9899:2024 (C23). Contrary to glibc, we do not provide inline definitions in <stdbit.h> as we expect our system compiler to soon recognise these as builtins anyway. Relnotes: yes MFC after: 1 month Reviewed by: adrian Approved by: markj (mentor) Differential Revision: https://reviews.freebsd.org/D53657 (cherry picked from commit 6296500a85c8474e3ff3fe2f8e4a9d56dd0acd64)
Diffstat (limited to 'lib/libc/stdbit/stdc_leading_zeros.c')
-rw-r--r--lib/libc/stdbit/stdc_leading_zeros.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/lib/libc/stdbit/stdc_leading_zeros.c b/lib/libc/stdbit/stdc_leading_zeros.c
new file mode 100644
index 000000000000..2fdf64ec93d4
--- /dev/null
+++ b/lib/libc/stdbit/stdc_leading_zeros.c
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2025 Robert Clausecker <fuz@FreeBSD.org>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <assert.h>
+#include <limits.h>
+#include <stdbit.h>
+
+/* Offset must be greater than zero. */
+static_assert(UCHAR_WIDTH < UINT_WIDTH,
+ "stdc_leading_zeros_uc needs UCHAR_WIDTH < UINT_WIDTH");
+
+unsigned int
+stdc_leading_zeros_uc(unsigned char x)
+{
+ const int offset = UINT_WIDTH - UCHAR_WIDTH;
+
+ return (__builtin_clz((x << offset) + (1U << (offset - 1))));
+}
+
+/* Offset must be greater than zero. */
+static_assert(USHRT_WIDTH < UINT_WIDTH,
+ "stdc_leading_zeros_us needs USHRT_WIDTH < UINT_WIDTH");
+
+unsigned int
+stdc_leading_zeros_us(unsigned short x)
+{
+ const int offset = UINT_WIDTH - USHRT_WIDTH;
+
+ return (__builtin_clz((x << offset) + (1U << (offset - 1))));
+}
+
+unsigned int
+stdc_leading_zeros_ui(unsigned int x)
+{
+ if (x == 0)
+ return (UINT_WIDTH);
+
+ return (__builtin_clz(x));
+}
+
+unsigned int
+stdc_leading_zeros_ul(unsigned long x)
+{
+ if (x == 0)
+ return (ULONG_WIDTH);
+
+ return (__builtin_clzl(x));
+}
+
+unsigned int
+stdc_leading_zeros_ull(unsigned long long x)
+{
+ if (x == 0)
+ return (ULLONG_WIDTH);
+
+ return (__builtin_clzll(x));
+}