Skip to content

Commit

Permalink
add strip_multiline_comments
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzziqersoftware committed Apr 25, 2024
1 parent 58d6ad8 commit a07045f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
30 changes: 30 additions & 0 deletions src/Strings.hh
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,36 @@ void strip_whitespace(StrT& s) {
}
}

template <typename StrT>
void strip_multiline_comments(StrT& s, bool allow_unterminated = false) {
bool is_in_comment = false;
size_t write_offset = 0;
for (size_t z = 0; z < s.size();) {
if (!is_in_comment) {
if ((s[z] == '/') && (z + 1 < s.size()) && (s[z + 1] == '*')) {
is_in_comment = true;
z += 2;
} else {
s[write_offset++] = s[z++];
}
} else {
if ((s[z] == '*') && (z + 1 < s.size()) && (s[z + 1] == '/')) {
is_in_comment = false;
z += 2;
} else {
if (s[z++] == '\n') {
s[write_offset++] = '\n';
}
}
}
}
s.resize(write_offset);

if (!allow_unterminated && is_in_comment) {
throw std::runtime_error("unterminated multiline comment");
}
}

std::string escape_quotes(const std::string& s);
std::string escape_url(const std::string& s, bool escape_slash = false);

Expand Down
17 changes: 16 additions & 1 deletion src/StringsTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,6 @@ int main(int, char**) {

string s = "abcdef";
strip_whitespace(s);
fprintf(stderr, "%s\n", s.c_str());
expect_eq(s, "abcdef");

s = "abcdef\r\n";
Expand All @@ -514,6 +513,22 @@ int main(int, char**) {
expect_eq(s, "");
}

{
fprintf(stderr, "-- strip_multiline_comments\n");

string s = "abc/*def*/ghi";
strip_multiline_comments(s);
expect_eq(s, "abcghi");

s = "/*abc*/def\r\n";
strip_multiline_comments(s);
expect_eq(s, "def\r\n");

s = "abc\n/*def\nghi*/\njkl";
strip_multiline_comments(s);
expect_eq(s, "abc\n\n\njkl");
}

{
fprintf(stderr, "-- string_printf\n");
string result = string_printf("%s %" PRIu64 " 0x%04hX", "lolz",
Expand Down

0 comments on commit a07045f

Please sign in to comment.