Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/lib/libc/stdbit/stdc_trailing_ones.c
96290 views
1
/*
2
* Copyright (c) 2025 Robert Clausecker <[email protected]>
3
*
4
* SPDX-License-Identifier: BSD-2-Clause
5
*/
6
7
#include <assert.h>
8
#include <limits.h>
9
#include <stdbit.h>
10
11
/* Avoid triggering undefined behavior if x == ~0. */
12
static_assert(UCHAR_WIDTH < UINT_WIDTH,
13
"stdc_trailing_ones_uc needs UCHAR_WIDTH < UINT_WIDTH");
14
15
unsigned int
16
stdc_trailing_ones_uc(unsigned char x)
17
{
18
return (__builtin_ctz(~x));
19
}
20
21
/* Avoid triggering undefined behavior if x == ~0. */
22
static_assert(USHRT_WIDTH < UINT_WIDTH,
23
"stdc_trailing_ones_uc needs USHRT_WIDTH < UINT_WIDTH");
24
25
unsigned int
26
stdc_trailing_ones_us(unsigned short x)
27
{
28
return (__builtin_ctz(~x));
29
}
30
31
unsigned int
32
stdc_trailing_ones_ui(unsigned int x)
33
{
34
if (x == ~0U)
35
return (UINT_WIDTH);
36
37
return (__builtin_ctz(~x));
38
}
39
40
unsigned int
41
stdc_trailing_ones_ul(unsigned long x)
42
{
43
if (x == ~0UL)
44
return (ULONG_WIDTH);
45
46
return (__builtin_ctzl(~x));
47
}
48
49
unsigned int
50
stdc_trailing_ones_ull(unsigned long long x)
51
{
52
if (x == ~0ULL)
53
return (ULLONG_WIDTH);
54
55
return (__builtin_ctzll(~x));
56
}
57
58