summaryrefslogtreecommitdiff
path: root/ThirdParty/CsvHelper-master/src/CsvHelper/CsvParser.cs
blob: 6d0db59c1993e609b40a96427af95d509bcf305a (plain)
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
// Copyright 2009-2022 Josh Close
// This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0.
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0.
// https://github.com/JoshClose/CsvHelper
using CsvHelper.Configuration;
using CsvHelper.Delegates;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CsvHelper
{
	/// <summary>
	/// Parses a CSV file.
	/// </summary>
	public class CsvParser : IParser, IDisposable
	{
		private readonly IParserConfiguration configuration;
		private readonly FieldCache fieldCache = new FieldCache();
		private readonly TextReader reader;
		private readonly char quote;
		private readonly char escape;
		private readonly bool countBytes;
		private readonly Encoding encoding;
		private readonly bool ignoreBlankLines;
		private readonly char comment;
		private readonly bool allowComments;
		private readonly BadDataFound badDataFound;
		private readonly bool lineBreakInQuotedFieldIsBadData;
		private readonly TrimOptions trimOptions;
		private readonly char[] whiteSpaceChars;
		private readonly bool leaveOpen;
		private readonly CsvMode mode;
		private readonly string newLine;
		private readonly char newLineFirstChar;
		private readonly bool isNewLineSet;
		private readonly bool cacheFields;
		private readonly string[] delimiterValues;
		private readonly bool detectDelimiter;
		private readonly double maxFieldSize;

		private string delimiter;
		private char delimiterFirstChar;
		private char[] buffer;
		private int bufferSize;
		private int charsRead;
		private int bufferPosition;
		private int rowStartPosition;
		private int fieldStartPosition;
		private int row;
		private int rawRow;
		private long charCount;
		private long byteCount;
		private bool inQuotes;
		private bool inEscape;
		private Field[] fields;
		private string[] processedFields;
		private int fieldsPosition;
		private bool disposed;
		private int quoteCount;
		private char[] processFieldBuffer;
		private int processFieldBufferSize;
		private ParserState state;
		private int delimiterPosition = 1;
		private int newLinePosition = 1;
		private bool fieldIsBadData;
		private bool fieldIsQuoted;
		private bool isProcessingField;
		private bool isRecordProcessed;
		private string[]? record;

		/// <inheritdoc/>
		public long CharCount => charCount;

		/// <inheritdoc/>
		public long ByteCount => byteCount;

		/// <inheritdoc/>
		public int Row => row;

		/// <inheritdoc/>
		public string[]? Record
		{
			get
			{
				if (isRecordProcessed == true)
				{
					return this.record;
				}

				if (fieldsPosition == 0)
				{
					return null;
				}

				var record = new string[fieldsPosition];

				for (var i = 0; i < record.Length; i++)
				{
					record[i] = this[i];
				}

				this.record = record;
				isRecordProcessed = true;

				return this.record;
			}
		}

		/// <inheritdoc/>
		public string RawRecord => new string(buffer, rowStartPosition, bufferPosition - rowStartPosition);

		/// <inheritdoc/>
		public int Count => fieldsPosition;

		/// <inheritdoc/>
		public int RawRow => rawRow;

		/// <inheritdoc/>
		public string Delimiter => delimiter;

		/// <inheritdoc/>
		public CsvContext Context { get; private set; }

		/// <inheritdoc/>
		public IParserConfiguration Configuration => configuration;

		/// <inheritdoc/>
		public string this[int index]
		{
			get
			{
				if (isProcessingField)
				{
					var message =
						$"You can't access {nameof(IParser)}[int] or {nameof(IParser)}.{nameof(IParser.Record)} inside of the {nameof(BadDataFound)} callback. " +
						$"Use {nameof(BadDataFoundArgs)}.{nameof(BadDataFoundArgs.Field)} and {nameof(BadDataFoundArgs)}.{nameof(BadDataFoundArgs.RawRecord)} instead."
					;

					throw new ParserException(Context, message);
				}

				isProcessingField = true;

				var field = GetField(index);

				isProcessingField = false;

				return field;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="CsvParser"/> class.
		/// </summary>
		/// <param name="reader">The reader.</param>
		/// <param name="culture">The culture.</param>
		/// <param name="leaveOpen">if set to <c>true</c> [leave open].</param>
		public CsvParser(TextReader reader, CultureInfo culture, bool leaveOpen = false) : this(reader, new CsvConfiguration(culture), leaveOpen) { }

		/// <summary>
		/// Initializes a new instance of the <see cref="CsvParser"/> class.
		/// </summary>
		/// <param name="reader">The reader.</param>
		/// <param name="configuration">The configuration.</param>
		/// <param name="leaveOpen">if set to <c>true</c> [leave open].</param>
		public CsvParser(TextReader reader, IParserConfiguration configuration, bool leaveOpen = false)
		{
			this.reader = reader ?? throw new ArgumentNullException(nameof(reader));
			this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

			configuration.Validate();

			Context = new CsvContext(this);

			allowComments = configuration.AllowComments;
			badDataFound = configuration.BadDataFound;
			bufferSize = configuration.BufferSize;
			cacheFields = configuration.CacheFields;
			comment = configuration.Comment;
			countBytes = configuration.CountBytes;
			delimiter = configuration.Delimiter;
			delimiterFirstChar = configuration.Delimiter[0];
			delimiterValues = configuration.DetectDelimiterValues;
			detectDelimiter = configuration.DetectDelimiter;
			encoding = configuration.Encoding;
			escape = configuration.Escape;
			ignoreBlankLines = configuration.IgnoreBlankLines;
			isNewLineSet = configuration.IsNewLineSet;
			this.leaveOpen = leaveOpen;
			lineBreakInQuotedFieldIsBadData = configuration.LineBreakInQuotedFieldIsBadData;
			maxFieldSize = configuration.MaxFieldSize;
			newLine = configuration.NewLine;
			newLineFirstChar = configuration.NewLine[0];
			mode = configuration.Mode;
			processFieldBufferSize = configuration.ProcessFieldBufferSize;
			quote = configuration.Quote;
			whiteSpaceChars = configuration.WhiteSpaceChars;
			trimOptions = configuration.TrimOptions;

			buffer = new char[bufferSize];
			processFieldBuffer = new char[processFieldBufferSize];
			fields = new Field[128];
			processedFields = new string[128];
		}

		/// <inheritdoc/>
		public bool Read()
		{
			isRecordProcessed = false;
			rowStartPosition = bufferPosition;
			fieldStartPosition = rowStartPosition;
			fieldsPosition = 0;
			quoteCount = 0;
			row++;
			rawRow++;
			var c = '\0';
			var cPrev = c;

			while (true)
			{
				if (bufferPosition >= charsRead)
				{
					if (!FillBuffer())
					{
						return ReadEndOfFile();
					}

					if (row == 1 && detectDelimiter)
					{
						DetectDelimiter();
					}
				}

				if (ReadLine(ref c, ref cPrev) == ReadLineResult.Complete)
				{
					return true;
				}
			}
		}

		/// <inheritdoc/>
		public async Task<bool> ReadAsync()
		{
			isRecordProcessed = false;
			rowStartPosition = bufferPosition;
			fieldStartPosition = rowStartPosition;
			fieldsPosition = 0;
			quoteCount = 0;
			row++;
			rawRow++;
			var c = '\0';
			var cPrev = c;

			while (true)
			{
				if (bufferPosition >= charsRead)
				{
					if (!await FillBufferAsync().ConfigureAwait(false))
					{
						return ReadEndOfFile();
					}

					if (row == 1 && detectDelimiter)
					{
						DetectDelimiter();
					}
				}

				if (ReadLine(ref c, ref cPrev) == ReadLineResult.Complete)
				{
					return true;
				}
			}
		}

		private void DetectDelimiter()
		{
			var text = new string(buffer, 0, charsRead);
			var newDelimiter = configuration.GetDelimiter(new GetDelimiterArgs(text, configuration));
			if (newDelimiter != null)
			{
				delimiter = newDelimiter;
				delimiterFirstChar = newDelimiter[0];
				configuration.Validate();
			}
		}

		private ReadLineResult ReadLine(ref char c, ref char cPrev)
		{
			while (bufferPosition < charsRead)
			{
				if (state != ParserState.None)
				{
					// Continue the state before doing anything else.
					ReadLineResult result;
					switch (state)
					{
						case ParserState.Spaces:
							result = ReadSpaces(ref c);
							break;
						case ParserState.BlankLine:
							result = ReadBlankLine(ref c);
							break;
						case ParserState.Delimiter:
							result = ReadDelimiter(ref c);
							break;
						case ParserState.LineEnding:
							result = ReadLineEnding(ref c);
							break;
						case ParserState.NewLine:
							result = ReadNewLine(ref c);
							break;
						default:
							throw new InvalidOperationException($"Parser state '{state}' is not valid.");
					}

					var shouldReturn =
						// Buffer needs to be filled.
						result == ReadLineResult.Incomplete ||
						// Done reading row.
						result == ReadLineResult.Complete && (state == ParserState.LineEnding || state == ParserState.NewLine)
					;

					if (result == ReadLineResult.Complete)
					{
						state = ParserState.None;
					}

					if (shouldReturn)
					{
						return result;
					}
				}

				cPrev = c;
				c = buffer[bufferPosition];
				bufferPosition++;
				charCount++;

				if (countBytes)
				{
					byteCount += encoding.GetByteCount(new char[] { c });
				}

				if (maxFieldSize > 0 && bufferPosition - fieldStartPosition - 1 > maxFieldSize)
				{
					throw new MaxFieldSizeException(Context);
				}

				var isFirstCharOfRow = rowStartPosition == bufferPosition - 1;
				if (isFirstCharOfRow && (allowComments && c == comment || ignoreBlankLines && ((c == '\r' || c == '\n') && !isNewLineSet || c == newLineFirstChar && isNewLineSet)))
				{
					state = ParserState.BlankLine;
					var result = ReadBlankLine(ref c);
					if (result == ReadLineResult.Complete)
					{
						state = ParserState.None;

						continue;
					}
					else
					{
						return ReadLineResult.Incomplete;
					}
				}

				if (mode == CsvMode.RFC4180)
				{
					var isFirstCharOfField = fieldStartPosition == bufferPosition - 1;
					if (isFirstCharOfField)
					{
						if ((trimOptions & TrimOptions.Trim) == TrimOptions.Trim && ArrayHelper.Contains(whiteSpaceChars, c))
						{
							// Skip through whitespace. This is so we can process the field later.
							var result = ReadSpaces(ref c);
							if (result == ReadLineResult.Incomplete)
							{
								fieldStartPosition = bufferPosition;
								return result;
							}
						}

						// Fields are only quoted if the first character is a quote.
						// If not, read until a delimiter or newline is found.
						fieldIsQuoted = c == quote;
					}

					if (fieldIsQuoted)
					{
						if (c == quote || c == escape)
						{
							quoteCount++;

							if (!inQuotes && !isFirstCharOfField && cPrev != escape)
							{
								fieldIsBadData = true;
							}
							else if (!fieldIsBadData)
							{
								// Don't process field quotes after bad data has been detected.
								inQuotes = !inQuotes;
							}
						}

						if (inQuotes)
						{
							if (c == '\r' || c == '\n' && cPrev != '\r')
							{
								rawRow++;
							}

							// We don't care about anything else if we're in quotes.
							continue;
						}
					}
					else
					{
						if (c == quote || c == escape)
						{
							// If the field isn't quoted but contains a
							// quote or escape, it's has bad data.
							fieldIsBadData = true;
						}
					}
				}
				else if (mode == CsvMode.Escape)
				{
					if (inEscape)
					{
						inEscape = false;

						continue;
					}

					if (c == escape)
					{
						inEscape = true;

						continue;
					}
				}

				if (c == delimiterFirstChar)
				{
					state = ParserState.Delimiter;
					var result = ReadDelimiter(ref c);
					if (result == ReadLineResult.Incomplete)
					{
						return result;
					}

					state = ParserState.None;

					continue;
				}

				if (!isNewLineSet && (c == '\r' || c == '\n'))
				{
					state = ParserState.LineEnding;
					var result = ReadLineEnding(ref c);
					if (result == ReadLineResult.Complete)
					{
						state = ParserState.None;
					}

					return result;
				}

				if (isNewLineSet && c == newLineFirstChar)
				{
					state = ParserState.NewLine;
					var result = ReadNewLine(ref c);
					if (result == ReadLineResult.Complete)
					{
						state = ParserState.None;
					}

					return result;
				}
			}

			return ReadLineResult.Incomplete;
		}

		private ReadLineResult ReadSpaces(ref char c)
		{
			while (ArrayHelper.Contains(whiteSpaceChars, c))
			{
				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}

				c = buffer[bufferPosition];
				bufferPosition++;
				charCount++;
				if (countBytes)
				{
					byteCount += encoding.GetByteCount(new char[] { c });
				}
			}

			return ReadLineResult.Complete;
		}

		private ReadLineResult ReadBlankLine(ref char c)
		{
			while (bufferPosition < charsRead)
			{
				if (c == '\r' || c == '\n')
				{
					var result = ReadLineEnding(ref c);
					if (result == ReadLineResult.Complete)
					{
						rowStartPosition = bufferPosition;
						fieldStartPosition = rowStartPosition;
						row++;
						rawRow++;
					}

					return result;
				}

				c = buffer[bufferPosition];
				bufferPosition++;
				charCount++;
				if (countBytes)
				{
					byteCount += encoding.GetByteCount(new char[] { c });
				}
			}

			return ReadLineResult.Incomplete;
		}

		private ReadLineResult ReadDelimiter(ref char c)
		{
			for (var i = delimiterPosition; i < delimiter.Length; i++)
			{
				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}

				delimiterPosition++;

				c = buffer[bufferPosition];
				if (c != delimiter[i])
				{
					c = buffer[bufferPosition - 1];
					delimiterPosition = 1;

					return ReadLineResult.Complete;
				}

				bufferPosition++;
				charCount++;
				if (countBytes)
				{
					byteCount += encoding.GetByteCount(new[] { c });
				}

				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}
			}

			AddField(fieldStartPosition, bufferPosition - fieldStartPosition - delimiter.Length);

			fieldStartPosition = bufferPosition;
			delimiterPosition = 1;
			fieldIsBadData = false;

			return ReadLineResult.Complete;
		}

		private ReadLineResult ReadLineEnding(ref char c)
		{
			var lessChars = 1;

			if (c == '\r')
			{
				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}

				c = buffer[bufferPosition];

				if (c == '\n')
				{
					lessChars++;
					bufferPosition++;
					charCount++;
					if (countBytes)
					{
						byteCount += encoding.GetByteCount(new char[] { c });
					}
				}
			}

			if (state == ParserState.LineEnding)
			{
				AddField(fieldStartPosition, bufferPosition - fieldStartPosition - lessChars);
			}

			fieldIsBadData = false;

			return ReadLineResult.Complete;
		}

		private ReadLineResult ReadNewLine(ref char c)
		{
			for (var i = newLinePosition; i < newLine.Length; i++)
			{
				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}

				newLinePosition++;

				c = buffer[bufferPosition];
				if (c != newLine[i])
				{
					c = buffer[bufferPosition - 1];
					newLinePosition = 1;

					return ReadLineResult.Complete;
				}

				bufferPosition++;
				charCount++;
				if (countBytes)
				{
					byteCount += encoding.GetByteCount(new[] { c });
				}

				if (bufferPosition >= charsRead)
				{
					return ReadLineResult.Incomplete;
				}
			}

			AddField(fieldStartPosition, bufferPosition - fieldStartPosition - newLine.Length);

			fieldStartPosition = bufferPosition;
			newLinePosition = 1;
			fieldIsBadData = false;

			return ReadLineResult.Complete;
		}

		private bool ReadEndOfFile()
		{
			var state = this.state;
			this.state = ParserState.None;

			if (state == ParserState.BlankLine)
			{
				return false;
			}

			if (state == ParserState.Delimiter)
			{
				AddField(fieldStartPosition, bufferPosition - fieldStartPosition - delimiter.Length);

				fieldStartPosition = bufferPosition;

				AddField(fieldStartPosition, bufferPosition - fieldStartPosition);

				return true;
			}

			if (state == ParserState.LineEnding)
			{
				AddField(fieldStartPosition, bufferPosition - fieldStartPosition - 1);

				return true;
			}

			if (state == ParserState.NewLine)
			{
				AddField(fieldStartPosition, bufferPosition - fieldStartPosition - newLine.Length);

				return true;
			}

			if (rowStartPosition < bufferPosition)
			{
				AddField(fieldStartPosition, bufferPosition - fieldStartPosition);
			}

			return fieldsPosition > 0;
		}

		private void AddField(int start, int length)
		{
			if (fieldsPosition >= fields.Length)
			{
				var newSize = fields.Length * 2;
				Array.Resize(ref fields, newSize);
				Array.Resize(ref processedFields, newSize);
			}

			ref var field = ref fields[fieldsPosition];
			field.Start = start - rowStartPosition;
			field.Length = length;
			field.QuoteCount = quoteCount;
			field.IsBad = fieldIsBadData;
			field.IsProcessed = false;

			fieldsPosition++;
			quoteCount = 0;
		}

		private bool FillBuffer()
		{
			// Don't forget the async method below.

			if (rowStartPosition == 0 && charCount > 0 && charsRead == bufferSize)
			{
				// The record is longer than the memory buffer. Increase the buffer.
				bufferSize *= 2;
				var tempBuffer = new char[bufferSize];
				buffer.CopyTo(tempBuffer, 0);
				buffer = tempBuffer;
			}

			var charsLeft = Math.Max(charsRead - rowStartPosition, 0);

			Array.Copy(buffer, rowStartPosition, buffer, 0, charsLeft);

			fieldStartPosition -= rowStartPosition;
			rowStartPosition = 0;
			bufferPosition = charsLeft;

			charsRead = reader.Read(buffer, charsLeft, buffer.Length - charsLeft);
			if (charsRead == 0)
			{
				return false;
			}

			charsRead += charsLeft;

			return true;
		}

		private async Task<bool> FillBufferAsync()
		{
			if (rowStartPosition == 0 && charCount > 0 && charsRead == bufferSize)
			{
				// The record is longer than the memory buffer. Increase the buffer.
				bufferSize *= 2;
				var tempBuffer = new char[bufferSize];
				buffer.CopyTo(tempBuffer, 0);
				buffer = tempBuffer;
			}

			var charsLeft = Math.Max(charsRead - rowStartPosition, 0);

			Array.Copy(buffer, rowStartPosition, buffer, 0, charsLeft);

			fieldStartPosition -= rowStartPosition;
			rowStartPosition = 0;
			bufferPosition = charsLeft;

			charsRead = await reader.ReadAsync(buffer, charsLeft, buffer.Length - charsLeft).ConfigureAwait(false);
			if (charsRead == 0)
			{
				return false;
			}

			charsRead += charsLeft;

			return true;
		}

		private string GetField(int index)
		{
			if (index > fieldsPosition)
			{
				throw new IndexOutOfRangeException();
			}

			ref var field = ref fields[index];

			if (field.Length == 0)
			{
				return string.Empty;
			}

			if (field.IsProcessed)
			{
				return processedFields[index];
			}

			var start = field.Start + rowStartPosition;
			var length = field.Length;
			var quoteCount = field.QuoteCount;

			ProcessedField processedField;
			switch (mode)
			{
				case CsvMode.RFC4180:
					processedField = field.IsBad
						? ProcessRFC4180BadField(start, length)
						: ProcessRFC4180Field(start, length, quoteCount);
					break;
				case CsvMode.Escape:
					processedField = ProcessEscapeField(start, length);
					break;
				case CsvMode.NoEscape:
					processedField = ProcessNoEscapeField(start, length);
					break;
				default:
					throw new InvalidOperationException($"ParseMode '{mode}' is not handled.");
			}

			var value = cacheFields
				? fieldCache.GetField(processedField.Buffer, processedField.Start, processedField.Length)
				: new string(processedField.Buffer, processedField.Start, processedField.Length);

			processedFields[index] = value;
			field.IsProcessed = true;

			return value;
		}

		/// <summary>
		/// Processes a field that complies with RFC4180.
		/// </summary>
		/// <param name="start">The start index of the field.</param>
		/// <param name="length">The length of the field.</param>
		/// <param name="quoteCount">The number of counted quotes.</param>
		/// <returns>The processed field.</returns>
		protected ProcessedField ProcessRFC4180Field(int start, int length, int quoteCount)
		{
			var newStart = start;
			var newLength = length;

			if ((trimOptions & TrimOptions.Trim) == TrimOptions.Trim)
			{
				ArrayHelper.Trim(buffer, ref newStart, ref newLength, whiteSpaceChars);
			}

			if (quoteCount == 0)
			{
				// Not quoted.
				// No processing needed.

				return new ProcessedField(newStart, newLength, buffer);
			}

			if (buffer[newStart] != quote || buffer[newStart + newLength - 1] != quote || newLength == 1 && buffer[newStart] == quote)
			{
				// If the field doesn't have quotes on the ends, or the field is a single quote char, it's bad data.
				return ProcessRFC4180BadField(start, length);
			}

			if (lineBreakInQuotedFieldIsBadData)
			{
				for (var i = newStart; i < newStart + newLength; i++)
				{
					if (buffer[i] == '\r' || buffer[i] == '\n')
					{
						return ProcessRFC4180BadField(start, length);
					}
				}
			}

			// Remove the quotes from the ends.
			newStart += 1;
			newLength -= 2;

			if ((trimOptions & TrimOptions.InsideQuotes) == TrimOptions.InsideQuotes)
			{
				ArrayHelper.Trim(buffer, ref newStart, ref newLength, whiteSpaceChars);
			}

			if (quoteCount == 2)
			{
				// The only quotes are the ends of the field.
				// No more processing is needed.
				return new ProcessedField(newStart, newLength, buffer);
			}

			if (newLength > processFieldBuffer.Length)
			{
				// Make sure the field processing buffer is large engough.
				while (newLength > processFieldBufferSize)
				{
					processFieldBufferSize *= 2;
				}

				processFieldBuffer = new char[processFieldBufferSize];
			}

			// Remove escapes.
			var inEscape = false;
			var position = 0;
			for (var i = newStart; i < newStart + newLength; i++)
			{
				var c = buffer[i];

				if (inEscape)
				{
					inEscape = false;
				}
				else if (c == escape)
				{
					inEscape = true;

					continue;
				}

				processFieldBuffer[position] = c;
				position++;
			}

			return new ProcessedField(0, position, processFieldBuffer);
		}

		/// <summary>
		/// Processes a field that does not comply with RFC4180.
		/// </summary>
		/// <param name="start">The start index of the field.</param>
		/// <param name="length">The length of the field.</param>
		/// <returns>The processed field.</returns>
		protected ProcessedField ProcessRFC4180BadField(int start, int length)
		{
			// If field is already known to be bad, different rules can be applied.

			var args = new BadDataFoundArgs(new string(buffer, start, length), RawRecord, Context);
			badDataFound?.Invoke(args);

			var newStart = start;
			var newLength = length;

			if ((trimOptions & TrimOptions.Trim) == TrimOptions.Trim)
			{
				ArrayHelper.Trim(buffer, ref newStart, ref newLength, whiteSpaceChars);
			}

			if (buffer[newStart] != quote)
			{
				// If the field doesn't start with a quote, don't process it.
				return new ProcessedField(newStart, newLength, buffer);
			}

			if (newLength > processFieldBuffer.Length)
			{
				// Make sure the field processing buffer is large engough.
				while (newLength > processFieldBufferSize)
				{
					processFieldBufferSize *= 2;
				}

				processFieldBuffer = new char[processFieldBufferSize];
			}

			// Remove escapes until the last quote is found.
			var inEscape = false;
			var position = 0;
			var c = '\0';
			var doneProcessing = false;
			for (var i = newStart + 1; i < newStart + newLength; i++)
			{
				var cPrev = c;
				c = buffer[i];

				// a,"b",c
				// a,"b "" c",d
				// a,"b "c d",e

				if (inEscape)
				{
					inEscape = false;

					if (c == quote)
					{
						// Ignore the quote after an escape.
						continue;
					}
					else if (cPrev == quote)
					{
						// The escape and quote are the same character.
						// This is the end of the field.
						// Don't process escapes for the rest of the field.
						doneProcessing = true;
					}
				}

				if (c == escape && !doneProcessing)
				{
					inEscape = true;

					continue;
				}

				processFieldBuffer[position] = c;
				position++;
			}

			return new ProcessedField(0, position, processFieldBuffer);
		}

		/// <summary>
		/// Processes an escaped field.
		/// </summary>
		/// <param name="start">The start index of the field.</param>
		/// <param name="length">The length of the field.</param>
		/// <returns>The processed field.</returns>
		protected ProcessedField ProcessEscapeField(int start, int length)
		{
			var newStart = start;
			var newLength = length;

			if ((trimOptions & TrimOptions.Trim) == TrimOptions.Trim)
			{
				ArrayHelper.Trim(buffer, ref newStart, ref newLength, whiteSpaceChars);
			}

			if (newLength > processFieldBuffer.Length)
			{
				// Make sure the field processing buffer is large engough.
				while (newLength > processFieldBufferSize)
				{
					processFieldBufferSize *= 2;
				}

				processFieldBuffer = new char[processFieldBufferSize];
			}

			// Remove escapes.
			var inEscape = false;
			var position = 0;
			for (var i = newStart; i < newStart + newLength; i++)
			{
				var c = buffer[i];

				if (inEscape)
				{
					inEscape = false;
				}
				else if (c == escape)
				{
					inEscape = true;
					continue;
				}

				processFieldBuffer[position] = c;
				position++;
			}

			return new ProcessedField(0, position, processFieldBuffer);
		}

		/// <inheritdoc/>
		/// <summary>
		/// Processes an non-escaped field.
		/// </summary>
		/// <param name="start">The start index of the field.</param>
		/// <param name="length">The length of the field.</param>
		/// <returns>The processed field.</returns>
		protected ProcessedField ProcessNoEscapeField(int start, int length)
		{
			var newStart = start;
			var newLength = length;

			if ((trimOptions & TrimOptions.Trim) == TrimOptions.Trim)
			{
				ArrayHelper.Trim(buffer, ref newStart, ref newLength, whiteSpaceChars);
			}

			return new ProcessedField(newStart, newLength, buffer);
		}

		/// <inheritdoc/>
		public void Dispose()
		{
			// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// Disposes the object.
		/// </summary>
		/// <param name="disposing">Indicates if the object is being disposed.</param>
		protected virtual void Dispose(bool disposing)
		{
			if (disposed)
			{
				return;
			}

			if (disposing)
			{
				// Dispose managed state (managed objects)

				if (!leaveOpen)
				{
					reader?.Dispose();
				}
			}

			// Free unmanaged resources (unmanaged objects) and override finalizer
			// Set large fields to null

			disposed = true;
		}

		/// <summary>
		/// Processes a raw field based on configuration.
		/// This will remove quotes, remove escapes, and trim if configured to.
		/// </summary>
		[DebuggerDisplay("Start = {Start}, Length = {Length}, Buffer.Length = {Buffer.Length}")]
		protected readonly struct ProcessedField
		{
			/// <summary>
			/// The start of the field in the buffer.
			/// </summary>
			public readonly int Start;

			/// <summary>
			/// The length of the field in the buffer.
			/// </summary>
			public readonly int Length;

			/// <summary>
			/// The buffer that contains the field.
			/// </summary>
			public readonly char[] Buffer;

			/// <summary>
			/// Creates a new instance of ProcessedField.
			/// </summary>
			/// <param name="start">The start of the field in the buffer.</param>
			/// <param name="length">The length of the field in the buffer.</param>
			/// <param name="buffer">The buffer that contains the field.</param>
			public ProcessedField(int start, int length, char[] buffer)
			{
				Start = start;
				Length = length;
				Buffer = buffer;
			}
		}

		private enum ReadLineResult
		{
			None = 0,
			Complete,
			Incomplete,
		}

		private enum ParserState
		{
			None = 0,
			Spaces,
			BlankLine,
			Delimiter,
			LineEnding,
			NewLine,
		}

		[DebuggerDisplay("Start = {Start}, Length = {Length}, QuoteCount = {QuoteCount}, IsBad = {IsBad}")]
		private struct Field
		{
			/// <summary>
			/// Starting position of the field.
			/// This is an offset from <see cref="rowStartPosition"/>.
			/// </summary>
			public int Start;

			public int Length;

			public int QuoteCount;

			public bool IsBad;

			public bool IsProcessed;
		}
	}
}