string: split into lines correctly

pull/3700/head
Alexey 2020-02-09 11:23:57 +03:00 committed by GitHub
parent 4bb5d7de8b
commit 1eeee40278
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 3 deletions

View File

@ -468,13 +468,27 @@ pub fn (s string) split_into_lines() []string {
} }
mut start := 0 mut start := 0
for i := 0; i < s.len; i++ { for i := 0; i < s.len; i++ {
last := i == s.len - 1 is_lf := s[i] == `\n`
if s[i] == 10 || last { is_crlf := i != s.len - 1 && s[i] == `\r` && s[i + 1] == `\n`
if last { is_eol := is_lf || is_crlf
is_last := if is_crlf {
i == s.len - 2
} else {
i == s.len - 1
}
if is_eol || is_last {
if is_last && !is_eol {
i++ i++
} }
line := s.substr(start, i) line := s.substr(start, i)
res << line res << line
if is_crlf {
i++
}
start = i + 1 start = i + 1
} }
} }

View File

@ -634,3 +634,21 @@ fn test_double_quote_inter() {
assert '${a} ${b}' == "1 2" assert '${a} ${b}' == "1 2"
} }
fn test_split_into_lines() {
line_content := 'Line'
text_crlf := '${line_content}\r\n${line_content}\r\n${line_content}'
lines_crlf := text_crlf.split_into_lines()
assert lines_crlf.len == 3
for line in lines_crlf {
assert line == line_content
}
text_lf := '${line_content}\n${line_content}\n${line_content}'
lines_lf := text_lf.split_into_lines()
assert lines_lf.len == 3
for line in lines_lf {
assert line == line_content
}
}