Skip to content

Commit a07045f

Browse files
add strip_multiline_comments
1 parent 58d6ad8 commit a07045f

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/Strings.hh

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,36 @@ void strip_whitespace(StrT& s) {
7373
}
7474
}
7575

76+
template <typename StrT>
77+
void strip_multiline_comments(StrT& s, bool allow_unterminated = false) {
78+
bool is_in_comment = false;
79+
size_t write_offset = 0;
80+
for (size_t z = 0; z < s.size();) {
81+
if (!is_in_comment) {
82+
if ((s[z] == '/') && (z + 1 < s.size()) && (s[z + 1] == '*')) {
83+
is_in_comment = true;
84+
z += 2;
85+
} else {
86+
s[write_offset++] = s[z++];
87+
}
88+
} else {
89+
if ((s[z] == '*') && (z + 1 < s.size()) && (s[z + 1] == '/')) {
90+
is_in_comment = false;
91+
z += 2;
92+
} else {
93+
if (s[z++] == '\n') {
94+
s[write_offset++] = '\n';
95+
}
96+
}
97+
}
98+
}
99+
s.resize(write_offset);
100+
101+
if (!allow_unterminated && is_in_comment) {
102+
throw std::runtime_error("unterminated multiline comment");
103+
}
104+
}
105+
76106
std::string escape_quotes(const std::string& s);
77107
std::string escape_url(const std::string& s, bool escape_slash = false);
78108

src/StringsTest.cc

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,6 @@ int main(int, char**) {
490490

491491
string s = "abcdef";
492492
strip_whitespace(s);
493-
fprintf(stderr, "%s\n", s.c_str());
494493
expect_eq(s, "abcdef");
495494

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

516+
{
517+
fprintf(stderr, "-- strip_multiline_comments\n");
518+
519+
string s = "abc/*def*/ghi";
520+
strip_multiline_comments(s);
521+
expect_eq(s, "abcghi");
522+
523+
s = "/*abc*/def\r\n";
524+
strip_multiline_comments(s);
525+
expect_eq(s, "def\r\n");
526+
527+
s = "abc\n/*def\nghi*/\njkl";
528+
strip_multiline_comments(s);
529+
expect_eq(s, "abc\n\n\njkl");
530+
}
531+
517532
{
518533
fprintf(stderr, "-- string_printf\n");
519534
string result = string_printf("%s %" PRIu64 " 0x%04hX", "lolz",

0 commit comments

Comments
 (0)