-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrecord_builder.go
More file actions
505 lines (427 loc) · 16.3 KB
/
record_builder.go
File metadata and controls
505 lines (427 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//go:build goexperiment.simd && amd64
//nolint:gosec // G115: Integer conversions are safe - buffer size bounded by DefaultMaxInputSize (2GB)
package simdcsv
import (
"bytes"
"unsafe"
)
// Buffer allocation constants for reducing reallocations in hot path.
const (
// minRecordBufferSize is the minimum capacity for recordBuffer to avoid small reallocations.
// 4KB covers most typical CSV rows.
minRecordBufferSize = 4 * 1024
// minFieldEndsSize is the minimum capacity for fieldEnds slice.
// 32 fields covers most typical CSV files.
minFieldEndsSize = 32
// minFieldPositionsSize is the minimum capacity for fieldPositions slice.
minFieldPositionsSize = 32
)
// ============================================================================
// Record Building - Main Entry Point
// ============================================================================
// buildRecordWithValidation constructs a []string record from a rowInfo with quote validation.
//
// Recovery Behavior: On validation error, returns a partial record containing all
// successfully parsed fields up to the error point, along with the error.
// This matches encoding/csv behavior and allows callers to recover partial data.
func (r *Reader) buildRecordWithValidation(row rowInfo, rowIdx int) ([]string, error) {
fieldCount := row.fieldCount
fields := r.getFieldsForRow(row, fieldCount)
// Fast path: check if any field needs transformation
needsTransform := r.state.hasCR
if !needsTransform {
for _, field := range fields {
if field.needsUnescape() {
needsTransform = true
break
}
}
}
// Fast path: zero-copy when no transformation needed (but still validate)
if !needsTransform && !r.TrimLeadingSpace {
return r.buildRecordWithValidationZeroCopy(row, fields)
}
// Standard path with transformation
r.prepareBuffers(row, fieldCount)
for i, field := range fields {
if err := r.validateFieldIfNeeded(field, row.lineNum); err != nil {
return r.buildPartialRecord(i), err
}
r.processField(field, i, row.lineNum)
}
return r.buildFinalRecord(fieldCount), nil
}
// buildRecordWithValidationZeroCopy builds a record with zero-copy strings while validating.
// Zero-copy is safe here because rawBuffer outlives the returned record strings.
func (r *Reader) buildRecordWithValidationZeroCopy(row rowInfo, fields []fieldInfo) ([]string, error) {
fieldCount := row.fieldCount
record := r.allocateRecord(fieldCount)
r.state.fieldPositions = r.ensureFieldPositionsCapacity(fieldCount)
buf := r.state.rawBuffer
bufLen := uint32(len(buf))
for i, field := range fields {
if err := r.validateFieldIfNeeded(field, row.lineNum); err != nil {
return record[:i], err
}
record[i] = r.extractFieldString(buf, bufLen, field)
r.state.fieldPositions[i] = position{line: row.lineNum, column: int(field.rawStart()) + 1}
}
return record, nil
}
// extractFieldString returns a zero-copy string for the field content.
// Returns empty string if field is out of bounds.
func (r *Reader) extractFieldString(buf []byte, bufLen uint32, field fieldInfo) string {
start := field.start
end := start + field.length
if start >= bufLen {
return ""
}
if end > bufLen {
end = bufLen
}
return unsafe.String(&buf[start], int(end-start))
}
// buildRecordNoQuotes builds a record when the input contains no quotes.
// Uses a single row string to avoid per-field allocations.
// Zero-copy when TrimLeadingSpace is disabled; copies when trimming is needed.
func (r *Reader) buildRecordNoQuotes(row rowInfo) []string {
fieldCount := row.fieldCount
record := r.allocateRecord(fieldCount)
r.state.fieldPositions = r.ensureFieldPositionsCapacity(fieldCount)
fields := r.getFieldsForRow(row, fieldCount)
if len(fields) == 0 {
return record
}
buf := r.state.rawBuffer
bufLen := uint32(len(buf))
// Calculate row span in buffer
rowStart := fields[0].rawStart()
rowEnd := fields[len(fields)-1].rawEnd()
// Handle out-of-bounds row
if rowStart >= bufLen {
for i, field := range fields {
record[i] = ""
r.state.fieldPositions[i] = position{line: row.lineNum, column: int(field.rawStart()) + 1}
}
return record
}
// Clamp row bounds
rowEnd = clampUint32(rowEnd, rowStart, bufLen)
// Create row string (copy if trimming, zero-copy otherwise)
rowStr := r.createRowString(buf, rowStart, rowEnd)
rowStrLen := len(rowStr)
// Extract fields from row string
for i, field := range fields {
record[i] = r.extractFieldFromRow(buf, bufLen, rowStr, rowStrLen, rowStart, field)
r.state.fieldPositions[i] = position{line: row.lineNum, column: int(field.rawStart()) + 1}
}
return record
}
// clampUint32 clamps value to [minVal, maxVal].
func clampUint32(value, minVal, maxVal uint32) uint32 {
if value < minVal {
return minVal
}
if value > maxVal {
return maxVal
}
return value
}
// createRowString creates a string for the row span.
// Copies when TrimLeadingSpace is enabled; zero-copy otherwise.
func (r *Reader) createRowString(buf []byte, rowStart, rowEnd uint32) string {
if r.TrimLeadingSpace {
return string(buf[rowStart:rowEnd])
}
return unsafe.String(&buf[rowStart], int(rowEnd-rowStart))
}
// extractFieldFromRow extracts a field string from the row string.
func (r *Reader) extractFieldFromRow(buf []byte, bufLen uint32, rowStr string, rowStrLen int, rowStart uint32, field fieldInfo) string {
start := field.start
end := start + field.length
// Apply trimming if needed
if r.TrimLeadingSpace && start < bufLen && start < end {
trimEnd := end
if trimEnd > bufLen {
trimEnd = bufLen
}
for start < trimEnd && (buf[start] == ' ' || buf[start] == '\t') {
start++
}
}
// Calculate relative positions in row string
relStart := clampInt(int(start)-int(rowStart), 0, rowStrLen)
relEnd := clampInt(int(end)-int(rowStart), relStart, rowStrLen)
return rowStr[relStart:relEnd]
}
// clampInt clamps value to [minVal, maxVal].
func clampInt(value, minVal, maxVal int) int {
if value < minVal {
return minVal
}
if value > maxVal {
return maxVal
}
return value
}
// getFieldsForRow extracts the slice of fieldInfo for the given row.
func (r *Reader) getFieldsForRow(row rowInfo, fieldCount int) []fieldInfo {
endIdx := row.firstField + fieldCount
if endIdx > len(r.state.parseResult.fields) {
endIdx = len(r.state.parseResult.fields)
}
return r.state.parseResult.fields[row.firstField:endIdx]
}
// processField handles a single field: appends content and records metadata.
func (r *Reader) processField(field fieldInfo, fieldIdx, lineNum int) {
rawStart, rawEnd := uint64(field.rawStart()), uint64(field.rawEnd())
r.appendFieldContent(field, rawStart, rawEnd)
r.state.fieldEnds = append(r.state.fieldEnds, len(r.state.recordBuffer))
r.state.fieldPositions[fieldIdx] = position{
line: lineNum,
column: int(rawStart) + 1, //nolint:gosec // G115: rawStart bounded by buffer size
}
}
// ============================================================================
// Quote Validation
// ============================================================================
// validateFieldIfNeeded validates field quotes when LazyQuotes is disabled and quotes exist.
func (r *Reader) validateFieldIfNeeded(field fieldInfo, lineNum int) error {
if r.LazyQuotes || !r.state.hasQuotes {
return nil
}
// Fast path: field doesn't contain any quotes (set during parsing)
if !field.containsQuote() {
return nil
}
rawStart, rawEnd := uint64(field.rawStart()), uint64(field.rawEnd())
return r.validateFieldQuotesWithField(field, rawStart, rawEnd, lineNum)
}
// ============================================================================
// Record Building - Output Construction
// ============================================================================
// buildFinalRecord converts the accumulated buffer into a []string record.
func (r *Reader) buildFinalRecord(fieldCount int) []string {
str := string(r.state.recordBuffer)
record := r.allocateRecord(fieldCount)
prevEnd := 0
for i, end := range r.state.fieldEnds {
record[i] = str[prevEnd:end]
prevEnd = end
}
return record
}
// buildPartialRecord creates a record from accumulated content up to errorFieldIdx.
func (r *Reader) buildPartialRecord(errorFieldIdx int) []string {
if errorFieldIdx == 0 || len(r.state.fieldEnds) == 0 {
return r.allocateRecord(errorFieldIdx)
}
str := string(r.state.recordBuffer)
record := r.allocateRecord(errorFieldIdx)
prevEnd := 0
for i := 0; i < errorFieldIdx && i < len(r.state.fieldEnds); i++ {
record[i] = str[prevEnd:r.state.fieldEnds[i]]
prevEnd = r.state.fieldEnds[i]
}
return record
}
// ============================================================================
// Field Content Transformation Pipeline
// ============================================================================
// appendFieldContent appends field content to recordBuffer with inline unescape and CRLF handling.
func (r *Reader) appendFieldContent(field fieldInfo, rawStart, rawEnd uint64) {
// Fast path: no quotes in entire input means no unescape/CRLF handling needed.
// CRLF inside fields only occurs in quoted fields, so hasQuotes=false implies no field-internal CRLF.
if !r.state.hasQuotes {
r.appendSimpleContent(field)
return
}
// Handle TrimLeadingSpace for quoted fields with leading whitespace.
if r.TrimLeadingSpace && r.tryAppendTrimmedQuotedField(rawStart) {
return
}
// Get content with optional trimming
content := r.getFieldContentWithTrim(field)
// Fast path: no transformation needed
if !r.needsContentTransform(field, content) {
r.state.recordBuffer = append(r.state.recordBuffer, content...)
return
}
// Slow path: apply unescape and CRLF normalization
r.appendContentWithTransform(content)
}
// appendSimpleContent appends field content without any transformation.
func (r *Reader) appendSimpleContent(field fieldInfo) {
content := r.getFieldContent(field)
if r.TrimLeadingSpace {
content = trimLeftBytes(content)
}
r.state.recordBuffer = append(r.state.recordBuffer, content...)
}
// tryAppendTrimmedQuotedField handles TrimLeadingSpace for quoted fields.
// Returns true if the field was processed, false if standard processing should continue.
func (r *Reader) tryAppendTrimmedQuotedField(rawStart uint64) bool {
if rawStart >= uint64(len(r.state.rawBuffer)) {
return false
}
raw := r.state.rawBuffer[rawStart:]
isQuoted, quoteOffset := isQuotedFieldStart(raw, true)
if !isQuoted || quoteOffset == 0 {
return false
}
quotedData := raw[quoteOffset:]
closingQuoteIdx := findClosingQuote(quotedData, 1)
if closingQuoteIdx <= 0 {
return false
}
content := quotedData[1:closingQuoteIdx]
r.appendContentWithTransform(content)
return true
}
// getFieldContentWithTrim returns field content with optional leading space trimming.
func (r *Reader) getFieldContentWithTrim(field fieldInfo) []byte {
content := r.getFieldContent(field)
if r.TrimLeadingSpace {
content = trimLeftBytes(content)
}
return content
}
// needsContentTransform determines if content requires unescape or CRLF normalization.
func (r *Reader) needsContentTransform(field fieldInfo, content []byte) bool {
if field.needsUnescape() {
return true
}
isQuoted := field.flags&fieldFlagIsQuoted != 0
hasCRLF := isQuoted && r.state.hasCR && containsCRLFBytes(content)
return hasCRLF
}
// ============================================================================
// Content Transformation - Unescape and CRLF Normalization
// ============================================================================
// appendContentWithTransform appends content with inline double-quote unescape and CRLF normalization.
func (r *Reader) appendContentWithTransform(content []byte) {
for i := 0; i < len(content); i++ {
b := content[i]
// Check for escaped quote: "" -> "
if b == '"' && i+1 < len(content) && content[i+1] == '"' {
r.state.recordBuffer = append(r.state.recordBuffer, '"')
i++ // skip next quote
continue
}
// Check for CRLF: \r\n -> \n
if b == '\r' && i+1 < len(content) && content[i+1] == '\n' {
r.state.recordBuffer = append(r.state.recordBuffer, '\n')
i++ // skip \n
continue
}
r.state.recordBuffer = append(r.state.recordBuffer, b)
}
}
// ============================================================================
// Field Content Extraction
// ============================================================================
// getFieldContent returns the raw field content bytes.
func (r *Reader) getFieldContent(field fieldInfo) []byte {
if field.length == 0 {
return nil
}
end := field.start + field.length
bufLen := uint32(len(r.state.rawBuffer))
if end > bufLen {
end = bufLen
}
if field.start >= bufLen {
return nil
}
return r.state.rawBuffer[field.start:end]
}
// ============================================================================
// Utility Functions
// ============================================================================
// trimLeftBytes trims leading spaces and tabs from byte slice.
func trimLeftBytes(b []byte) []byte {
for len(b) > 0 && (b[0] == ' ' || b[0] == '\t') {
b = b[1:]
}
return b
}
// containsCRLFBytes checks if byte slice contains CRLF sequence.
func containsCRLFBytes(b []byte) bool {
return bytes.Contains(b, []byte("\r\n"))
}
// ============================================================================
// Record Allocation
// ============================================================================
// allocateRecord returns a record slice, reusing the previous one if ReuseRecord is enabled.
func (r *Reader) allocateRecord(fieldCount int) []string {
if r.ReuseRecord && cap(r.state.lastRecord) >= fieldCount {
r.state.lastRecord = r.state.lastRecord[:fieldCount]
return r.state.lastRecord
}
record := make([]string, fieldCount)
if r.ReuseRecord {
r.state.lastRecord = record
}
return record
}
// ============================================================================
// Buffer Management
// ============================================================================
// prepareBuffers initializes recordBuffer, fieldEnds, and fieldPositions for a row.
func (r *Reader) prepareBuffers(row rowInfo, fieldCount int) {
r.state.recordBuffer = r.estimateAndPrepareRecordBuffer(row, fieldCount)
r.state.fieldEnds = r.ensureFieldEndsCapacity(fieldCount)
r.state.fieldPositions = r.ensureFieldPositionsCapacity(fieldCount)
}
// estimateAndPrepareRecordBuffer estimates row length and prepares the buffer.
func (r *Reader) estimateAndPrepareRecordBuffer(row rowInfo, fieldCount int) []byte {
if fieldCount == 0 || row.firstField >= len(r.state.parseResult.fields) {
return r.state.recordBuffer[:0]
}
lastFieldIdx := row.firstField + fieldCount - 1
if lastFieldIdx >= len(r.state.parseResult.fields) {
return r.state.recordBuffer[:0]
}
firstField := r.state.parseResult.fields[row.firstField]
lastField := r.state.parseResult.fields[lastFieldIdx]
rowRawLen := int(lastField.rawEnd() - firstField.rawStart())
return r.ensureRecordBufferCapacity(rowRawLen)
}
// growCapacity calculates new capacity with exponential growth (2x current).
func growCapacity(current, required, minimum int) int {
newCap := current * 2
if newCap < minimum {
newCap = minimum
}
if newCap < required {
newCap = required
}
return newCap
}
// ensureRecordBufferCapacity ensures recordBuffer has at least the required capacity.
// Returns the buffer reset to zero length.
func (r *Reader) ensureRecordBufferCapacity(required int) []byte {
if cap(r.state.recordBuffer) >= required {
return r.state.recordBuffer[:0]
}
r.state.recordBuffer = make([]byte, 0, growCapacity(cap(r.state.recordBuffer), required, minRecordBufferSize))
return r.state.recordBuffer
}
// ensureFieldEndsCapacity ensures fieldEnds has at least the required capacity.
// Returns the slice reset to zero length.
func (r *Reader) ensureFieldEndsCapacity(required int) []int {
if cap(r.state.fieldEnds) >= required {
return r.state.fieldEnds[:0]
}
r.state.fieldEnds = make([]int, 0, growCapacity(cap(r.state.fieldEnds), required, minFieldEndsSize))
return r.state.fieldEnds
}
// ensureFieldPositionsCapacity ensures fieldPositions has at least the required capacity.
// Returns the slice with length set to required.
func (r *Reader) ensureFieldPositionsCapacity(required int) []position {
if cap(r.state.fieldPositions) >= required {
return r.state.fieldPositions[:required]
}
r.state.fieldPositions = make([]position, required, growCapacity(cap(r.state.fieldPositions), required, minFieldPositionsSize))
return r.state.fieldPositions
}