[PATCH] D39279: Stringizing raw string literals containing newline
Jan Korous via Phabricator via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 29 06:03:54 PST 2017
jkorous-apple added a comment.
I am sorry I wasn't really clear. What I meant was to do something like this (pseudo-code, dealing only with newlines):
if( Str.size() == 0)
return;
// Calculate all the extra space needed first.
typename T::size_type extra_space = 0;
bool previous_char_was_endline = false;
for(const auto ch : Str) {
if( ch == '\n' || ch == '\r' ) {
if( !previous_char_was_endline )
++extra_space;
previous_char_was_endline = true;
} else {
previous_char_was_endline = false;
}
}
if (extra_space == 0)
return;
// Resize the string.
const typename T::size_type original_size = Str.size();
Str.resize(original_size + extra_space);
// Iterate backwards and move characters as needed.
bool is_in_block_of_endlines = false;
for(typename T::size_type i = original_size - 1; i > 0; --i) {
if( Str[i] == '\n' || Str[i] == '\r' ) {
if (!is_in_block_of_endlines) {
Str[i + extra_space - 1] = '\\';
Str[i + extra_space] = 'n';
--extra_space;
if(extra_space == 0)
return; // early exit - no more characters need to be moved
}
is_in_block_of_endlines = true;
} else {
Str[i + extra_space] = Str[i];
is_in_block_of_endlines = false;
}
}
This is just a suggestion, it is a bit more complicated but should be O(lenght_of_string) whereas your solution is a bit more straightforward but is more like O(length_of_string * number_of_endlines_in_string). I leave it up to you what is better here. If you decide to go this way, please assume my pseudocode is buggy and don't rely on it.
https://reviews.llvm.org/D39279
More information about the cfe-commits
mailing list