Skip to content

Commit 9fbc06e

Browse files
nussjustinianlancetaylor
authored andcommitted
encoding/csv: preserve \r\n in quoted fields
The parser mistakenly assumed it could always fold \r\n into \n, which is not true since a \r\n inside a quoted fields has no special meaning and should be kept as is. Fix this by not folding \r\n to \n inside quotes fields. Fixes #21201 Change-Id: Ifebc302e49cf63e0a027ee90f088dbc050a2b7a6 Reviewed-on: https://go-review.googlesource.com/52810 Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent f9cf8e5 commit 9fbc06e

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/encoding/csv/reader.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,13 @@ func (r *Reader) readRune() (rune, error) {
233233
return r1, err
234234
}
235235

236+
// readRawRune works the same way as readRune, but does not fold \r\n to \n.
237+
func (r *Reader) readRawRune() (rune, error) {
238+
r1, _, err := r.r.ReadRune()
239+
r.column++
240+
return r1, err
241+
}
242+
236243
// skip reads runes up to and including the rune delim or until error.
237244
func (r *Reader) skip(delim rune) error {
238245
for {
@@ -351,7 +358,9 @@ func (r *Reader) parseField() (haveField bool, delim rune, err error) {
351358
// quoted field
352359
Quoted:
353360
for {
354-
r1, err = r.readRune()
361+
// use readRawRune instead of readRune to preserve \r\n
362+
// in quotes fields.
363+
r1, err = r.readRawRune()
355364
if err != nil {
356365
if err == io.EOF {
357366
if r.LazyQuotes {

src/encoding/csv/reader_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,13 @@ x,,,
284284
Line: 2,
285285
Column: 2,
286286
},
287+
{ // issue 21201
288+
Name: "CRLFInQuotedField",
289+
Input: "\"Hello\r\nHi\"",
290+
Output: [][]string{
291+
{"Hello\r\nHi"},
292+
},
293+
},
287294
}
288295

289296
func TestRead(t *testing.T) {

0 commit comments

Comments
 (0)