summaryrefslogtreecommitdiff
path: root/lib/libc/stdbit/stdc_trailing_zeros.c
blob: 6213f62cffdb28b26a8ee60a8d21912b32d572a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
 * Copyright (c) 2025 Robert Clausecker <fuz@FreeBSD.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <assert.h>
#include <limits.h>
#include <stdbit.h>

/* Ensure we do not shift 1U out of range. */
static_assert(UCHAR_WIDTH < UINT_WIDTH,
    "stdc_trailing_zeros_uc needs UCHAR_WIDTH < UINT_WIDTH");

unsigned int
stdc_trailing_zeros_uc(unsigned char x)
{
	return (__builtin_ctz(x | 1U << UCHAR_WIDTH));
}

/* Ensure we do not shift 1U out of range. */
static_assert(USHRT_WIDTH < UINT_WIDTH,
    "stdc_trailing_zeros_uc needs USHRT_WIDTH < UINT_WIDTH");

unsigned int
stdc_trailing_zeros_us(unsigned short x)
{
	return (__builtin_ctz(x | 1U << USHRT_WIDTH));
}

unsigned int
stdc_trailing_zeros_ui(unsigned int x)
{
	if (x == 0U)
		return (UINT_WIDTH);

	return (__builtin_ctz(x));
}

unsigned int
stdc_trailing_zeros_ul(unsigned long x)
{
	if (x == 0UL)
		return (ULONG_WIDTH);

	return (__builtin_ctzl(x));
}

unsigned int
stdc_trailing_zeros_ull(unsigned long long x)
{
	if (x == 0ULL)
		return (ULLONG_WIDTH);

	return (__builtin_ctzll(x));
}