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 /* 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 stdc_trailing_ones_uc(unsigned char x)16stdc_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 stdc_trailing_ones_us(unsigned short x)26stdc_trailing_ones_us(unsigned short x) 27 { 28 return (__builtin_ctz(~x)); 29 } 30 31 unsigned int stdc_trailing_ones_ui(unsigned int x)32stdc_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 stdc_trailing_ones_ul(unsigned long x)41stdc_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 stdc_trailing_ones_ull(unsigned long long x)50stdc_trailing_ones_ull(unsigned long long x) 51 { 52 if (x == ~0ULL) 53 return (ULLONG_WIDTH); 54 55 return (__builtin_ctzll(~x)); 56 } 57