storj.io/minio@v0.0.0-20230509071714-0cbc90f649b1/pkg/csvparser/reader.go (about)

     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 https://golang.org/LICENSE
     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 (rune 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  // Unwrap returns the underlying error
    84  func (e *ParseError) Unwrap() error { return e.Err }
    85  
    86  // These are the errors that can be returned in ParseError.Err.
    87  var (
    88  	ErrTrailingComma = errors.New("extra delimiter at end of line") // Deprecated: No longer used.
    89  	ErrBareQuote     = errors.New("bare \" in non-quoted-field")
    90  	ErrQuote         = errors.New("extraneous or missing \" in quoted-field")
    91  	ErrFieldCount    = errors.New("wrong number of fields")
    92  )
    93  
    94  var errInvalidDelim = errors.New("csv: invalid field or comment delimiter")
    95  
    96  func validDelim(r rune) bool {
    97  	return r != 0 && r != '"' && r != '\r' && r != '\n' && utf8.ValidRune(r) && r != utf8.RuneError
    98  }
    99  
   100  // A Reader reads records from a CSV-encoded file.
   101  //
   102  // As returned by NewReader, a Reader expects input conforming to RFC 4180.
   103  // The exported fields can be changed to customize the details before the
   104  // first call to Read or ReadAll.
   105  //
   106  // The Reader converts all \r\n sequences in its input to plain \n,
   107  // including in multiline field values, so that the returned data does
   108  // not depend on which line-ending convention an input file uses.
   109  type Reader struct {
   110  	// Comma is the field delimiter.
   111  	// It is set to comma (',') by NewReader.
   112  	// Comma must be a valid rune and must not be \r, \n,
   113  	// or the Unicode replacement character (0xFFFD).
   114  	Comma rune
   115  
   116  	// Quote is a single rune used for marking fields limits
   117  	Quote []rune
   118  
   119  	// QuoteEscape is a single rune to escape the quote character
   120  	QuoteEscape rune
   121  
   122  	// Comment, if not 0, is the comment character. Lines beginning with the
   123  	// Comment character without preceding whitespace are ignored.
   124  	// With leading whitespace the Comment character becomes part of the
   125  	// field, even if TrimLeadingSpace is true.
   126  	// Comment must be a valid rune and must not be \r, \n,
   127  	// or the Unicode replacement character (0xFFFD).
   128  	// It must also not be equal to Comma.
   129  	Comment rune
   130  
   131  	// FieldsPerRecord is the number of expected fields per record.
   132  	// If FieldsPerRecord is positive, Read requires each record to
   133  	// have the given number of fields. If FieldsPerRecord is 0, Read sets it to
   134  	// the number of fields in the first record, so that future records must
   135  	// have the same field count. If FieldsPerRecord is negative, no check is
   136  	// made and records may have a variable number of fields.
   137  	FieldsPerRecord int
   138  
   139  	// If LazyQuotes is true, a quote may appear in an unquoted field and a
   140  	// non-doubled quote may appear in a quoted field.
   141  	LazyQuotes bool
   142  
   143  	// If TrimLeadingSpace is true, leading white space in a field is ignored.
   144  	// This is done even if the field delimiter, Comma, is white space.
   145  	TrimLeadingSpace bool
   146  
   147  	// ReuseRecord controls whether calls to Read may return a slice sharing
   148  	// the backing array of the previous call's returned slice for performance.
   149  	// By default, each call to Read returns newly allocated memory owned by the caller.
   150  	ReuseRecord bool
   151  
   152  	TrailingComma bool // Deprecated: No longer used.
   153  
   154  	r *bufio.Reader
   155  
   156  	// numLine is the current line being read in the CSV file.
   157  	numLine int
   158  
   159  	// rawBuffer is a line buffer only used by the readLine method.
   160  	rawBuffer []byte
   161  
   162  	// recordBuffer holds the unescaped fields, one after another.
   163  	// The fields can be accessed by using the indexes in fieldIndexes.
   164  	// E.g., For the row `a,"b","c""d",e`, recordBuffer will contain `abc"de`
   165  	// and fieldIndexes will contain the indexes [1, 2, 5, 6].
   166  	recordBuffer []byte
   167  
   168  	// fieldIndexes is an index of fields inside recordBuffer.
   169  	// The i'th field ends at offset fieldIndexes[i] in recordBuffer.
   170  	fieldIndexes []int
   171  
   172  	// lastRecord is a record cache and only used when ReuseRecord == true.
   173  	lastRecord []string
   174  
   175  	// Caching some values between Read() calls for performance gain
   176  	cached               bool
   177  	cachedQuoteEscapeLen int
   178  	cachedQuoteLen       int
   179  	cachedEncodedQuote   []byte
   180  	cachedCommaLen       int
   181  	cachedQuotes         string
   182  }
   183  
   184  // NewReader returns a new Reader that reads from r.
   185  func NewReader(r io.Reader) *Reader {
   186  	return &Reader{
   187  		Comma:       ',',
   188  		Quote:       []rune(`"`),
   189  		QuoteEscape: '"',
   190  		r:           bufio.NewReader(r),
   191  	}
   192  }
   193  
   194  // Read reads one record (a slice of fields) from r.
   195  // If the record has an unexpected number of fields,
   196  // Read returns the record along with the error ErrFieldCount.
   197  // Except for that case, Read always returns either a non-nil
   198  // record or a non-nil error, but not both.
   199  // If there is no data left to be read, Read returns nil, io.EOF.
   200  // If ReuseRecord is true, the returned slice may be shared
   201  // between multiple calls to Read.
   202  func (r *Reader) Read() (record []string, err error) {
   203  	if r.ReuseRecord {
   204  		record, err = r.readRecord(r.lastRecord)
   205  		r.lastRecord = record
   206  	} else {
   207  		record, err = r.readRecord(nil)
   208  	}
   209  	return record, err
   210  }
   211  
   212  // ReadAll reads all the remaining records from r.
   213  // Each record is a slice of fields.
   214  // A successful call returns err == nil, not err == io.EOF. Because ReadAll is
   215  // defined to read until EOF, it does not treat end of file as an error to be
   216  // reported.
   217  func (r *Reader) ReadAll() (records [][]string, err error) {
   218  	for {
   219  		record, err := r.readRecord(nil)
   220  		if err == io.EOF {
   221  			return records, nil
   222  		}
   223  		if err != nil {
   224  			return nil, err
   225  		}
   226  		records = append(records, record)
   227  	}
   228  }
   229  
   230  // readLine reads the next line (with the trailing endline).
   231  // If EOF is hit without a trailing endline, it will be omitted.
   232  // If some bytes were read, then the error is never io.EOF.
   233  // The result is only valid until the next call to readLine.
   234  func (r *Reader) readLine() ([]byte, error) {
   235  	line, err := r.r.ReadSlice('\n')
   236  	if err == bufio.ErrBufferFull {
   237  		r.rawBuffer = append(r.rawBuffer[:0], line...)
   238  		for err == bufio.ErrBufferFull {
   239  			line, err = r.r.ReadSlice('\n')
   240  			r.rawBuffer = append(r.rawBuffer, line...)
   241  		}
   242  		line = r.rawBuffer
   243  	}
   244  	if len(line) > 0 && err == io.EOF {
   245  		err = nil
   246  		// For backwards compatibility, drop trailing \r before EOF.
   247  		if line[len(line)-1] == '\r' {
   248  			line = line[:len(line)-1]
   249  		}
   250  	}
   251  	r.numLine++
   252  	// Normalize \r\n to \n on all input lines.
   253  	if n := len(line); n >= 2 && line[n-2] == '\r' && line[n-1] == '\n' {
   254  		line[n-2] = '\n'
   255  		line = line[:n-1]
   256  	}
   257  	return line, err
   258  }
   259  
   260  // lengthNL reports the number of bytes for the trailing \n.
   261  func lengthNL(b []byte) int {
   262  	if len(b) > 0 && b[len(b)-1] == '\n' {
   263  		return 1
   264  	}
   265  	return 0
   266  }
   267  
   268  // nextRune returns the next rune in b or utf8.RuneError.
   269  func nextRune(b []byte) rune {
   270  	r, _ := utf8.DecodeRune(b)
   271  	return r
   272  }
   273  
   274  func encodeRune(r rune) []byte {
   275  	rlen := utf8.RuneLen(r)
   276  	p := make([]byte, rlen)
   277  	_ = utf8.EncodeRune(p, r)
   278  	return p
   279  }
   280  
   281  func (r *Reader) readRecord(dst []string) ([]string, error) {
   282  	if r.Comma == r.Comment || !validDelim(r.Comma) || (r.Comment != 0 && !validDelim(r.Comment)) {
   283  		return nil, errInvalidDelim
   284  	}
   285  
   286  	// Read line (automatically skipping past empty lines and any comments).
   287  	var line, fullLine []byte
   288  	var errRead error
   289  	for errRead == nil {
   290  		line, errRead = r.readLine()
   291  		if r.Comment != 0 && nextRune(line) == r.Comment {
   292  			line = nil
   293  			continue // Skip comment lines
   294  		}
   295  		if errRead == nil && len(line) == lengthNL(line) {
   296  			line = nil
   297  			continue // Skip empty lines
   298  		}
   299  		fullLine = line
   300  		break
   301  	}
   302  	if errRead == io.EOF {
   303  		return nil, errRead
   304  	}
   305  
   306  	if !r.cached {
   307  		r.cachedQuoteEscapeLen = utf8.RuneLen(r.QuoteEscape)
   308  		if len(r.Quote) > 0 {
   309  			r.cachedQuoteLen = utf8.RuneLen(r.Quote[0])
   310  			r.cachedEncodedQuote = encodeRune(r.Quote[0])
   311  			r.cachedQuotes += string(r.Quote[0])
   312  		}
   313  		r.cachedCommaLen = utf8.RuneLen(r.Comma)
   314  		r.cachedQuotes += string(r.QuoteEscape)
   315  		r.cached = true
   316  	}
   317  
   318  	// Parse each field in the record.
   319  	var err error
   320  	recLine := r.numLine // Starting line for record
   321  	r.recordBuffer = r.recordBuffer[:0]
   322  	r.fieldIndexes = r.fieldIndexes[:0]
   323  parseField:
   324  	for {
   325  		if r.TrimLeadingSpace {
   326  			line = bytes.TrimLeftFunc(line, unicode.IsSpace)
   327  		}
   328  		if len(line) == 0 || r.cachedQuoteLen == 0 || nextRune(line) != r.Quote[0] {
   329  			// Non-quoted string field
   330  			i := bytes.IndexRune(line, r.Comma)
   331  			field := line
   332  			if i >= 0 {
   333  				field = field[:i]
   334  			} else {
   335  				field = field[:len(field)-lengthNL(field)]
   336  			}
   337  			// Check to make sure a quote does not appear in field.
   338  			if !r.LazyQuotes {
   339  				if j := bytes.IndexRune(field, r.Quote[0]); j >= 0 {
   340  					col := utf8.RuneCount(fullLine[:len(fullLine)-len(line[j:])])
   341  					err = &ParseError{StartLine: recLine, Line: r.numLine, Column: col, Err: ErrBareQuote}
   342  					break parseField
   343  				}
   344  			}
   345  			r.recordBuffer = append(r.recordBuffer, field...)
   346  			r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   347  			if i >= 0 {
   348  				line = line[i+r.cachedCommaLen:]
   349  				continue parseField
   350  			}
   351  			break parseField
   352  		} else {
   353  			// Quoted string field
   354  			line = line[r.cachedQuoteLen:]
   355  			for {
   356  				i := bytes.IndexAny(line, r.cachedQuotes)
   357  				if i >= 0 {
   358  					// Hit next quote or escape quote
   359  					r.recordBuffer = append(r.recordBuffer, line[:i]...)
   360  
   361  					escape := nextRune(line[i:]) == r.QuoteEscape
   362  					if escape {
   363  						line = line[i+r.cachedQuoteEscapeLen:]
   364  					} else {
   365  						line = line[i+r.cachedQuoteLen:]
   366  					}
   367  
   368  					switch rn := nextRune(line); {
   369  					case escape && r.QuoteEscape != r.Quote[0]:
   370  						r.recordBuffer = append(r.recordBuffer, encodeRune(rn)...)
   371  						line = line[utf8.RuneLen(rn):]
   372  					case rn == r.Quote[0]:
   373  						// `""` sequence (append quote).
   374  						r.recordBuffer = append(r.recordBuffer, r.cachedEncodedQuote...)
   375  						line = line[r.cachedQuoteLen:]
   376  					case rn == r.Comma:
   377  						// `",` sequence (end of field).
   378  						line = line[r.cachedCommaLen:]
   379  						r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   380  						continue parseField
   381  					case lengthNL(line) == len(line):
   382  						// `"\n` sequence (end of line).
   383  						r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   384  						break parseField
   385  					case r.LazyQuotes:
   386  						// `"` sequence (bare quote).
   387  						r.recordBuffer = append(r.recordBuffer, r.cachedEncodedQuote...)
   388  					default:
   389  						// `"*` sequence (invalid non-escaped quote).
   390  						col := utf8.RuneCount(fullLine[:len(fullLine)-len(line)-r.cachedQuoteLen])
   391  						err = &ParseError{StartLine: recLine, Line: r.numLine, Column: col, Err: ErrQuote}
   392  						break parseField
   393  					}
   394  				} else if len(line) > 0 {
   395  					// Hit end of line (copy all data so far).
   396  					r.recordBuffer = append(r.recordBuffer, line...)
   397  					if errRead != nil {
   398  						break parseField
   399  					}
   400  					line, errRead = r.readLine()
   401  					if errRead == io.EOF {
   402  						errRead = nil
   403  					}
   404  					fullLine = line
   405  				} else {
   406  					// Abrupt end of file (EOF or error).
   407  					if !r.LazyQuotes && errRead == nil {
   408  						col := utf8.RuneCount(fullLine)
   409  						err = &ParseError{StartLine: recLine, Line: r.numLine, Column: col, Err: ErrQuote}
   410  						break parseField
   411  					}
   412  					r.fieldIndexes = append(r.fieldIndexes, len(r.recordBuffer))
   413  					break parseField
   414  				}
   415  			}
   416  		}
   417  	}
   418  	if err == nil {
   419  		err = errRead
   420  	}
   421  
   422  	// Create a single string and create slices out of it.
   423  	// This pins the memory of the fields together, but allocates once.
   424  	str := string(r.recordBuffer) // Convert to string once to batch allocations
   425  	dst = dst[:0]
   426  	if cap(dst) < len(r.fieldIndexes) {
   427  		dst = make([]string, len(r.fieldIndexes))
   428  	}
   429  	dst = dst[:len(r.fieldIndexes)]
   430  	var preIdx int
   431  	for i, idx := range r.fieldIndexes {
   432  		dst[i] = str[preIdx:idx]
   433  		preIdx = idx
   434  	}
   435  
   436  	// Check or update the expected fields per record.
   437  	if r.FieldsPerRecord > 0 {
   438  		if len(dst) != r.FieldsPerRecord && err == nil {
   439  			err = &ParseError{StartLine: recLine, Line: recLine, Err: ErrFieldCount}
   440  		}
   441  	} else if r.FieldsPerRecord == 0 {
   442  		r.FieldsPerRecord = len(dst)
   443  	}
   444  	return dst, err
   445  }