and i want to execute a function corresponding to certain strings (in an optimized way):
bluetooth => functionA()
boo => functionB()
boots => functionC()
coffee => functionA()
so here is my function:
void parse_and_execute(char* input) {
if (input[0] == 'b') {
if (input[1] == 'l') {
if (std::strcmp(input + 2, "uetooth") == 0) {
functionA();
} else {
defaultFunction();
}
} else if (input[1] == 'o' && input[2] == 'o') {
if (input[3] == '\0') {
functionB();
} else if (std::strcmp(input + 3, "bs") == 0) {
functionC();
} else {
defaultFunction();
}
} else {
defaultFunction();
}
} else if (input[0] == 'e') {
if (std::strcmp(input + 1, "ffoc") == 0) {
functionA();
} else {
defaultFunction();
}
} else {
defaultFunction();
}
}
but its not very comfortable to write, i want to lay what string corresponds to what function in a flat manner.
1 idea that i had that DID NOT work was this:
constexpr uint32_t hashString(std::string_view str) {
uint32_t hash = 2166136261u;
for (char c : str) {
hash ^= static_cast<uint32_t>(c);
hash *= 16777619u;
}
return hash;
}
void execute(char* input) {
const uint32_t hash = hashString(input);
switch (hash) {
case hashString("bluetooth"):
functionA();
break;
case hashString("boo"):
functionB();
break;
case hashString("boots"):
functionC();
break;
case hashString("coffee"):
functionA();
break;
default:
defaultFunction();
break;
}
}
i thought i could get a hash at compile-time and input at runtime, but for this to work, we need input to be constexpr which doesn't work. i need it to be available at runtime