/src/sudo/lib/util/roundup.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * SPDX-License-Identifier: ISC |
3 | | * |
4 | | * Copyright (c) 2019-2020 Todd C. Miller <Todd.Miller@sudo.ws> |
5 | | * |
6 | | * Permission to use, copy, modify, and distribute this software for any |
7 | | * purpose with or without fee is hereby granted, provided that the above |
8 | | * copyright notice and this permission notice appear in all copies. |
9 | | * |
10 | | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
11 | | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
12 | | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
13 | | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
14 | | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
15 | | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
16 | | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
17 | | */ |
18 | | |
19 | | /* |
20 | | * This is an open source non-commercial project. Dear PVS-Studio, please check it. |
21 | | * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com |
22 | | */ |
23 | | |
24 | | #include <config.h> |
25 | | |
26 | | #include <sudo_compat.h> |
27 | | #include <sudo_debug.h> |
28 | | #include <sudo_util.h> |
29 | | |
30 | | /* |
31 | | * Round 32-bit unsigned length to the next highest power of two. |
32 | | * Always returns at least 64. |
33 | | */ |
34 | | unsigned int |
35 | | sudo_pow2_roundup_v1(unsigned int len) |
36 | 0 | { |
37 | 0 | if (len < 64) |
38 | 0 | return 64; |
39 | | |
40 | 0 | #ifdef HAVE___BUILTIN_CLZ |
41 | 0 | return 1U << (32 - __builtin_clz(len - 1)); |
42 | | #else |
43 | | len--; |
44 | | len |= len >> 1; |
45 | | len |= len >> 2; |
46 | | len |= len >> 4; |
47 | | len |= len >> 8; |
48 | | len |= len >> 16; |
49 | | len++; |
50 | | return len; |
51 | | #endif |
52 | 0 | } |
53 | | |
54 | | /* |
55 | | * Round a size_t length to the next highest power of two. |
56 | | * Always returns at least 64. |
57 | | */ |
58 | | size_t |
59 | | sudo_pow2_roundup_v2(size_t len) |
60 | 25.6k | { |
61 | 25.6k | if (len < 64) |
62 | 0 | return 64; |
63 | | |
64 | 25.6k | #if defined(__LP64__) && defined(HAVE___BUILTIN_CLZL) |
65 | 25.6k | return 1UL << (64 - __builtin_clzl(len - 1)); |
66 | | #elif !defined(__LP64__) && defined(HAVE___BUILTIN_CLZ) |
67 | | return 1U << (32 - __builtin_clz(len - 1)); |
68 | | #else |
69 | | len--; |
70 | | len |= len >> 1; |
71 | | len |= len >> 2; |
72 | | len |= len >> 4; |
73 | | len |= len >> 8; |
74 | | len |= len >> 16; |
75 | | # ifdef __LP64__ |
76 | | len |= len >> 32; |
77 | | # endif |
78 | | len++; |
79 | | return len; |
80 | | #endif |
81 | 25.6k | } |