Use compiler-specific functions in Nim

C compilers, like GCC, provide various "builtin" compiler-specific extensions (functions). Sure, using them may be looked down upon, but sometimes they can give you access to hardware-optimized operations that significantly boost performance. You can always provide a slower fallback.

Let's take as an example the operation "find how many bytes a number would take up". I needed this to implement a function that returns a random number in a specific range, using an entropy source that just gives bytes, such as /dev/urandom.


GCC provides a function __builtin_clz:

Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.

For example, the number 00011001 (when talking in 8-bit context) has 3 leading 0-bits, so it takes up 8-3 == 5 bits. Let's use __builtin_clzll to do the same thing for a 64 bit number, then just use the "bit size" to get the "byte size".


Now let's do this for Visual C, using _BitScanReverse. Credits to this StackOverflow answer.

Untested code:


And the fallback...


A list of compilers can be found here.

Comments powered by Disqus