Created
October 7, 2016 13:45
-
-
Save Chippiewill/953e0fd06db04e14ce4d0fa537d2b554 to your computer and use it in GitHub Desktop.
Example code for performing fast comparison against string literals in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstring> | |
#include <iostream> | |
#include <string> | |
template <size_t N> | |
bool compare(const char* s, size_t n, const char(&data)[N]) { | |
// Subtract 1 from N to remove null-termination | |
if (n != (N - 1)) { | |
return false; | |
} | |
return std::memcmp(s, data, (N - 1)) == 0; | |
} | |
template <size_t N> | |
bool compare_prefix(const char* s, size_t n, const char(&data)[N]) { | |
// Subtract 1 from N to remove null-termination | |
if (n < (N - 1)) { | |
return false; | |
} | |
return std::memcmp(s, data, (N - 1)) == 0; | |
} | |
template <size_t N> | |
bool compare(const std::string& s, const char(&data)[N]) { | |
return compare(s.c_str(), s.size(), data); | |
} | |
template <size_t N> | |
bool compare_prefix(const std::string& s, const char(&data)[N]) { | |
return compare_prefix(s.c_str(), s.size(), data); | |
} | |
int main(int argc, char** argv) { | |
const std::string input{"failovers some_key"}; | |
if (compare(input, "dcp")) { | |
std::cout << "Called DCP stats\n"; | |
} else if (compare(input, "diskinfo")) { | |
std::cout << "Called diskinfo stats\n"; | |
} else if (compare_prefix(input, "failovers ")) { | |
std::cout << "Called failover prefixed stats\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment