xref: /freebsd/lib/libc/stdbit/stdc_trailing_zeros.c (revision 6296500a85c8474e3ff3fe2f8e4a9d56dd0acd64)
1 /*
2  * Copyright (c) 2025 Robert Clausecker <fuz@FreeBSD.org>
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6 
7 #include <assert.h>
8 #include <limits.h>
9 #include <stdbit.h>
10 
11 /* Ensure we do not shift 1U out of range. */
12 static_assert(UCHAR_WIDTH < UINT_WIDTH,
13     "stdc_trailing_zeros_uc needs UCHAR_WIDTH < UINT_WIDTH");
14 
15 unsigned int
stdc_trailing_zeros_uc(unsigned char x)16 stdc_trailing_zeros_uc(unsigned char x)
17 {
18 	return (__builtin_ctz(x | 1U << UCHAR_WIDTH));
19 }
20 
21 /* Ensure we do not shift 1U out of range. */
22 static_assert(USHRT_WIDTH < UINT_WIDTH,
23     "stdc_trailing_zeros_uc needs USHRT_WIDTH < UINT_WIDTH");
24 
25 unsigned int
stdc_trailing_zeros_us(unsigned short x)26 stdc_trailing_zeros_us(unsigned short x)
27 {
28 	return (__builtin_ctz(x | 1U << USHRT_WIDTH));
29 }
30 
31 unsigned int
stdc_trailing_zeros_ui(unsigned int x)32 stdc_trailing_zeros_ui(unsigned int x)
33 {
34 	if (x == 0U)
35 		return (UINT_WIDTH);
36 
37 	return (__builtin_ctz(x));
38 }
39 
40 unsigned int
stdc_trailing_zeros_ul(unsigned long x)41 stdc_trailing_zeros_ul(unsigned long x)
42 {
43 	if (x == 0UL)
44 		return (ULONG_WIDTH);
45 
46 	return (__builtin_ctzl(x));
47 }
48 
49 unsigned int
stdc_trailing_zeros_ull(unsigned long long x)50 stdc_trailing_zeros_ull(unsigned long long x)
51 {
52 	if (x == 0ULL)
53 		return (ULLONG_WIDTH);
54 
55 	return (__builtin_ctzll(x));
56 }
57