Skip to content

Instantly share code, notes, and snippets.

@max-dark
Last active June 2, 2016 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-dark/4ec52ed55b225e52a7ca125b72640dc0 to your computer and use it in GitHub Desktop.
Save max-dark/4ec52ed55b225e52a7ca125b72640dc0 to your computer and use it in GitHub Desktop.
switch by string
#include <iostream>
#include <locale>
#include <string>
#include <cstdint>
#include <limits>
static_assert(sizeof(char) == sizeof(uint8_t), "char != 8 bit");
constexpr uint64_t make_cs(const char str[], std::size_t cnt, std::size_t n) noexcept {
return (
(n < cnt) ?
static_cast<uint64_t>(str[n]) << n*8
: uint64_t(0)
);
using test_type = decltype(static_cast<uint64_t>(str[n]) << n*8);
using result_type = decltype((n < cnt ? static_cast<uint64_t>(str[n]) << n*8 : uint64_t(0)));
static_assert(std::is_unsigned<
test_type
>::value, "(str[n]) << n*8 != uint");
static_assert(std::is_same<
test_type,
uint64_t
>::value, "(str[n]) << n*8 != uint64");
static_assert(std::is_unsigned<
result_type
>::value, "result_type != uint");
static_assert(std::is_same<
result_type,
uint64_t
>::value, "result_type != uint64");
}
constexpr uint64_t make_cs(const char str[], std::size_t cnt) noexcept {
return (
(str == nullptr) ? // if () {
uint64_t( 0 )
:( // } else { pack string to uint64_t
make_cs(str, cnt, 0) |
make_cs(str, cnt, 1) |
make_cs(str, cnt, 2) |
make_cs(str, cnt, 3) |
make_cs(str, cnt, 4) |
make_cs(str, cnt, 5) |
make_cs(str, cnt, 6) |
make_cs(str, cnt, 7)
)
);
using result_type = decltype(
(str == nullptr) ? uint64_t( 0 ):(make_cs(str, cnt, 0) | make_cs(str, cnt, 1))
);
static_assert(std::is_unsigned<
result_type
>::value, "result_type != uint");
static_assert(std::is_same<
result_type,
uint64_t
>::value, "result_type != uint64");
}
uint64_t make_cs(const std::string& str) noexcept {
return make_cs(str.c_str(), str.length());
}
constexpr uint64_t operator "" _cs(const char* str, std::size_t cnt) noexcept {
return make_cs(str, cnt);
}
int main () {
std::string cmd;
bool run = true;
while (run and (std::cin >> cmd)) {
switch (make_cs(cmd)) {
case "quit"_cs:
case "exit"_cs:
run = false;
std::cerr << "bye" << std::endl;
break;
case "begin"_cs:
std::cout << "{" << std::endl;
break;
case "end"_cs:
std::cout << "}" << std::endl;
break;
case "<>"_cs:
std::cout << " != ";
break;
case ":="_cs:
std::cout << " = ";
break;
case "="_cs:
std::cout << " == ";
break;
case "coolname"_cs: // в case учитывается только 8 первых символов
std::cerr << "is cool" << std::endl; break;
//case "coolname_is_same"_cs: // err: дубль
// std::cout << "// empty line" << std::endl; break;
case ""_cs:
std::cout << "// empty line" << std::endl;
break;
default:
std::cerr << "echo: " << cmd << std::endl;
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment