Add _glfw_ffs returning 1-based index of lsb set to one

This commit is contained in:
Florian Albrechtskirchinger 2022-06-16 15:06:31 +02:00
parent 8031534c38
commit 519ee68876
No known key found for this signature in database
GPG Key ID: 19618CE9B2D4BE6D
2 changed files with 36 additions and 0 deletions

View File

@ -266,6 +266,41 @@ float _glfw_fmaxf(float a, float b)
return b; return b;
} }
int _glfw_ffs(int i)
{
#if defined(__GNUC__) || defined(__clang__)
return __builtin_ffs(i);
#elif defined(_MSC_VER)
unsigned long n, u = i;
return _BitScanForward(&n, u) ? n + 1 : 0;
#else
// https://en.wikipedia.org/wiki/Find_first_set#CTZ
unsigned int u = i;
int n = 1;
if (!u) return 0;
if (!(u & 0x0000FFFF)) {
n += 16;
u >>= 16;
}
if (!(u & 0x000000FF)) {
n += 8;
u >>= 8;
}
if (!(u & 0x0000000F)) {
n += 4;
u >>= 4;
}
if (!(u & 0x00000003)) {
n += 2;
u >>= 2;
}
if (!(u & 0x00000001)) {
n += 1;
}
return n;
#endif
}
void* _glfw_calloc(size_t count, size_t size) void* _glfw_calloc(size_t count, size_t size)
{ {
if (count && size) if (count && size)

View File

@ -1015,6 +1015,7 @@ int _glfw_min(int a, int b);
int _glfw_max(int a, int b); int _glfw_max(int a, int b);
float _glfw_fminf(float a, float b); float _glfw_fminf(float a, float b);
float _glfw_fmaxf(float a, float b); float _glfw_fmaxf(float a, float b);
int _glfw_ffs(int i);
void* _glfw_calloc(size_t count, size_t size); void* _glfw_calloc(size_t count, size_t size);
void* _glfw_realloc(void* pointer, size_t size); void* _glfw_realloc(void* pointer, size_t size);