Skip to content

Instantly share code, notes, and snippets.

@jimregan
Created November 16, 2015 11:29
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 jimregan/36dd36acf01f0c7a6a17 to your computer and use it in GitHub Desktop.
Save jimregan/36dd36acf01f0c7a6a17 to your computer and use it in GitHub Desktop.
test escapes
#include <iostream>
#include <string>
#include <map>
#include <cwchar>
#include <cstring>
using namespace std;
struct WS
{
bool operator()(wstring const &s1, wstring const &s2) const
{
return wcscmp(s1.c_str(), s2.c_str()) < 0;
}
};
wstring
escape_string(wstring const &s)
{
wstring out = L"";
for(int i = 0, lim = s.size(); i != lim; i++)
{
if(s[i] == L'\\' || s[i] == L'{' || s[i] == L'}')
{
out += L'\\';
}
out += s[i];
}
return out;
}
wstring
fill_template(wstring const &s, map<wstring, wstring, Ltstr> &m)
{
wstring out = L"";
wstring tmp = L"";
bool writing = true;
for(int i = 0, lim = s.size(); i != lim; i++)
{
if(writing)
{
if(s[i] == L'\\')
{
out += s[++i];
}
else if(s[i] == L'{')
{
writing = false;
}
else
{
out += s[i];
}
}
else
{
if(s[i] == L'\\')
{
tmp += s[++i];
}
else if(s[i] == L'}')
{
writing = true;
out.append(m[tmp]);
tmp = L"";
}
else
{
tmp += s[i];
}
}
}
return out;
}
int
main (int argc, char** argv)
{
wstring test1 = L"nothing here";
wstring test2 = L"a \\{test}\\ string \\\\{}{}";
wstring t1 = escape_string(test1);
wstring t2 = escape_string(test2);
wcout << L"Test 1 \"" << test1 << L"\" : \"" << t1 << L"\"" << endl;
wcout << L"Test 2 \"" << test2 << L"\" : \"" << t2 << L"\"" << endl;
map<wstring, wstring, WS> mm;
mm[L"f{}oo"] = L"bar";
wstring testtpl = L"a test \\{ {f\\{\\}oo} string";
wstring ttpl2 = fill_template(testtpl, mm);
wcout << L"Test 3: " << ttpl2 << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment