Skip to content

Instantly share code, notes, and snippets.

@KoneLinx
Created August 21, 2021 11:31
Show Gist options
  • Save KoneLinx/d3601597248bed423daf1a7cf7bd9533 to your computer and use it in GitHub Desktop.
Save KoneLinx/d3601597248bed423daf1a7cf7bd9533 to your computer and use it in GitHub Desktop.
A simple compile time random number generator for C++. (uses std::rotl (C++20), but can be easily replaced if needed)
constexpr uint32_t hash(uint32_t in)
{
constexpr uint32_t r[]{
0xdf15236c, 0x16d16793, 0x3a697614, 0xe0fe08e4,
0xa3a53275, 0xccc10ff9, 0xb92fae55, 0xecf491de,
0x36e86773, 0x0ed24a6a, 0xd7153d80, 0x84adf386,
0x17110e76, 0x6d411a6a, 0xcbd41fed, 0x4b1d6b30
};
uint32_t out{ in ^ r[in & 0xF] };
out ^= std::rotl(in, 020) ^ r[(in >> 010) & 0xF];
out ^= std::rotl(in, 010) ^ r[(in >> 020) & 0xF];
out ^= std::rotr(in, 010) ^ r[(in >> 030) & 0xF];
return out;
}
template <size_t N>
constexpr uint32_t hash(char const(&str)[N])
{
uint32_t h{};
for (uint32_t i{}; i < N; ++i)
h ^= uint32_t(str[i]) << (i % 4 * 8);
return hash(h);
}
template <size_t N>
constexpr uint32_t constexpr_rand_impl(char const(&file)[N], uint32_t line, uint32_t column = 0x8dc97987)
{
return hash(hash(__TIME__) ^ hash(file) ^ hash(line) ^ hash(column));
}
#define RANDOM constexpr_rand_impl(__FILE__, __LINE__)
void test()
{
constexpr auto r1 = RANDOM;
constexpr auto r2 = RANDOM;
constexpr auto r3 = RANDOM;
constexpr auto r4 = RANDOM;
}
@ReimuNotMoe
Copy link

Hello, would you like to add a license to this code snippet?

@KoneLinx
Copy link
Author

Hello, would you like to add a license to this code snippet?

Thanks for reaching out. I am happy to throw it under public domain since it's just a short snippet. My friend at the time was breaking his head trying to get a random number at compile time and I just quickly threw this together to help him out.

I must say it's been quite a while though and even after a thorough search I cannot for the life of me remember where I got the hash table from. Might have been me generating a random sequence but I don't remember. Other than the hash table I'm pretty sure I threw the rest together on the spot. If in doubt, replace the hash table and xor sequence and you're good. Take note that the random output generated here is not well distributed or collision free. As long as you're fine with any number that is unlikely to be the same twice, feel free to use and modify this snippet however you like. If you would like a beter hash function, replace the top hash fucntion with any other hash function of your choosing.

Public Domain, do as you like. Attribution is appreciated but not necessary. I'll leave this snippet untouched so you can always track back here.

@ReimuNotMoe
Copy link

Thanks! I will definitely add an attribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment