encoding.csv: fix reading when there is no line ending at the end of the file (fix #22337) (#22342)

This commit is contained in:
Felipe Pena 2024-09-28 11:49:40 -03:00 committed by GitHub
parent 64eb4c4913
commit 24238c107d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 2 deletions

View File

@ -0,0 +1,34 @@
import encoding.csv
fn test_no_ending() {
data := 'x,y,d
a,b
w'
mut parser := csv.new_reader(data)
mut arr := []string{}
for {
items := parser.read() or { break }
arr << items.join('-')
}
dump(arr)
assert arr[0].str() == 'x-y-d'
assert arr[1].str() == 'a-b'
assert arr[2].str() == 'w'
}
fn test_with_ending() {
data := 'x,y,d
a,b
w
'
mut parser := csv.new_reader(data)
mut arr := []string{}
for {
items := parser.read() or { break }
arr << items.join('-')
}
dump(arr)
assert arr[0].str() == 'x-y-d'
assert arr[1].str() == 'a-b'
assert arr[2].str() == 'w'
}

View File

@ -91,7 +91,7 @@ pub fn (mut r Reader) read() ![]string {
// } // }
fn (mut r Reader) read_line() !string { fn (mut r Reader) read_line() !string {
// last record // last record
if r.row_pos == r.data.len { if r.row_pos >= r.data.len {
return &EndOfFileError{} return &EndOfFileError{}
} }
le := if r.is_mac_pre_osx_le { '\r' } else { '\n' } le := if r.is_mac_pre_osx_le { '\r' } else { '\n' }
@ -108,7 +108,7 @@ fn (mut r Reader) read_line() !string {
} }
} else { } else {
// No line ending on file // No line ending on file
i = r.data.len - 1 i = r.data.len
} }
} }
mut line := r.data[r.row_pos..i] mut line := r.data[r.row_pos..i]