| 1 |
package csv |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
|
| 6 |
"github.com/gabriel-vasile/mimetype/internal/scan" |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
type Parser struct { |
| 13 |
comma byte |
| 14 |
comment byte |
| 15 |
s scan.Bytes |
| 16 |
} |
| 17 |
|
| 18 |
func NewParser(comma, comment byte, s scan.Bytes) *Parser { |
| 19 |
return &Parser{ |
| 20 |
comma: comma, |
| 21 |
comment: comment, |
| 22 |
s: s, |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
func (r *Parser) readLine() (line []byte, cutShort bool) { |
| 27 |
line = r.s.ReadSlice('\n') |
| 28 |
|
| 29 |
n := len(line) |
| 30 |
if n > 0 && line[n-1] == '\r' { |
| 31 |
return line[:n-1], false |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
if n >= 2 && line[n-2] == '\r' && line[n-1] == '\n' { |
| 39 |
return line[:n-2], true |
| 40 |
} |
| 41 |
return line, false |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
func (r *Parser) CountFields(collectIndexes bool) (fields int, fieldPos []int, hasMore bool) { |
| 50 |
finished := false |
| 51 |
var line scan.Bytes |
| 52 |
cutShort := false |
| 53 |
for { |
| 54 |
line, cutShort = r.readLine() |
| 55 |
if finished { |
| 56 |
return 0, nil, false |
| 57 |
} |
| 58 |
finished = len(r.s) == 0 && len(line) == 0 |
| 59 |
if len(line) == lengthNL(line) { |
| 60 |
line = nil |
| 61 |
continue |
| 62 |
} |
| 63 |
if len(line) > 0 && line[0] == r.comment { |
| 64 |
line = nil |
| 65 |
continue |
| 66 |
} |
| 67 |
break |
| 68 |
} |
| 69 |
|
| 70 |
indexes := []int{} |
| 71 |
originalLine := line |
| 72 |
parseField: |
| 73 |
for { |
| 74 |
if len(line) == 0 || line[0] != '"' { |
| 75 |
fields++ |
| 76 |
if collectIndexes { |
| 77 |
indexes = append(indexes, len(originalLine)-len(line)) |
| 78 |
} |
| 79 |
i := bytes.IndexByte(line, r.comma) |
| 80 |
if i >= 0 { |
| 81 |
line.Advance(i + 1) |
| 82 |
continue parseField |
| 83 |
} |
| 84 |
break parseField |
| 85 |
} else { |
| 86 |
if collectIndexes { |
| 87 |
indexes = append(indexes, len(originalLine)-len(line)) |
| 88 |
} |
| 89 |
line.Advance(1) |
| 90 |
for { |
| 91 |
i := bytes.IndexByte(line, '"') |
| 92 |
if i >= 0 { |
| 93 |
line.Advance(i + 1) |
| 94 |
switch rn := line.Peek(); { |
| 95 |
case rn == '"': |
| 96 |
line.Advance(1) |
| 97 |
case rn == r.comma: |
| 98 |
line.Advance(1) |
| 99 |
fields++ |
| 100 |
continue parseField |
| 101 |
case lengthNL(line) == len(line): |
| 102 |
fields++ |
| 103 |
break parseField |
| 104 |
} |
| 105 |
} else if len(line) > 0 || cutShort { |
| 106 |
line, cutShort = r.readLine() |
| 107 |
originalLine = line |
| 108 |
} else { |
| 109 |
fields++ |
| 110 |
break parseField |
| 111 |
} |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
return fields, indexes, fields != 0 |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
func lengthNL(b []byte) int { |
| 121 |
if len(b) > 0 && b[len(b)-1] == '\n' { |
| 122 |
return 1 |
| 123 |
} |
| 124 |
return 0 |
| 125 |
} |