summaryrefslogtreecommitdiffhomepage
path: root/src/nxt_unit_bit.h
blob: 6b43b7c04a90e9ecc88d1cb4c7733da91eee5708 (plain) (blame)
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
57
58
59
60
61
62
63
64
/*
 * Copyright (C) 2022-2023, Alejandro Colomar <alx@kernel.org>
 * Copyright (C) NGINX, Inc.
 */

#ifndef _NXT_UNIT_BIT_H_INCLUDED_
#define _NXT_UNIT_BIT_H_INCLUDED_


#include <limits.h>


/* C23 <stdbit.h> stuff */
nxt_inline unsigned long nxt_bit_ceil_ul(unsigned long x);
nxt_inline unsigned long nxt_bit_ceil_wrap_ul(unsigned long x);
nxt_inline int nxt_bit_width_ul(unsigned long x);
nxt_inline int nxt_leading_zeros_ul(unsigned long x);
nxt_inline int nxt_trailing_zeros_ul(unsigned long x);


nxt_inline unsigned long
nxt_bit_ceil_ul(unsigned long x)
{
    return 1 + (ULONG_MAX >> nxt_leading_zeros_ul(x));
}


nxt_inline unsigned long
nxt_bit_ceil_wrap_ul(unsigned long x)
{
    return (x == 0) ? 0 : nxt_bit_ceil_ul(x);
}


nxt_inline int
nxt_bit_width_ul(unsigned long x)
{
    return (x == 0) ? 0 : nxt_trailing_zeros_ul(nxt_bit_ceil_ul(x));
}


nxt_inline int
nxt_leading_zeros_ul(unsigned long x)
{
    if (x == 0) {
        return sizeof(unsigned long) * CHAR_BIT;
    }

    return __builtin_clzl(x);
}


nxt_inline int
nxt_trailing_zeros_ul(unsigned long x)
{
    if (x == 0) {
        return sizeof(unsigned long) * CHAR_BIT;
    }

    return __builtin_ctzl(x);
}


#endif /* _NXT_UNIT_BIT_H_INCLUDED_ */