-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparsegen_string.cpp
94 lines (84 loc) · 1.81 KB
/
parsegen_string.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "parsegen_string.hpp"
#include <stdexcept>
#include <cctype>
#include <algorithm>
namespace parsegen {
std::string escape(std::string const& in)
{
std::string out;
for (char c : in) {
if (c == '\n') {
out += "\\n";
} else if (c == '\r') {
out += "\\r";
} else if (c == '\t') {
out += "\\t";
} else if (c == '"') {
out += "\\\"";
} else if (c == '\'') {
out += "\\'";
} else {
out.push_back(c);
}
}
return out;
}
std::string unescape(std::string const& in)
{
bool is_escaped = false;
std::string out;
for (char c : in) {
if (is_escaped) {
if (c == 'n') {
out.push_back('\n');
} else if (c == 'r') {
out.push_back('\r');
} else if (c == 't') {
out.push_back('\t');
} else {
out.push_back(c);
}
is_escaped = false;
} else {
if (c == '\\') {
is_escaped = true;
} else if (c == '"') {
} else {
out.push_back(c);
}
}
}
return out;
}
std::string double_quote(std::string const& s)
{
return "\"" + escape(s) + "\"";
}
std::string single_quote(std::string const& s)
{
return "'" + escape(s) + "'";
}
std::string unquote(std::string const& s)
{
if (s.length() < 2) {
throw std::runtime_error("parsegen::unquote given a string shorter than two quotes");
}
return unescape(s.substr(1, s.length() - 2));
}
std::string lowercase(std::string const& s) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(),
[] (unsigned char c) {
return std::tolower(c);
});
return result;
}
std::string uppercase(std::string const& s) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(),
[] (unsigned char c) {
return std::toupper(c);
});
return result;
}
}