Skip to content

Instantly share code, notes, and snippets.

@Chippiewill
Created October 7, 2016 13:45
Show Gist options
  • Save Chippiewill/953e0fd06db04e14ce4d0fa537d2b554 to your computer and use it in GitHub Desktop.
Save Chippiewill/953e0fd06db04e14ce4d0fa537d2b554 to your computer and use it in GitHub Desktop.
Example code for performing fast comparison against string literals in C++
#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