tree-sitter/src/compiler/util/string_helpers.cc

56 lines
1.2 KiB
C++
Raw Normal View History

#include "compiler/util/string_helpers.h"
#include <vector>
namespace tree_sitter {
namespace util {
2014-03-28 13:51:32 -07:00
using std::string;
using std::vector;
using std::set;
2014-03-28 13:51:32 -07:00
void str_replace(string *input, const string &search, const string &replace) {
size_t pos = 0;
while (1) {
pos = input->find(search, pos);
if (pos == string::npos)
break;
input->erase(pos, search.length());
input->insert(pos, replace);
pos += replace.length();
}
}
string escape_string(string input) {
str_replace(&input, "\"", "\\\"");
str_replace(&input, "\n", "\\n");
return input;
}
string escape_char(char character) {
switch (character) {
case '"':
return "'\\\"'";
case '\'':
return "'\\''";
case '\n':
return "'\\n'";
case '\r':
return "'\\r'";
case '\t':
return "'\\t'";
case '\\':
return "'\\\\'";
default:
if (character >= ' ' && character <= '~') {
return string("'") + character + "'";
} else {
char buffer[5];
snprintf(buffer, sizeof(buffer), "%d", static_cast<int>(character));
return string(buffer);
}
}
2014-04-28 21:46:43 -07:00
}
} // namespace util
} // namespace tree_sitter