Source file src/encoding/csv/reader.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package csv reads and writes comma-separated values (CSV) files.
     6  // There are many kinds of CSV files; this package supports the format
     7  // described in RFC 4180.
     8  //
     9  // A csv file contains zero or more records of one or more fields per record.
    10  // Each record is separated by the newline character. The final record may
    11  // optionally be followed by a newline character.
    12  //
    13  //	field1,field2,field3
    14  //
    15  // White space is considered part of a field.
    16  //
    17  // Carriage returns before newline characters are silently removed.
    18  //
    19  // Blank lines are ignored. A line with only whitespace characters (excluding
    20  // the ending newline character) is not considered a blank line.
    21  //
    22  // Fields which start and stop with the quote character " are called
    23  // quoted-fields. The beginning and ending quote are not part of the
    24  // field.
    25  //
    26  // The source:
    27  //
    28  //	normal string,"quoted-field"
    29  //
    30  // results in the fields
    31  //
    32  //	{`normal string`, `quoted-field`}
    33  //
    34  // Within a quoted-field a quote character followed by a second quote
    35  // character is considered a single quote.
    36  //
    37  //	"the ""word"" is true","a ""quoted-field"""
    38  //
    39  // results in
    40  //
    41  //	{`the "word" is true`, `a "quoted-field"`}
    42  //
    43  // Newlines and commas may be included in a quoted-field
    44  //
    45  //	"Multi-line
    46  //	field","comma is ,"
    47  //
    48  // results in
    49  //
    50  //	{`Multi-line
    51  //	field`, `comma is ,`}
    52  package csv
    53  
    54  import (
    55  	"bufio"
    56  	"bytes"
    57  	"errors"
    58  	"fmt"
    59  	"io"
    60  	"unicode"
    61  	"unicode/utf8"
    62  )
    63  
    64  // A ParseError is returned for parsing errors.
    65  // Line numbers are 1-indexed and columns are 0-indexed.
    66  type ParseError struct {
    67  	StartLine int   // Line where the record starts
    68  	Line      int   // Line where the error occurred
    69  	Column    int   // Column (1-based byte index) where the error occurred
    70  	Err       error // The actual error
    71  }
    72  
    73  func (e *ParseError) Error() string {
    74  	if e.Err == ErrFieldCount {
    75  		return fmt.Sprintf("record on line %d: %v", e.Line, e.Err)
    76  	}
    77  	if e.StartLine != e.Line {
    78  		return fmt.Sprintf("record on line %d; parse error on line %d, column %d: %v", e.StartLine, e.Line, e.Column, e.Err)
    79  	}
    80  	return fmt.Sprintf("parse error on line %d, column %d: %v", e.Line, e.Column, e.Err)
    81  }
    82  
    83  func (e *ParseError) Unwrap() error { return e.Err }
    84  
    85  // These are the errors that can be returned in ParseError.Err.
    86  var (
    87  	ErrBareQuote  = errors.New("bare \" in non-quoted-field")
    88  	ErrQuote      = errors.New("extraneous or missing \" in quoted-field")
    89  	ErrFieldCount = errors.New("wrong number of fields")
    90  
    91  	// Deprecated: ErrTrailingComma is no longer used.
    92  	ErrTrailingComma = errors.New("extra delimiter at end of line")
    93  )
    94  
    95  var errInvalidDelim = errors.New("csv: invalid field or comment delimiter")
    96  
    97  func validDelim(r rune) bool {
    98  	return r != 0 && r != '"' && r != '\r' && r != '\n' && utf8.ValidRune(r) && r != utf8.RuneError
    99  }
   100  
   101  // A Reader reads records from a CSV-encoded file.
   102  //
   103  // As returned by NewReader, a Reader expects input conforming to RFC 4180.
   104  // The exported fields can be changed to customize the details before the
   105  // first call to Read or ReadAll.
   106  //
   107  // The Reader converts all \r\n sequences in its input to plain \n,
   108  // including in multiline field values, so that the returned data does
   109  // not depend on which line-ending convention an input file uses.
   110  type Reader struct {
   111  	// Comma is the field delimiter.
   112  	// It is set to comma (',') by NewReader.
   113  	// Comma must be a valid rune and must not be \r, \n,
   114  	// or the Unicode replacement character (0xFFFD).
   115  	Comma rune
   116  
   117  	// Comment, if not 0, is the comment character. Lines beginning with the
   118  	// Comment character without preceding whitespace are ignored.
   119  	// With leading whitespace the Comment character becomes part of the
   120  	// field, even if TrimLeadingSpace is true.
   121  	// Comment must be a valid rune and must not be \r, \n,
   122  	// or the Unicode replacement character (0xFFFD).
   123  	// It must also not be equal to Comma.
   124  	Comment rune
   125  
   126  	// FieldsPerRecord is the number of expected fields per record.
   127  	// If FieldsPerRecord is positive, Read requires each record to
   128  	// have the given number of fields. If FieldsPerRecord is 0, Read sets it to
   129  	// the number of fields in the first record, so that future records must
   130  	// have the same field count. If FieldsPerRecord is negative, no check is
   131  	// made and records may have a variable number of fields.
   132  	FieldsPerRecord int
   133  
   134  	// If LazyQuotes is true, a quote may appear in an unquoted field and a
   135  	// non-doubled quote may appear in a quoted field.
   136  	LazyQuotes bool
   137  
   138  	// If TrimLeadingSpace is true, leading white space in a field is ignored.
   139  	// This is done even if the field delimiter, Comma, is white space.
   140  	TrimLeadingSpace bool
   141  
   142  	// ReuseRecord controls whether calls to Read may return a slice sharing
   143  	// the backing array of the previous call's returned slice for performance.
   144  	// By default, each call to Read returns newly allocated memory owned by the caller.
   145  	ReuseRecord bool
   146  
   147  	// Deprecated: TrailingComma is no longer used.
   148  	TrailingComma bool
   149  
   150  	r *bufio.Reader
   151  
   152  	// numLine is the current line being read in the CSV file.
   153  	numLine int
   154  
   155  	// offset is the input stream byte offset of the current reader position.
   156  	offset int64
   157  
   158  	// rawBuffer is a line buffer only used by the readLine method.
   159  	rawBuffer []byte
   160  
   161  	// recordBuffer holds the unescaped fields, one after another.
   162  	// The fields can be accessed by using the indexes in fieldIndexes.
   163  	// E.g., For the row `a,"b","c""d",e`, recordBuffer will contain `abc"de`
   164  	// and fieldIndexes will contain the indexes [1, 2, 5, 6].
   165  	recordBuffer []byte
   166  
   167  	// fieldIndexes is an index of fields inside recordBuffer.
   168  	// The i'th field ends at offset fieldIndexes[i] in recordBuffer.
   169  	fieldIndexes []int
   170  
   171  	// fieldPositions is an index of field positions for the
   172  	// last record returned by Read.
   173  	fieldPositions []position
   174  
   175  	// lastRecord is a record cache and only used when ReuseRecord == true.
   176  	lastRecord []string
   177  }
   178  
   179  // NewReader returns a new Reader that reads from r.
   180  func NewReader(r io.Reader) *Reader {
   181  	return &Reader{
   182  		Comma: ',',
   183  		r:     bufio.NewReader(r),
   184  	}
   185  }
   186  
   187  // Read reads one record (a slice of fields) from r.
   188  // If the record has an unexpected number of fields,
   189  // Read returns the record along with the error ErrFieldCount.
   190  // Except for that case, Read always returns either a non-nil
   191  // record or a non-nil error, but not both.
   192  // If there is no data left to be read, Read returns nil, io.EOF.
   193  // If ReuseRecord is true, the returned slice may be shared
   194  // between multiple calls to Read.
   195  func (r *Reader) Read() (record []string, err error) {
   196  	if r.ReuseRecord {
   197  		record, err = r.readRecord(r.lastRecord)
   198  		r.lastRecord = record
   199  	} else {
   200  		record, err = r.readRecord(nil)
   201  	}
   202  	return record, err
   203  }
   204  
   205  // FieldPos returns the line and column corresponding to
   206  // the start of the field with the given index in the slice most recently
   207  // returned by Read. Numbering of lines and columns starts at 1;
   208  // columns are counted in bytes, not runes.
   209  //
   210  // If this is called with an out-of-bounds index, it panics.
   211  func (r *Reader) FieldPos(field int) (line, column int) {
   212  	if field < 0 || field >= len(r.fieldPositions) {
   213  		panic("out of range index passed to FieldPos")
   214  	}
   215  	p := &r.fieldPositions[field]
   216  	return p.line, p.col
   217  }
   218  
   219  // InputOffset returns the input stream byte offset of the current reader
   220  // position. The offset gives the location of the end of the most recently
   221  // read row and the beginning of the next row.
   222  func (r *Reader) InputOffset() int64 {
   223  	return r.offset
   224  }
   225  
   226  // pos holds the position of a field in the current line.
   227  type position struct {
   228  	line, col int
   229  }
   230  
   231  // ReadAll reads all the remaining records from r.
   232  // Each record is a slice of fields.
   233  // A successful call returns err == nil, not err == io.EOF. Because ReadAll is
   234  // defined to read until EOF, it does not treat end of file as an error to be
   235  // reported.
   236  func (r *Reader) ReadAll() (records [][]string, err error) {
   237  	for {
   238  		record, err := r.readRecord(nil)
   239  		if err == io.EOF {
   240  			return records, nil
   241  		}
   242  		if err != nil {
   243  			return nil, err
   244  		}
   245  		records = append(records, record)
   246  	}
   247  }
   248  
   249  // readLine reads the next line (with the trailing endline).
   250  // If EOF is hit without a trailing endline, it will be omitted.
   251  // If some bytes were read, then the error is never io.EOF.
   252  // The result is only valid until the next call to readLine.
   253  func (r *Reader) readLine() ([]byte, error) {
   254  	line, err := r.r.ReadSlice('\n')
   255  	if err == bufio.ErrBufferFull {
   256  		r.rawBuffer = append(r.rawBuffer[:0], line...)
   257  		for err == bufio.ErrBufferFull {
   258  			line, err = r.r.ReadSlice('\n')
   259  			r.rawBuffer = append(r.rawBuffer, line...)
   260  		}
   261  		line = r.rawBuffer
   262  	}
   263  	readSize := len(line)
   264  	if readSize > 0 && err == io.EOF {
   265  		err = nil
   266  		// For backwards compatibility, drop trailing \r before EOF.
   267  		if line[readSize-1] == '\r' {
   268  			line = line[:readSize-1]
   269  		}
   270  	}
   271  	r.numLine++
   272  	r.offset += int64(readSize)
   273  	// Normalize \r\n to \n on all input lines.
   274  	if n := len(line); n >= 2 && line[n-2] == '\r' && line[n-1] == '\n' {
   275  		line[n-2] = '\n'
   276  		line = line[:n-1]
   277  	}
   278  	return line, err
   279  }
   280  
   281  // lengthNL reports the number of bytes for the trailing \n.
   282  func lengthNL(b []byte) int {
   283  	if len(b) > 0 && b[len(b)-1] == '\n' {
   284  		return 1
   285  	}
   286  	return 0
   287  }
   288  
   289  // nextRune returns the next rune in b or utf8.RuneError.
   290  func nextRune(b []byte) rune {
   291  	r, _ := utf8.DecodeRune(b)
   292  	return r
   293  }
   294  
   295  func (r *Reader) readRecord(dst []string) ([]string, error) {
   296  	if r.Comma == r.Comment || !validDelim(r.Comma) || (r.Comment != 0 && !validDelim(r.Comment)) {
   297  		return nil, errInvalidDelim
   298  	}
   299  
   300  	// Read line (automatically skipping past empty lines and any comments).
   301  	var line []byte
   302  	var errRead error
   303  	for errRead == nil {
   304  		line, errRead = r.readLine()
   305  		if r.Comment != 0 && nextRune(line) == r.Comment {
   306  			line = nil
   307  			continue // Skip comment lines
   308  		}
   309  		if errRead == nil && len(line) == lengthNL(line) {
   310  			line = nil
   311  			continue // Skip empty lines
   312  		}
   313  		break
   314  	}
   315  	if errRead == io.EOF {
   316  		return nil, errRead
   317  	}
   318  
   319  	// Parse each field in the record.
   320  	var err error
   321  	const quoteLen = len(`"`)
   322  	commaLen := utf8.RuneLen(r.Comma)
   323  	recLine := r.numLine // Starting line for record
   324  	r.recordBuffer = r.recordBuffer[:0]
   325  	r.fieldIndexes = r.fieldIndexes[:0]
   326  	r.fieldPositions = r.fieldPositions[:0]
   327  	pos := position{line: r.numLine, col: 1}
   328  parseField:
   329  	for {
   330  		if r.TrimLeadingSpace {
   331  			i := bytes.IndexFunc(line, func(r rune) bool {
   332  				return !unicode.IsSpace(r)
   333  			})
   334  			if i < 0 {
   335  				i = len(line)
   336  				pos.col -= lengthNL(line)
   337  			}
   338  			line = line[i:]
   339  			pos.col += i
   340  		}
   341  		if len(line) == 0 || line[0] != '"' {
   342  			// Non-quoted string field
   343  			i := bytes.IndexRune(line, r.Comma)
   344  			field := line
   345  			if i >= 0 {
   346  				field = field[:i]
   347  			} else {
   348  				field = field[:len(field)-lengthNL(field)]
   349  			}
   350  			// Check to make sure a quote does not appear in field.
   351  			if !r.LazyQuotes {
   352  				if j := bytes.IndexByte(field, '"'); j >= 0 {
   353  					col := pos.col + j
   354  					err = &ParseError{StartLine: recLine, Line: r.numLine, Column: col, Err: ErrBareQuote}
   355  					break parseField
   356  				}
   357  			}
   358  			r.recordBuffer = append(r.recordBuffer, field...)
   359  			r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   360  			r.fieldPositions = append(r.fieldPositions, pos)
   361  			if i >= 0 {
   362  				line = line[i+commaLen:]
   363  				pos.col += i + commaLen
   364  				continue parseField
   365  			}
   366  			break parseField
   367  		} else {
   368  			// Quoted string field
   369  			fieldPos := pos
   370  			line = line[quoteLen:]
   371  			pos.col += quoteLen
   372  			for {
   373  				i := bytes.IndexByte(line, '"')
   374  				if i >= 0 {
   375  					// Hit next quote.
   376  					r.recordBuffer = append(r.recordBuffer, line[:i]...)
   377  					line = line[i+quoteLen:]
   378  					pos.col += i + quoteLen
   379  					switch rn := nextRune(line); {
   380  					case rn == '"':
   381  						// `""` sequence (append quote).
   382  						r.recordBuffer = append(r.recordBuffer, '"')
   383  						line = line[quoteLen:]
   384  						pos.col += quoteLen
   385  					case rn == r.Comma:
   386  						// `",` sequence (end of field).
   387  						line = line[commaLen:]
   388  						pos.col += commaLen
   389  						r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   390  						r.fieldPositions = append(r.fieldPositions, fieldPos)
   391  						continue parseField
   392  					case lengthNL(line) == len(line):
   393  						// `"\n` sequence (end of line).
   394  						r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   395  						r.fieldPositions = append(r.fieldPositions, fieldPos)
   396  						break parseField
   397  					case r.LazyQuotes:
   398  						// `"` sequence (bare quote).
   399  						r.recordBuffer = append(r.recordBuffer, '"')
   400  					default:
   401  						// `"*` sequence (invalid non-escaped quote).
   402  						err = &ParseError{StartLine: recLine, Line: r.numLine, Column: pos.col - quoteLen, Err: ErrQuote}
   403  						break parseField
   404  					}
   405  				} else if len(line) > 0 {
   406  					// Hit end of line (copy all data so far).
   407  					r.recordBuffer = append(r.recordBuffer, line...)
   408  					if errRead != nil {
   409  						break parseField
   410  					}
   411  					pos.col += len(line)
   412  					line, errRead = r.readLine()
   413  					if len(line) > 0 {
   414  						pos.line++
   415  						pos.col = 1
   416  					}
   417  					if errRead == io.EOF {
   418  						errRead = nil
   419  					}
   420  				} else {
   421  					// Abrupt end of file (EOF or error).
   422  					if !r.LazyQuotes && errRead == nil {
   423  						err = &ParseError{StartLine: recLine, Line: pos.line, Column: pos.col, Err: ErrQuote}
   424  						break parseField
   425  					}
   426  					r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   427  					r.fieldPositions = append(r.fieldPositions, fieldPos)
   428  					break parseField
   429  				}
   430  			}
   431  		}
   432  	}
   433  	if err == nil {
   434  		err = errRead
   435  	}
   436  
   437  	// Create a single string and create slices out of it.
   438  	// This pins the memory of the fields together, but allocates once.
   439  	str := string(r.recordBuffer) // Convert to string once to batch allocations
   440  	dst = dst[:0]
   441  	if cap(dst) < len(r.fieldIndexes) {
   442  		dst = make([]string, len(r.fieldIndexes))
   443  	}
   444  	dst = dst[:len(r.fieldIndexes)]
   445  	var preIdx int
   446  	for i, idx := range r.fieldIndexes {
   447  		dst[i] = str[preIdx:idx]
   448  		preIdx = idx
   449  	}
   450  
   451  	// Check or update the expected fields per record.
   452  	if r.FieldsPerRecord > 0 {
   453  		if len(dst) != r.FieldsPerRecord && err == nil {
   454  			err = &ParseError{
   455  				StartLine: recLine,
   456  				Line:      recLine,
   457  				Column:    1,
   458  				Err:       ErrFieldCount,
   459  			}
   460  		}
   461  	} else if r.FieldsPerRecord == 0 {
   462  		r.FieldsPerRecord = len(dst)
   463  	}
   464  	return dst, err
   465  }
   466  

View as plain text