diff --git a/docs/formats.md b/docs/formats.md
index 2cf1c3d..2534b94 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -168,10 +168,14 @@ TabularOpenOptions options = new() { Csv = new CsvCursorOptions { QuoteMode = Cs
Strict mode reads quotes as RFC 4180 does. A quoted field holds any number of lines and delimiters,
bounded only by `MaxFieldChars`; a quoted field the file ends inside, and text after a closing quote
-(`"C" Road`), are refused as `format.corrupt`, the message naming the row. Whitespace before an
-opening quote and after a closing one is not part of the field, so `1, "Payroll", "monthly, HR"` is
-three values — in the default mode the quotes after a space are text, and the last value is split at
-its comma. A quote inside a field that does not start with one (`21"st AVE`) is text in both modes.
+(`"C" Road`), are refused as `format.corrupt`, the message naming the row — and, in an archive, the
+file. A quote never closed and followed by more than `MaxFieldChars` characters reaches that limit
+first and is refused as `limit.exceeded`, the message naming the row and the open quote. Whitespace before an
+opening quote and after a closing one — any whitespace a cell is trimmed of, a no-break space
+included — is not part of the field, so `1, "Payroll", "monthly, HR"` is three values; in the default
+mode the quotes after a space are text, and the last value is split at its comma. That whitespace
+counts towards `MaxFieldChars` until the quote is read, and `Quote` may not be whitespace in strict
+mode. A quote inside a field that does not start with one (`21"st AVE`) is text in both modes.
Nothing is repaired, so `Diagnostics.IsClean` stays true.
## What each format holds when written
diff --git a/src/TriasDev.Tabular/Archive/ArchiveCursor.cs b/src/TriasDev.Tabular/Archive/ArchiveCursor.cs
index 060f481..fc1b350 100644
--- a/src/TriasDev.Tabular/Archive/ArchiveCursor.cs
+++ b/src/TriasDev.Tabular/Archive/ArchiveCursor.cs
@@ -237,6 +237,12 @@ public bool ReadRow(CancellationToken cancellationToken = default)
// Raised by a zip's decompressor: the entry's data is damaged, whatever the file inside is.
throw Corrupt(e);
}
+ catch (TabularFormatException e)
+ {
+ // The file inside refused a row — a csv read strictly, a damaged workbook part. Its own
+ // message names the row but not which of the archive's files it is in.
+ throw new TabularFormatException(e.Code, $"{_sources[_innerSource].Entry.Path}: {e.Message}", e);
+ }
}
///
diff --git a/src/TriasDev.Tabular/Csv/CsvCursor.cs b/src/TriasDev.Tabular/Csv/CsvCursor.cs
index 4837805..fd30ea5 100644
--- a/src/TriasDev.Tabular/Csv/CsvCursor.cs
+++ b/src/TriasDev.Tabular/Csv/CsvCursor.cs
@@ -78,6 +78,9 @@ internal sealed class CsvCursor : ITabularCursor
private int _pendingLength;
+ /// Whether a quoted field is open in strict mode, for the message of a field that grows past the limit.
+ private bool _inStrictQuote;
+
private RawCell[] _cells = new RawCell[16];
private int _cellCount;
private int _bufferLength;
@@ -263,6 +266,7 @@ public bool ReadRow(CancellationToken cancellationToken = default)
_cellCount = 0;
_field.Clear();
_pendingStart = -1;
+ _inStrictQuote = false;
try
{
@@ -368,7 +372,10 @@ private bool ReadRowCore(CancellationToken cancellationToken)
if (inQuotes && _peeked < 0 && _pushbackPosition >= _pushback.Count && _bufferPosition < _bufferLength)
{
ReadOnlySpan ahead = _buffer.AsSpan(_bufferPosition, _bufferLength - _bufferPosition);
- int run = ahead.IndexOfAny(_specials);
+
+ // Strict mode counts nothing inside quotes, so only a quote ends its run: a long note
+ // full of commas and line breaks is taken in one search, not stopped at each of them.
+ int run = strict ? ahead.IndexOf(Dialect.Quote) : ahead.IndexOfAny(_specials);
if (run != 0)
{
@@ -539,7 +546,7 @@ private bool ReadRowCore(CancellationToken cancellationToken)
continue;
}
- EndQuotedFieldStrictly();
+ EndQuotedFieldStrictly(cancellationToken);
inQuotes = false;
continue;
}
@@ -551,6 +558,7 @@ private bool ReadRowCore(CancellationToken cancellationToken)
// three. The text is trimmed when it becomes a cell anyway, so no value changes.
_field.Clear();
_pendingStart = -1;
+ _inStrictQuote = strict;
inQuotes = true;
fieldWasQuoted = true;
@@ -597,29 +605,28 @@ private bool ReadRowCore(CancellationToken cancellationToken)
}
}
- ///
- /// Adds a character to the field being built, refusing one that grows past the ceiling.
- ///
- ///
- /// A field has no length limit in the format, and a reader that honours that has none either: one
- /// unterminated value in a modest upload is enough to spend a host's memory, since the text is
- /// held twice while a quoted field is open — once as the value and once as the raw text kept for
- /// a possible replay.
- ///
- /// Adds a run of ordinary text to the field being built, under the same ceiling.
+ /// Adds a run of ordinary text to the field being built, under the ceiling keeps.
private void AppendRunToField(ReadOnlySpan run)
{
FlushPending();
if (_field.Length + run.Length > _options.MaxFieldChars)
{
- throw new TabularLimitException(nameof(CsvCursorOptions.MaxFieldChars), _options.MaxFieldChars,
- $"A field exceeds the {_options.MaxFieldChars} characters allowed.");
+ throw FieldTooLong();
}
_field.Append(run);
}
+ ///
+ /// Adds a character to the field being built, refusing one that grows past the ceiling.
+ ///
+ ///
+ /// A field has no length limit in the format, and a reader that honours that has none either: one
+ /// unterminated value in a modest upload is enough to spend a host's memory, since the text is
+ /// held twice while a quoted field is open — once as the value and once as the raw text kept for
+ /// a possible replay.
+ ///
private void AppendToField(char c)
{
if (_pendingStart >= 0)
@@ -629,15 +636,35 @@ private void AppendToField(char c)
if (_field.Length >= _options.MaxFieldChars)
{
- throw new TabularLimitException(nameof(CsvCursorOptions.MaxFieldChars), _options.MaxFieldChars,
- $"A field exceeds the {_options.MaxFieldChars} characters allowed.");
+ throw FieldTooLong();
}
_field.Append(c);
}
- /// Whitespace that strict mode drops around a quoted field: a space, and a tab that is not the delimiter.
- private bool IsBlank(int c) => c == ' ' || (c == '\t' && Dialect.Delimiter != '\t');
+ /// The refusal of a field past , naming the row.
+ ///
+ /// In strict mode a quote that is never closed reads on to this limit — a small file ends first
+ /// and is refused as quoting, a large one ends here — so the message says what it most likely is.
+ /// It stays a limit, not a format error: a quoted field this long that would have closed later
+ /// is indistinguishable, and a host answers a limit as an upload too large.
+ ///
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private TabularLimitException FieldTooLong() => new(
+ nameof(CsvCursorOptions.MaxFieldChars),
+ _options.MaxFieldChars,
+ $"A field exceeds the {_options.MaxFieldChars} characters allowed, at row {(long)CurrentRowNumber + 1}."
+ + (_inStrictQuote
+ ? $" It is a quoted field that was never closed within that many characters: read with {nameof(CsvQuoteMode)}.{nameof(CsvQuoteMode.Strict)}, "
+ + "a quote that is never closed reads on to this limit."
+ : string.Empty));
+
+ ///
+ /// Whitespace that strict mode drops around a quoted field: what trims
+ /// from a cell anyway — a no-break space included —, except the delimiter and line endings.
+ ///
+ private bool IsBlank(int c) =>
+ c >= 0 && c != Dialect.Delimiter && c != '\r' && c != '\n' && char.IsWhiteSpace((char)c);
/// Whether the field read so far is nothing but whitespace.
///
@@ -679,13 +706,26 @@ private bool OnlyBlankSoFar()
/// After a closing quote in strict mode: drops the whitespace that follows it, and refuses
/// anything else but the end of the field.
///
+ ///
+ /// The run of whitespace has no bound of its own — nothing of it is kept — so it asks for
+ /// cancellation on the same stride the row loop does, or a file of a closing quote and a billion
+ /// spaces would hold the read beyond its token.
+ ///
[MethodImpl(MethodImplOptions.NoInlining)]
- private void EndQuotedFieldStrictly()
+ private void EndQuotedFieldStrictly(CancellationToken cancellationToken)
{
+ _inStrictQuote = false;
int next = PeekChar();
+ int skipped = 0;
while (IsBlank(next))
{
+ if (++skipped >= 64 * 1024)
+ {
+ skipped = 0;
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+
ReadChar();
next = PeekChar();
}
@@ -697,6 +737,11 @@ private void EndQuotedFieldStrictly()
}
/// The refusal of strict mode, naming the record being read.
+ ///
+ /// also for a file that ends inside a quoted field,
+ /// not : that says the upload was cut off, and a quote
+ /// left open is far more often one a person forgot than the end of a clipped file.
+ ///
[MethodImpl(MethodImplOptions.NoInlining)]
private TabularFormatException Malformed(string what) => new(
TabularFormatException.Corrupt,
diff --git a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs
index a999067..1195dd8 100644
--- a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs
+++ b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs
@@ -46,7 +46,8 @@ public sealed record CsvCursorOptions
///
/// It may not be a line ending, nor one of the delimiters the reader knows (, ; tab
/// |), since a detected delimiter could then be the quote too. Delimiter detection honours
- /// it.
+ /// it. With it may not be whitespace
+ /// either, since that mode drops whitespace around a quoted field.
///
public char? Quote { get; init; }
@@ -120,6 +121,9 @@ public sealed record CsvCursorOptions
///
public int MaxColumns { get; init; } = 16_384;
+ /// The parameter the options arrive through, as names it.
+ private const string OptionsParameter = "options";
+
internal CsvCursorOptions Checked()
{
OptionChecks.AtLeast(MaxQuotedFieldLines, 0, nameof(CsvCursorOptions), nameof(MaxQuotedFieldLines));
@@ -131,7 +135,7 @@ internal CsvCursorOptions Checked()
{
#pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it
throw new ArgumentOutOfRangeException(
- "options",
+ OptionsParameter,
QuoteMode,
$"{nameof(CsvCursorOptions)}.{nameof(QuoteMode)} is not a quote mode.");
#pragma warning restore S3928
@@ -141,7 +145,7 @@ internal CsvCursorOptions Checked()
{
#pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it
throw new ArgumentOutOfRangeException(
- "options",
+ OptionsParameter,
delimiter,
$"{nameof(CsvCursorOptions)}.{nameof(Delimiter)} must be one of , ; tab | — the delimiters the reader detects.");
#pragma warning restore S3928
@@ -151,12 +155,24 @@ internal CsvCursorOptions Checked()
{
#pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it
throw new ArgumentOutOfRangeException(
- "options",
+ OptionsParameter,
quote,
$"{nameof(CsvCursorOptions)}.{nameof(Quote)} may be neither a line ending nor one of , ; tab |, the delimiters the reader detects.");
#pragma warning restore S3928
}
+ // Strict mode drops whitespace around a quoted field, so a quote that is whitespace would be
+ // both the field's syntax and what is dropped around it.
+ if (QuoteMode == CsvQuoteMode.Strict && Quote is { } blank && char.IsWhiteSpace(blank))
+ {
+#pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it
+ throw new ArgumentOutOfRangeException(
+ OptionsParameter,
+ blank,
+ $"{nameof(CsvCursorOptions)}.{nameof(Quote)} may not be whitespace when {nameof(QuoteMode)} is {nameof(CsvQuoteMode.Strict)}, which drops whitespace around a quoted field.");
+#pragma warning restore S3928
+ }
+
return this;
}
}
diff --git a/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs b/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs
index 494c542..06c91bc 100644
--- a/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs
+++ b/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs
@@ -25,10 +25,26 @@ public enum CsvQuoteMode
/// only bounds it.
///
///
+ ///
/// Whitespace before an opening quote and after a closing one is not part of the field, so
- /// 1, "Payroll", "monthly, HR" reads as three values. A quote inside a field that does not
- /// start with one (21"st AVE) is a character of the text, as it is in every spreadsheet
- /// program. Nothing is repaired, so stays true.
+ /// 1, "Payroll", "monthly, HR" reads as three values. That is any whitespace a cell is
+ /// trimmed of anyway — a no-break space included — except a tab that is the delimiter, so
+ /// may not be whitespace in this mode. The whitespace before
+ /// a quote is held until the quote shows it is not content, so it counts towards
+ /// .
+ ///
+ ///
+ /// A quote inside a field that does not start with one (21"st AVE) is a character of the
+ /// text, as it is in every spreadsheet program. Nothing is repaired, so
+ /// stays true.
+ ///
+ ///
+ /// An opening quote that is never closed reads on to the end of the file and is refused there, as
+ /// ; in an archive that message also names the file the
+ /// row is in. When more than characters follow the
+ /// quote, it reaches that limit first and is refused as a whose
+ /// message names the row and the open quote.
+ ///
///
Strict = 1,
}
diff --git a/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs
index d777c0a..3d0e082 100644
--- a/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs
+++ b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs
@@ -1,6 +1,8 @@
+using System.Formats.Tar;
using System.Text;
using TriasDev.Tabular.Csv;
+using TriasDev.Tabular.Tests.Fixtures;
using Xunit;
@@ -175,7 +177,7 @@ public void ReadsQuotesAfterLeadingBlanksInLinearTime()
{
// Each quote inside a field asks whether the field so far is only whitespace. Asked from the
// field's start, that cost the length of its leading blanks per quote: sixty thousand blanks
- // and as many quotes took some fifteen seconds, eighty thousand thirty-seven, and cancellation,
+ // and as many quotes took twenty-four seconds, eighty thousand thirty-seven, and cancellation,
// checked per character, could not reach it. Linear, it is milliseconds, so the ceiling sits a
// thousand times above it and far below the defect.
const int n = 60_000;
@@ -189,6 +191,135 @@ public void ReadsQuotesAfterLeadingBlanksInLinearTime()
Assert.True(watch.Elapsed < TimeSpan.FromSeconds(3), $"took {watch.Elapsed}");
}
+ [Fact]
+ public void NamesTheRowAndTheOpenQuoteWhenAStrayQuoteReachesTheFieldLimit()
+ {
+ // A quote that is never closed reads on to the field limit. A small file ends first and is
+ // refused as quoting; a large one meets the limit, and the message has to say where and why.
+ CsvCursorOptions options = new() { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',', MaxFieldChars = 100 };
+ string text = "a,b\n1,\"oops,3\n" + string.Concat(Enumerable.Repeat("x,y\n", 50));
+ using CsvCursor cursor = Open(text, options);
+
+ Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken));
+ TabularLimitException error = Assert.Throws(() => cursor.ReadRow(TestContext.Current.CancellationToken));
+
+ Assert.Contains("row 2", error.Message, StringComparison.Ordinal);
+ Assert.Contains("never closed", error.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void CountsTheBlanksBeforeAQuoteTowardsTheFieldLimit()
+ {
+ // They are held until the quote shows they are not content, so they count — as documented.
+ CsvCursorOptions options = new() { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',', MaxFieldChars = 8 };
+ using CsvCursor cursor = Open("a\n" + new string(' ', 10) + "\"x\"\n", options);
+
+ Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken));
+ Assert.Throws(() => cursor.ReadRow(TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public void DropsAnyWhitespaceAroundAQuotedFieldNotOnlySpaces()
+ {
+ // A no-break space is what a cell pasted from a spreadsheet or a web page often starts with,
+ // and the value is trimmed of it anyway.
+ (List rows, _) = Read(
+ "a,b\n\u00A0\"x,y\"\u2003,z\n",
+ new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',' });
+
+ Assert.Equal(["x,y", "z"], rows[1]);
+ }
+
+ [Fact]
+ public void CancellationReachesARunOfBlanksAfterAClosingQuote()
+ {
+ using CancellationTokenSource source = new();
+ byte[] text = Utf8NoBom.GetBytes("a\n\"x\"" + new string(' ', 3_000_000) + "\nb\n");
+ using CancellingStream stream = new(text, source);
+ using CsvCursor cursor = new(stream, "t.csv", new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',' });
+
+ Assert.True(cursor.ReadRow(source.Token));
+ stream.CancelAfter(1);
+
+ Assert.ThrowsAny(() => cursor.ReadRow(source.Token));
+ }
+
+ [Theory]
+ [InlineData(65_531)]
+ [InlineData(65_532)]
+ [InlineData(65_533)]
+ public void RefusesTextAfterAClosingQuoteOnTheReadBufferEdge(int pad)
+ {
+ // "a\n" and the opening quote take three characters, so the closing quote lands on either side
+ // of the first 64 K buffer's last character.
+ TabularFormatException error = Refused(
+ "a\n\"" + new string('p', pad) + "\"Road\n",
+ new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',' });
+
+ Assert.Contains("row 2", error.Message, StringComparison.Ordinal);
+ }
+
+ [Theory]
+ [InlineData(65_532)]
+ [InlineData(65_533)]
+ [InlineData(65_534)]
+ [InlineData(65_535)]
+ public void OpensAQuoteAfterBlanksThatCrossTheReadBufferEdge(int blanks)
+ {
+ (List rows, _) = Read(
+ "a\n" + new string(' ', blanks) + "\"x,y\" \n",
+ new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Delimiter = ',' });
+
+ Assert.Equal(["x,y"], rows[1]);
+ }
+
+ [Fact]
+ public void ReadsACsvInsideAZipStrictlyAndNamesTheEntryItRefuses()
+ {
+ byte[] zip = new ZipArchiveBuilder()
+ .With("ok.csv", ExcelExport)
+ .With("data/bad.csv", "a,b\n\"C\" Road,x\n")
+ .Build();
+
+ AssertReadsTheGoodEntryAndNamesTheBadOne(zip, "t.zip");
+ }
+
+ [Fact]
+ public void ReadsACsvInsideATarStrictlyAndNamesTheEntryItRefuses()
+ {
+ byte[] tar = TarArchive.Of(TarEntryFormat.Pax, ("ok.csv", ExcelExport), ("data/bad.csv", "a,b\n\"C\" Road,x\n"));
+
+ AssertReadsTheGoodEntryAndNamesTheBadOne(tar, "t.tar");
+ }
+
+ private static void AssertReadsTheGoodEntryAndNamesTheBadOne(byte[] archive, string name)
+ {
+ CancellationToken token = TestContext.Current.CancellationToken;
+ TabularOpenOptions options = new() { Csv = new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict } };
+ using ITabularCursor cursor = TabularFile.Open(new MemoryStream(archive, writable: false), name, options, token);
+ int good = cursor.Sheets.ToList().FindIndex(sheet => sheet.Source == "ok.csv");
+ int bad = cursor.Sheets.ToList().FindIndex(sheet => sheet.Source == "data/bad.csv");
+
+ Assert.True(cursor.MoveToSheet(good, token));
+ int rows = 0;
+
+ while (cursor.ReadRow(token))
+ {
+ rows++;
+ }
+
+ Assert.Equal(3, rows);
+ Assert.True(cursor.Diagnostics.IsClean);
+
+ Assert.True(cursor.MoveToSheet(bad, token));
+ Assert.True(cursor.ReadRow(token));
+ TabularFormatException error = Assert.Throws(() => cursor.ReadRow(token));
+
+ Assert.Equal(TabularFormatException.Corrupt, error.Code);
+ Assert.Contains("data/bad.csv", error.Message, StringComparison.Ordinal);
+ Assert.Contains("row 2", error.Message, StringComparison.Ordinal);
+ }
+
[Fact]
public void ReadsACsvInsideGzipStrictlyToo()
{
diff --git a/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs b/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs
index ae14c33..de321e5 100644
--- a/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs
+++ b/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs
@@ -166,11 +166,13 @@ private static byte[] Write(string[][] table, char delimiter, string lineEnd, En
return [.. encoding.GetPreamble(), .. encoding.GetBytes(csv.ToString())];
}
- /// Nothing, or a few spaces and — where tab is not the delimiter — tabs.
+ /// Nothing, or a few whitespace characters: spaces, no-break and em spaces, and — where tab is not the delimiter — tabs.
private static string Blank(Random random, char delimiter) =>
random.Chance(0.5)
? string.Empty
- : new string([.. Enumerable.Range(0, random.Next(1, 4)).Select(_ => delimiter != '\t' && random.Chance(0.3) ? '\t' : ' ')]);
+ : new string([.. Enumerable.Range(0, random.Next(1, 4)).Select(_ => delimiter != '\t' && random.Chance(0.3)
+ ? '\t'
+ : random.Pick(' ', ' ', '\u00A0', '\u2003'))]);
private static string Field(string value, char delimiter, bool quote)
{
diff --git a/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs b/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs
index bcb775a..7beceed 100644
--- a/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs
+++ b/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs
@@ -39,6 +39,8 @@ public sealed class OptionsValidationTests
{ new CsvCursorOptions { Quote = ';' }, nameof(CsvCursorOptions.Quote) },
{ new CsvCursorOptions { Delimiter = '|', Quote = '|' }, nameof(CsvCursorOptions.Quote) },
{ new CsvCursorOptions { QuoteMode = (CsvQuoteMode)7 }, nameof(CsvCursorOptions.QuoteMode) },
+ { new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Quote = ' ' }, nameof(CsvCursorOptions.Quote) },
+ { new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Quote = '\u00A0' }, nameof(CsvCursorOptions.Quote) },
};
public static TheoryData BadXlsxOptions => new()