Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions docs/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/TriasDev.Tabular/Archive/ArchiveCursor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

/// <inheritdoc />
Expand Down
83 changes: 64 additions & 19 deletions src/TriasDev.Tabular/Csv/CsvCursor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ internal sealed class CsvCursor : ITabularCursor

private int _pendingLength;

/// <summary>Whether a quoted field is open in strict mode, for the message of a field that grows past the limit.</summary>
private bool _inStrictQuote;

private RawCell[] _cells = new RawCell[16];
private int _cellCount;
private int _bufferLength;
Expand Down Expand Up @@ -263,6 +266,7 @@ public bool ReadRow(CancellationToken cancellationToken = default)
_cellCount = 0;
_field.Clear();
_pendingStart = -1;
_inStrictQuote = false;

try
{
Expand Down Expand Up @@ -368,7 +372,10 @@ private bool ReadRowCore(CancellationToken cancellationToken)
if (inQuotes && _peeked < 0 && _pushbackPosition >= _pushback.Count && _bufferPosition < _bufferLength)
{
ReadOnlySpan<char> 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)
{
Expand Down Expand Up @@ -539,7 +546,7 @@ private bool ReadRowCore(CancellationToken cancellationToken)
continue;
}

EndQuotedFieldStrictly();
EndQuotedFieldStrictly(cancellationToken);
inQuotes = false;
continue;
}
Expand All @@ -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;
Expand Down Expand Up @@ -597,29 +605,28 @@ private bool ReadRowCore(CancellationToken cancellationToken)
}
}

/// <summary>
/// Adds a character to the field being built, refusing one that grows past the ceiling.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <summary>Adds a run of ordinary text to the field being built, under the same ceiling.</summary>
/// <summary>Adds a run of ordinary text to the field being built, under the ceiling <see cref="AppendToField"/> keeps.</summary>
private void AppendRunToField(ReadOnlySpan<char> 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);
}

/// <summary>
/// Adds a character to the field being built, refusing one that grows past the ceiling.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
private void AppendToField(char c)
{
if (_pendingStart >= 0)
Expand All @@ -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);
}

/// <summary>Whitespace that strict mode drops around a quoted field: a space, and a tab that is not the delimiter.</summary>
private bool IsBlank(int c) => c == ' ' || (c == '\t' && Dialect.Delimiter != '\t');
/// <summary>The refusal of a field past <see cref="CsvCursorOptions.MaxFieldChars"/>, naming the row.</summary>
/// <remarks>
/// 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.
/// </remarks>
[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));

/// <summary>
/// Whitespace that strict mode drops around a quoted field: what <see cref="string.Trim()"/> trims
/// from a cell anyway — a no-break space included —, except the delimiter and line endings.
/// </summary>
private bool IsBlank(int c) =>
c >= 0 && c != Dialect.Delimiter && c != '\r' && c != '\n' && char.IsWhiteSpace((char)c);

/// <summary>Whether the field read so far is nothing but <see cref="IsBlank"/> whitespace.</summary>
/// <remarks>
Expand Down Expand Up @@ -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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[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();
}
Expand All @@ -697,6 +737,11 @@ private void EndQuotedFieldStrictly()
}

/// <summary>The refusal of strict mode, naming the record being read.</summary>
/// <remarks>
/// <see cref="TabularFormatException.Corrupt"/> also for a file that ends inside a quoted field,
/// not <see cref="TabularFormatException.Truncated"/>: 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.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
private TabularFormatException Malformed(string what) => new(
TabularFormatException.Corrupt,
Expand Down
24 changes: 20 additions & 4 deletions src/TriasDev.Tabular/Csv/CsvCursorOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ public sealed record CsvCursorOptions
/// <remarks>
/// It may not be a line ending, nor one of the delimiters the reader knows (<c>,</c> <c>;</c> tab
/// <c>|</c>), since a detected delimiter could then be the quote too. Delimiter detection honours
/// it.
/// it. With <see cref="QuoteMode"/> <see cref="CsvQuoteMode.Strict"/> it may not be whitespace
/// either, since that mode drops whitespace around a quoted field.
/// </remarks>
public char? Quote { get; init; }

Expand Down Expand Up @@ -120,6 +121,9 @@ public sealed record CsvCursorOptions
/// </remarks>
public int MaxColumns { get; init; } = 16_384;

/// <summary>The parameter the options arrive through, as <see cref="OptionChecks"/> names it.</summary>
private const string OptionsParameter = "options";

internal CsvCursorOptions Checked()
{
OptionChecks.AtLeast(MaxQuotedFieldLines, 0, nameof(CsvCursorOptions), nameof(MaxQuotedFieldLines));
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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;
}
}
22 changes: 19 additions & 3 deletions src/TriasDev.Tabular/Csv/CsvQuoteMode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,26 @@ public enum CsvQuoteMode
/// only <see cref="CsvCursorOptions.MaxFieldChars"/> bounds it.
/// </summary>
/// <remarks>
/// <para>
/// Whitespace before an opening quote and after a closing one is not part of the field, so
/// <c>1, "Payroll", "monthly, HR"</c> reads as three values. A quote inside a field that does not
/// start with one (<c>21"st AVE</c>) is a character of the text, as it is in every spreadsheet
/// program. Nothing is repaired, so <see cref="CursorDiagnostics.IsClean"/> stays true.
/// <c>1, "Payroll", "monthly, HR"</c> 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
/// <see cref="CsvCursorOptions.Quote"/> 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
/// <see cref="CsvCursorOptions.MaxFieldChars"/>.
/// </para>
/// <para>
/// A quote inside a field that does not start with one (<c>21"st AVE</c>) is a character of the
/// text, as it is in every spreadsheet program. Nothing is repaired, so
/// <see cref="CursorDiagnostics.IsClean"/> stays true.
/// </para>
/// <para>
/// An opening quote that is never closed reads on to the end of the file and is refused there, as
/// <see cref="TabularFormatException.Corrupt"/>; in an archive that message also names the file the
/// row is in. When more than <see cref="CsvCursorOptions.MaxFieldChars"/> characters follow the
/// quote, it reaches that limit first and is refused as a <see cref="TabularLimitException"/> whose
/// message names the row and the open quote.
/// </para>
/// </remarks>
Strict = 1,
}
Loading
Loading