Skip to content

Instantly share code, notes, and snippets.

@randombit
Last active October 9, 2016 17:10
Show Gist options
  • Save randombit/1a85dcb32ab4b3f369d2848c784bc759 to your computer and use it in GitHub Desktop.
Save randombit/1a85dcb32ab4b3f369d2848c784bc759 to your computer and use it in GitHub Desktop.
/*
Compile time string switch
Requires C++14 constexpr
*/
#include <cstdint>
#include <cstdio>
#if 0
// C++14 version
// Collisions are fine because they are detected at compile time ;)
constexpr uint32_t cstr_hash(const char* s)
{
uint32_t V0 = 0, V1 = 0;
// Basic sponge hash
for(size_t i = 0; s[i]; ++i)
{
V0 ^= s[i];
for(size_t r = 0; r != 8; ++r)
{
V1 += V0;
V1 = (V1 << 13) | (V1 >> 19);
V1 ^= r;
V0 += V1;
V0 = (V0 << 13) | (V0 >> 19);
}
}
return V0 + V1;
}
#else
// C++11 much less elegant hash but it works
constexpr uint64_t cstr_hash_perm(uint64_t V, uint64_t R)
{
return (R == 0) ? V :
cstr_hash_perm(((V^R) << 16) + (V >> 32) + ((V & 0xFFFFFFFF) * (R + 7)), R - 1);
}
constexpr uint64_t cstr_hash_core(uint64_t V, const char* s)
{
return (*s == 0) ? V : cstr_hash_core(cstr_hash_perm(V ^ static_cast<uint8_t>(*s), 4), s+1);
}
constexpr uint32_t cstr_hash(const char* s)
{
return cstr_hash_core(0xDEADBEEFCAFE000F, s);
}
#endif
#include <iostream>
#include <string>
#include <map>
int main(int argc, char* argv[])
{
/*
Perl for literals:
while(<>) { if(/.*"(.*)".*/) { print $1, "\n"; } }
*/
/*
std::map<uint32_t, std::string> vals;
while(std::cin.good())
{
std::string line;
std::getline(std::cin, line);
uint32_t h = cstr_hash(line.c_str());
if(vals.count(h))
{
if(vals[h] != line)
{
std::cout << "Collision on " << line << " " << vals[h] << " = " << h << "\n";
return 1;
}
}
vals[h] = line;
}
for(auto&& x : vals)
printf("H(%s) = %08X\n", x.second.c_str(), x.first);
*/
const std::string x = "RSA";
switch(cstr_hash(argv[1]))
{
case cstr_hash("RSA"):
printf("switch RSA\n");
break;
case cstr_hash("DSA"):
printf("switch DSA\n");
break;
case cstr_hash("ECDSA"):
printf("switch ECDSA\n");
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment