Skip to content

Instantly share code, notes, and snippets.

@ryuukk
Created November 26, 2021 04:10
Show Gist options
  • Save ryuukk/a9692100bf00f38422dfbb54c672bbd6 to your computer and use it in GitHub Desktop.
Save ryuukk/a9692100bf00f38422dfbb54c672bbd6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int main()
{
for(unsigned int i = 0; i< 1024; i++)
{
unsigned int size = i * 4;
unsigned int bucket = (__builtin_clz(size - 1) ^ 31) + 1;
printf("%u %u\n", size, bucket);
}
return 0;
}
import core.stdc.stdio;
extern(C) int main()
{
for(uint i = 0; i< 1024; i++)
{
uint size = i * 4;
uint bucket = (bsr(size - 1) ^ 31) + 1;
printf("%u %u\n", size, bucket);
}
return 0;
}
int bsr(uint v) pure
{
pragma(inline, false); // so intrinsic detection will work
return softBsr!uint(v);
}
/// ditto
int bsr(ulong v) pure
{
static if (size_t.sizeof == ulong.sizeof) // 64 bit code gen
{
pragma(inline, false); // so intrinsic detection will work
return softBsr!ulong(v);
}
else
{
/* intrinsic not available for 32 bit code,
* make do with 32 bit bsr
*/
const sv = Split64(v);
return (sv.hi == 0)?
bsr(sv.lo) :
bsr(sv.hi) + 32;
}
}
private alias softBsf(N) = softScan!(N, true);
private alias softBsr(N) = softScan!(N, false);
/* Shared software fallback implementation for bit scan foward and reverse.
If forward is true, bsf is computed (the index of the first set bit).
If forward is false, bsr is computed (the index of the last set bit).
-1 is returned if no bits are set (v == 0).
*/
private int softScan(N, bool forward)(N v) pure
if (is(N == uint) || is(N == ulong))
{
// bsf() and bsr() are officially undefined for v == 0.
if (!v)
return -1;
// This is essentially an unrolled binary search:
enum mask(ulong lo) = forward ? cast(N) lo : cast(N)~lo;
enum inc(int up) = forward ? up : -up;
N x;
int ret;
static if (is(N == ulong))
{
x = v & mask!0x0000_0000_FFFF_FFFFL;
if (x)
{
v = x;
ret = forward ? 0 : 63;
}
else
ret = forward ? 32 : 31;
x = v & mask!0x0000_FFFF_0000_FFFFL;
if (x)
v = x;
else
ret += inc!16;
}
else static if (is(N == uint))
{
x = v & mask!0x0000_FFFF;
if (x)
{
v = x;
ret = forward ? 0 : 31;
}
else
ret = forward ? 16 : 15;
}
else
static assert(false);
x = v & mask!0x00FF_00FF_00FF_00FFL;
if (x)
v = x;
else
ret += inc!8;
x = v & mask!0x0F0F_0F0F_0F0F_0F0FL;
if (x)
v = x;
else
ret += inc!4;
x = v & mask!0x3333_3333_3333_3333L;
if (x)
v = x;
else
ret += inc!2;
x = v & mask!0x5555_5555_5555_5555L;
if (!x)
ret += inc!1;
return ret;
}
private union Split64
{
ulong u64;
struct
{
version (LittleEndian)
{
uint lo;
uint hi;
}
else
{
uint hi;
uint lo;
}
}
pragma(inline, true)
this(ulong u64) @safe pure nothrow @nogc
{
if (__ctfe)
{
lo = cast(uint) u64;
hi = cast(uint) (u64 >>> 32);
}
else
this.u64 = u64;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment