File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change @@ -73,6 +73,36 @@ void strip_whitespace(StrT& s) {
73
73
}
74
74
}
75
75
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
+
76
106
std::string escape_quotes (const std::string& s);
77
107
std::string escape_url (const std::string& s, bool escape_slash = false );
78
108
Original file line number Diff line number Diff line change @@ -490,7 +490,6 @@ int main(int, char**) {
490
490
491
491
string s = " abcdef" ;
492
492
strip_whitespace (s);
493
- fprintf (stderr, " %s\n " , s.c_str ());
494
493
expect_eq (s, " abcdef" );
495
494
496
495
s = " abcdef\r\n " ;
@@ -514,6 +513,22 @@ int main(int, char**) {
514
513
expect_eq (s, " " );
515
514
}
516
515
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\n ghi*/\n jkl" ;
528
+ strip_multiline_comments (s);
529
+ expect_eq (s, " abc\n\n\n jkl" );
530
+ }
531
+
517
532
{
518
533
fprintf (stderr, " -- string_printf\n " );
519
534
string result = string_printf (" %s %" PRIu64 " 0x%04hX" , " lolz" ,
You can’t perform that action at this time.
0 commit comments