Table of Contents

Utf8TomlReader Struct

Definition

Namespace
Bodu.Text.Toml.Reader
Assembly
Bodu.Text.Toml.dll
Package
Bodu.Text.Toml 1.0.0
Source
Utf8TomlReader.DateTimes.cs

Provides a forward-only, source-order reader for UTF-8 TOML bytes: a ref struct that holds the input span and scans it incrementally. Each Read() advances to the next lexical token in document order - for example [server.tls] surfaces as TableHeader followed by a Key per dotted segment, and ports = [1, 2] as a key, then StartArray, two integers, and EndArray.

public ref struct Utf8TomlReader
Inherited Members

Remarks

The reader validates lexical well-formedness only: UTF-8 validity, string termination and escapes, number and date-time grammar, newline discipline, control characters, the bracket nesting bound, and the grammar features gated by TomlSpecVersion. It enforces no structural semantics - duplicate keys, table redefinition, dotted-key rules, arrays of tables, and inline-table closedness are whole-document rules applied by the parsing entry points (TomlSerializer, TomlNode.Parse, TomlDocument.Parse, and the binding cursor TomlDocumentReader). A document can therefore read cleanly here and still be rejected by those surfaces, and lexical errors are raised from Read() as scanning reaches them, not from the constructor.

Scalar values are validated and decoded as part of Read() - a malformed number or date-time raises TomlFormatException from Read() even when the consumer never asks for the value - and the typed accessors return the decoded result. String content is the exception: Read() validates it in place, and GetString() materializes the string on demand from ValueSpan.

All positions - TokenStartIndex, ColumnNumber, and the positions carried by thrown TomlFormatException instances - are byte-true offsets into the UTF-8 source.

// Lex "port = 8080" into a key token followed by an integer token.
var reader = new Utf8TomlReader("port = 8080"u8);

while (reader.Read())
{
    if (reader.TokenType == TomlTokenType.Key)
        Console.Write($"{reader.GetString()} = ");
    else if (reader.TokenType == TomlTokenType.Integer)
        Console.WriteLine(reader.GetInt64());
}

Constructors

Utf8TomlReader(in ReadOnlySequence<byte>)

Initializes a new instance of the Utf8TomlReader struct over the supplied sequence, enforcing strict TOML v1.0.0.

public Utf8TomlReader(in ReadOnlySequence<byte> utf8Toml)

Parameters

utf8Toml ReadOnlySequence<byte>

The UTF-8 TOML source bytes.

Remarks

A single-segment sequence is read in place; a multi-segment sequence is copied once into a contiguous buffer before reading.

Utf8TomlReader(in ReadOnlySequence<byte>, TomlReaderOptions)

Initializes a new instance of the Utf8TomlReader struct over the supplied sequence using the supplied options.

public Utf8TomlReader(in ReadOnlySequence<byte> utf8Toml, TomlReaderOptions options)

Parameters

utf8Toml ReadOnlySequence<byte>

The UTF-8 TOML source bytes.

options TomlReaderOptions

The reader options controlling the specification version and maximum bracket nesting depth.

Remarks

A single-segment sequence is read in place; a multi-segment sequence is copied once into a contiguous buffer before reading.

Utf8TomlReader(in ReadOnlySequence<byte>, bool, TomlReaderState)

Initializes a new instance of the Utf8TomlReader struct over one block of a document supplied as a sequence, resuming from the state captured at the end of the previous block.

public Utf8TomlReader(in ReadOnlySequence<byte> utf8Toml, bool isFinalBlock, TomlReaderState state)

Parameters

utf8Toml ReadOnlySequence<byte>

The unconsumed bytes carried over from the previous block plus the newly arrived data.

isFinalBlock bool

true when no further data follows this block; false to make Read() return false instead of throwing when the buffer ends mid-token.

state TomlReaderState

The continuation state: a new TomlReaderState for the first block, or the previous reader's CurrentState thereafter.

Remarks

A single-segment sequence is read in place; a multi-segment sequence is copied once into a contiguous buffer before reading.

Utf8TomlReader(ReadOnlySpan<byte>)

Initializes a new instance of the Utf8TomlReader struct over the supplied bytes, enforcing strict TOML v1.0.0.

public Utf8TomlReader(ReadOnlySpan<byte> utf8Toml)

Parameters

utf8Toml ReadOnlySpan<byte>

The UTF-8 TOML source bytes.

Utf8TomlReader(ReadOnlySpan<byte>, TomlReaderOptions)

Initializes a new instance of the Utf8TomlReader struct over the supplied bytes using the supplied options, skipping a leading byte-order mark when present.

public Utf8TomlReader(ReadOnlySpan<byte> utf8Toml, TomlReaderOptions options)

Parameters

utf8Toml ReadOnlySpan<byte>

The UTF-8 TOML source bytes.

options TomlReaderOptions

The reader options controlling the specification version and maximum bracket nesting depth.

Remarks

A MaxDepth of zero or less selects the default maximum depth of 64, and a larger value is clamped to Bodu.Text.Toml.TomlLimits.AbsoluteMaxDepth; input nested deeper than the effective limit throws TomlFormatException.

Utf8TomlReader(ReadOnlySpan<byte>, bool, TomlReaderState)

Initializes a new instance of the Utf8TomlReader struct over one block of a document, resuming from the state captured at the end of the previous block.

public Utf8TomlReader(ReadOnlySpan<byte> utf8Toml, bool isFinalBlock, TomlReaderState state)

Parameters

utf8Toml ReadOnlySpan<byte>

The unconsumed bytes carried over from the previous block plus the newly arrived data.

isFinalBlock bool

true when no further data follows this block; false to make Read() return false instead of throwing when the buffer ends mid-token.

state TomlReaderState

The continuation state: a new TomlReaderState for the first block, or the previous reader's CurrentState thereafter.

Properties

BytesConsumed

Gets the number of bytes of the current block the reader has fully processed.

public readonly long BytesConsumed { get; }

Property Value

long

The byte count. Because the reader consumes input only in whole tokens, the caller carries the bytes from this offset onward into the next block's buffer when resuming.

ColumnNumber

Gets the 1-based byte column at which the current token begins.

public readonly int ColumnNumber { get; }

Property Value

int

The token's source column, counted in bytes from the start of its line.

CurrentDepth

Gets the current bracket nesting depth: the number of arrays and inline tables open around the current token.

public readonly int CurrentDepth { get; }

Property Value

int

The depth, where zero is outside any value. A StartArray or StartInlineTable token reports the depth of its enclosing context, and the matching end token likewise.

Remarks

The depth counts only lexical bracket nesting. [table] and [[array-of-tables]] headers describe structural - not lexical - nesting, so they do not contribute; the normalized CurrentDepth reflects them instead.

CurrentState

Gets the resumable state to construct the next block's reader from.

public readonly TomlReaderState CurrentState { get; }

Property Value

TomlReaderState

The continuation state capturing the grammar context, line counter, and options.

HasEscapes

Gets a value indicating whether the current string token contains escape sequences or line-ending backslashes, so that GetString() cannot return the raw bytes by direct transcoding.

public readonly bool HasEscapes { get; }

Property Value

bool

true when decoding must resolve escapes.

IsFinalBlock

Gets a value indicating whether the supplied bytes contain the final block of the document.

public readonly bool IsFinalBlock { get; }

Property Value

bool

true when running out of input mid-token is an error; false when Read() instead returns false and the caller supplies more data.

IsFinalKeySegment

Gets a value indicating whether the current Key token is the final segment of its dotted path.

public readonly bool IsFinalKeySegment { get; }

Property Value

bool

true when no further Key segment follows in the same header or key/value path.

LineNumber

Gets the 1-based line on which the current token begins.

public readonly int LineNumber { get; }

Property Value

int

The token's source line.

TokenStartIndex

Gets the byte offset at which the current token begins, including any delimiters.

public readonly int TokenStartIndex { get; }

Property Value

int

The zero-based byte offset of the token within the source.

TokenType

Gets the kind of the current token.

public readonly TomlTokenType TokenType { get; }

Property Value

TomlTokenType

The current token kind, or None before the first or after the last token.

ValueSpan

Gets the raw UTF-8 bytes of the current token's text content, excluding delimiters.

public readonly ReadOnlySpan<byte> ValueSpan { get; }

Property Value

ReadOnlySpan<byte>

The content slice: the text inside a string's quotes (with a multi-line string's leading newline already trimmed), the characters of a bare key, the bytes after a comment's #, or the full token text of a scalar literal. Empty for structural tokens.

Methods

GetBoolean()

Reads the current token as a Boolean.

public readonly bool GetBoolean()

Returns

bool

The Boolean value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not a Boolean.

GetByte()

Reads the current token as an 8-bit unsigned integer.

public readonly byte GetByte()

Returns

byte

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in a byte.

GetComment()

Reads the current token as a comment, returning the text after the # to the end of the line.

public readonly string GetComment()

Returns

string

The comment text, excluding the leading #.

Exceptions

InvalidOperationException

Thrown when the current token is not a Comment.

GetDateOnly()

Reads the current token as a local date.

public readonly DateOnly GetDateOnly()

Returns

DateOnly

The local date value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not a LocalDate.

GetDateTime()

Reads the current token as a local date-time.

public readonly DateTime GetDateTime()

Returns

DateTime

The local date-time value decoded during Read(), whose Kind is Unspecified.

Exceptions

InvalidOperationException

Thrown when the current token is not a LocalDateTime.

GetDateTimeOffset()

Reads the current token as an offset date-time.

public readonly DateTimeOffset GetDateTimeOffset()

Returns

DateTimeOffset

The offset date-time value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not an OffsetDateTime.

GetDecimal()

Reads the current token as a decimal, parsed exactly from the raw float literal.

public readonly decimal GetDecimal()

Returns

decimal

The decimal value.

Exceptions

InvalidOperationException

Thrown when the current token is not a Float.

FormatException

Thrown when the literal is inf, -inf, or nan, or its magnitude exceeds the decimal range.

GetDouble()

Reads the current token as an IEEE 754 binary64 floating-point value.

public readonly double GetDouble()

Returns

double

The floating-point value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not a Float.

GetGuid()

Reads the current token as a Guid, parsed from a string token in the 36-character hyphenated ( D) format.

public readonly Guid GetGuid()

Returns

Guid

The parsed GUID.

Exceptions

InvalidOperationException

Thrown when the current token is not a String.

FormatException

Thrown when the string is not a GUID in the D format.

GetInt16()

Reads the current token as a 16-bit signed integer.

public readonly short GetInt16()

Returns

short

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in a short.

GetInt32()

Reads the current token as a 32-bit signed integer.

public readonly int GetInt32()

Returns

int

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in an int.

GetInt64()

Reads the current token as a 64-bit signed integer.

public readonly long GetInt64()

Returns

long

The integer value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

GetSByte()

Reads the current token as an 8-bit signed integer.

public readonly sbyte GetSByte()

Returns

sbyte

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in an sbyte.

GetSingle()

Reads the current token as an IEEE 754 binary32 floating-point value, parsed from the raw float literal.

public readonly float GetSingle()

Returns

float

The single-precision value.

Exceptions

InvalidOperationException

Thrown when the current token is not a Float.

GetString()

Reads the current token's text as a string, decoding escape sequences when present.

public readonly string GetString()

Returns

string

The decoded string value of a string, key, or comment token.

Exceptions

InvalidOperationException

Thrown when the current token is not a String, Key, or Comment.

GetTimeOnly()

Reads the current token as a local time.

public readonly TimeOnly GetTimeOnly()

Returns

TimeOnly

The local time value decoded during Read().

Exceptions

InvalidOperationException

Thrown when the current token is not a LocalTime.

GetUInt16()

Reads the current token as a 16-bit unsigned integer.

public readonly ushort GetUInt16()

Returns

ushort

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in a ushort.

GetUInt32()

Reads the current token as a 32-bit unsigned integer.

public readonly uint GetUInt32()

Returns

uint

The integer value, narrowed from TOML's 64-bit integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value does not fit in a uint.

GetUInt64()

Reads the current token as a 64-bit unsigned integer.

public readonly ulong GetUInt64()

Returns

ulong

The integer value, converted from TOML's 64-bit signed integer.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

FormatException

Thrown when the value is negative.

Read()

Advances the reader to the next token.

public bool Read()

Returns

bool

true when a token was read; false at the end of the document, or - when IsFinalBlock is false - when the buffer ends mid-token and the caller must supply more data before retrying.

Remarks

When the method returns false on a non-final block, the reader is restored to its state before the call: BytesConsumed covers only fully tokenized input, and the caller resumes by constructing a new reader over the remaining bytes plus new data, passing CurrentState.

Exceptions

TomlFormatException

Thrown when the source is not lexically valid TOML.

Skip()

Skips the current value in source order.

public void Skip()

Remarks

When the reader is positioned on a Key, it advances over the remaining key segments onto the value and then skips it, finishing on the value's last token. When it is positioned on a StartArray or StartInlineTable, it advances to the matching end token, reading - and lexically validating - everything in between. On any other token the call has no effect.

Exceptions

TomlFormatException

Thrown when the skipped source is not lexically valid TOML.

InvalidOperationException

Thrown when IsFinalBlock is false; use TrySkip() on partial data.

TryGetByte(out byte)

Attempts to read the current token as an 8-bit unsigned integer.

public readonly bool TryGetByte(out byte value)

Parameters

value byte

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in a byte.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetDecimal(out decimal)

Attempts to read the current token as a decimal, parsed exactly from the raw float literal.

public readonly bool TryGetDecimal(out decimal value)

Parameters

value decimal

When this method returns true, the decimal value; otherwise zero.

Returns

bool

true when the literal is finite and within the decimal range.

Remarks

The decimal is parsed from the document's raw literal rather than converted from the binary64 value, so digits that binary64 cannot represent exactly are preserved.

Exceptions

InvalidOperationException

Thrown when the current token is not a Float.

TryGetGuid(out Guid)

Attempts to read the current token as a Guid in the 36-character hyphenated (D) format.

public readonly bool TryGetGuid(out Guid value)

Parameters

value Guid

When this method returns true, the parsed GUID; otherwise Empty.

Returns

bool

true when the string parses as a GUID in the D format.

Exceptions

InvalidOperationException

Thrown when the current token is not a String.

TryGetInt16(out short)

Attempts to read the current token as a 16-bit signed integer.

public readonly bool TryGetInt16(out short value)

Parameters

value short

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in a short.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetInt32(out int)

Attempts to read the current token as a 32-bit signed integer.

public readonly bool TryGetInt32(out int value)

Parameters

value int

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in an int.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetSByte(out sbyte)

Attempts to read the current token as an 8-bit signed integer.

public readonly bool TryGetSByte(out sbyte value)

Parameters

value sbyte

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in an sbyte.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetSingle(out float)

Attempts to read the current token as an IEEE 754 binary32 floating-point value.

public readonly bool TryGetSingle(out float value)

Parameters

value float

When this method returns true, the single-precision value.

Returns

bool

true always; the conversion cannot fail. A magnitude beyond the float range rounds to an infinity.

Exceptions

InvalidOperationException

Thrown when the current token is not a Float.

TryGetUInt16(out ushort)

Attempts to read the current token as a 16-bit unsigned integer.

public readonly bool TryGetUInt16(out ushort value)

Parameters

value ushort

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in a ushort.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetUInt32(out uint)

Attempts to read the current token as a 32-bit unsigned integer.

public readonly bool TryGetUInt32(out uint value)

Parameters

value uint

When this method returns true, the narrowed value; otherwise zero.

Returns

bool

true when the value fits in a uint.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TryGetUInt64(out ulong)

Attempts to read the current token as a 64-bit unsigned integer.

public readonly bool TryGetUInt64(out ulong value)

Parameters

value ulong

When this method returns true, the converted value; otherwise zero.

Returns

bool

true when the value is non-negative.

Remarks

TOML integers are 64-bit signed, so a value above MaxValue cannot appear in a document; only a negative value fails the conversion.

Exceptions

InvalidOperationException

Thrown when the current token is not an Integer.

TrySkip()

Attempts to skip the current value in source order.

public bool TrySkip()

Returns

bool

true when the value was skipped; false when the buffer ends inside the value on a non-final block, in which case the reader is restored to its position before the call.

Remarks

On the final block the method behaves exactly like Skip() and always returns true; lexically invalid skipped source still raises TomlFormatException.

Exceptions

TomlFormatException

Thrown when the skipped source is not lexically valid TOML.

ValueTextEquals(ReadOnlySpan<byte>)

Compares the current string or key token to the supplied UTF-8 text without allocating when the token is escape-free.

public readonly bool ValueTextEquals(ReadOnlySpan<byte> utf8Text)

Parameters

utf8Text ReadOnlySpan<byte>

The UTF-8 text to compare against the decoded token text.

Returns

bool

true when the decoded token text equals utf8Text.

Exceptions

InvalidOperationException

Thrown when the current token is not a String or Key.

ValueTextEquals(ReadOnlySpan<char>)

Compares the current string or key token to the supplied text without allocating when the token is escape-free and the text is small.

public readonly bool ValueTextEquals(ReadOnlySpan<char> text)

Parameters

text ReadOnlySpan<char>

The text to compare against the decoded token text.

Returns

bool

true when the decoded token text equals text.

Exceptions

InvalidOperationException

Thrown when the current token is not a String or Key.

ValueTextEquals(string?)

Compares the current string or key token to the supplied text.

public readonly bool ValueTextEquals(string? text)

Parameters

text string

The text to compare against the decoded token text.

Returns

bool

true when the decoded token text equals text.

Remarks

A null text compares as empty.

Exceptions

InvalidOperationException

Thrown when the current token is not a String or Key.

Applies to

ProductVersions
.NET8, 10