Skip to content

Instantly share code, notes, and snippets.

@idispatch
Last active June 8, 2017 15:25
Show Gist options
  • Save idispatch/ddce18a3115c6fb7351d0f79192ede23 to your computer and use it in GitHub Desktop.
Save idispatch/ddce18a3115c6fb7351d0f79192ede23 to your computer and use it in GitHub Desktop.
#include <string>
#include <iostream>
#include <map>
typedef std::map<std::string, std::string> Defines;
bool evaluate(const Defines& defines, std::string *value) {
std::string::reverse_iterator i = value->rbegin();
std::string::iterator e = value->end();
while (i != value->rend()) {
if (*i == '}') {
e = i.base() - 1;
i++;
} else if (*i == '{') {
if (e == value->end()) {
return false;
}
const std::string::iterator b = i.base() -1;
const std::string v(b + 1, e);
const Defines::const_iterator p = defines.find(v);
if (p != defines.end()) {
value->replace(b, e + 1, p->second);
} else {
return false; // or value->erase(b - 1, e);
}
i = value->rbegin();
e = value->end();
} else {
i++;
}
}
return e == value->end();
}
int main()
{
{
Defines d;
std::string s = "hello world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
d["1"] = "my";
d["2"] = "test";
d["3"] = "string";
std::string s = "{1} {2} {3}";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
d["world"] = "1";
d["hello 1"] = "my";
std::string s = "here is {hello {world}} string";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
d["world"] = "this";
std::string s = "here is {world} string";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
d["world"] = "1";
std::string s = "here is {hello {world}} string";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello { world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello } world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello world}";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello world{";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "{hello world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "}hello world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello {{world";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
{
Defines d;
std::string s = "hello world{{";
std::cout << (evaluate(d, &s) ? "pass":"fail") << ": " << s << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment