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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Nothing was removed or renamed. Some calls answer differently, text that parsed
- EF Core: `Any` or `Count` with a predicate over an empty captured list of value sets, or of ranges beside a `Contains`, returns `false` or `0`, as in memory. It threw `InvalidOperationException` ("Empty collections are not supported as inline query roots") ([EF Core](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/efcore.md#match-a-column-against-a-list-of-sets)).
- Docs: an exclusive `infinity` or `-infinity` date bound excludes the date extreme, which stands for the infinity, so `[2026-01-01,infinity)` is `[2026-01-01,9999-12-30]` from a column and from the literal alike. Ask other tools to write an open end as absent or inclusive ([Domain width](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/architecture.md#domain-width-and-the-boundary)).
- Docs: a temporal literal with more than six fraction digits keeps them in memory, while PostgreSQL reads the same text rounded to the microsecond and the EF Core package stores it truncated, so the three can be 1 µs apart ([Literals](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/serialization.md#dates-and-times-are-strict-iso-8601)).
- Literals: integer bounds and elements read PostgreSQL 16's `0x`, `0o` and `0b` prefixes and single underscores between digits, in `Int32Range`, `Int64Range`, their multiranges, `Int16Set`, `Int32Set`, `Int64Set` and the wrapper sets. `[0x1F,)` and `{1_000}` threw `FormatException` ([Literals](https://github.com/CaffeinatedCoder/CodoMetis.ValueRanges/blob/main/docs/serialization.md#parse-a-literal)).

## [9.1.0] — 2026-10-17

Expand Down
4 changes: 4 additions & 0 deletions docs/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ if (Int32Range.TryParse(userInput, null, out var range))
`Parse` and `TryParse` read the invariant literal and **ignore the provider**, as `Guid.Parse`
does. The text is PostgreSQL's, and it has no culture.

Integer bounds and elements follow PostgreSQL 16's integer grammar. You can write them in decimal,
or in hexadecimal, octal or binary after `0x`, `0o` or `0b`, with single underscores between digits:
`[0x1F,1_000)` is `[31,1000)`. PostgreSQL 15 and older read decimal digits only.

Decimal bounds follow PostgreSQL's `numeric` grammar: sign, digits, point and exponent. A group
separator or a currency symbol fails (`FormatException`).

Expand Down
4 changes: 3 additions & 1 deletion src/CodoMetis.ValueRanges/Int32Range.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,10 @@ public static Int32Range CreateFinite(
};

/// <inheritdoc />
/// <remarks>PostgreSQL 16\'s integer grammar — decimal, or <c>0x</c>, <c>0o</c> or <c>0b</c> digits, with single
/// underscores between digits (<see cref="IntegerLiteral"/>); the provider is ignored.</remarks>
public static int ParseValue(ReadOnlySpan<char> s, IFormatProvider? provider)
=> int.Parse(s, NumberStyles.Integer, provider ?? CultureInfo.InvariantCulture);
=> IntegerLiteral.Parse<int>(s);

/// <summary>
/// Parses a PostgreSQL range literal (e.g. <c>[1,10]</c>, <c>empty</c>, <c>(,)</c>)
Expand Down
4 changes: 3 additions & 1 deletion src/CodoMetis.ValueRanges/Int64Range.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,10 @@ public static Int64Range CreateFinite(
}

/// <inheritdoc />
/// <remarks>PostgreSQL 16\'s integer grammar — decimal, or <c>0x</c>, <c>0o</c> or <c>0b</c> digits, with single
/// underscores between digits (<see cref="IntegerLiteral"/>); the provider is ignored.</remarks>
public static long ParseValue(ReadOnlySpan<char> s, IFormatProvider? provider)
=> long.Parse(s, NumberStyles.Integer, provider ?? CultureInfo.InvariantCulture);
=> IntegerLiteral.Parse<long>(s);

/// <summary>
/// Parses a PostgreSQL range literal (e.g. <c>[1,10]</c>, <c>empty</c>, <c>(,)</c>)
Expand Down
79 changes: 79 additions & 0 deletions src/CodoMetis.ValueRanges/Internals/IntegerLiteral.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System.Globalization;
using System.Numerics;

namespace CodoMetis.ValueRanges.Internals;

/// <summary>
/// An integer bound or element as PostgreSQL 16's <c>int2</c>, <c>int4</c> and <c>int8</c> input reads
/// it: an optional sign, then decimal digits, or <c>0x</c>, <c>0o</c> or <c>0b</c> (either case) and
/// digits in that base, with single underscores between digits (and one straight after the prefix),
/// around which <see cref="LiteralWhiteSpace"/> is skipped. Until 10.0.0 only the decimal form was
/// read, so <c>[0x1F,)</c> and <c>{1_000}</c>, which the server reads, threw here (#127).
/// </summary>
/// <remarks>
/// Measured on PostgreSQL 16 and 18, which agree: <c>0x_1F</c>, <c>0_1</c> and <c>-0x80000000</c>
/// (as <c>int4</c>) are read; <c>0x</c>, <c>0x1__F</c>, <c>0x1F_</c>, <c>_1</c>, <c>00x1</c>,
/// <c>0x-1</c>, <c>0o8</c> and <c>1e3</c> are refused. The magnitude is checked against the type
/// before the sign is applied, so the minimum is reachable in every base. Too large a magnitude
/// throws <see cref="OverflowException"/>, as the BCL integer parsers do. The provider never reaches
/// it. Shared by the integer ranges' and sets' <c>ParseValue</c>, which every literal, JSON element,
/// <c>TypeConverter</c> and EF Core JSON document reaches.
/// </remarks>
internal static class IntegerLiteral
{
internal static T Parse<T>(ReadOnlySpan<char> s) where T : IBinaryInteger<T>, IMinMaxValue<T>
{
// The decimal form without separators, which is nearly every literal.
if (T.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) return value;

var text = LiteralWhiteSpace.Trim(s);
var negative = text.Length > 0 && text[0] == '-';
if (text.Length > 0 && text[0] is '+' or '-') text = text[1..];

var radix = text.Length > 1 && text[0] == '0'
? text[1] switch { 'x' or 'X' => 16, 'o' or 'O' => 8, 'b' or 'B' => 2, _ => 10 }
: 10;
if (radix != 10) text = text[2..];

// Each underscore needs a digit after it, and a digit before it unless it follows the prefix.
UInt128 magnitude = 0;
var digits = 0;
var underscore = false;
var limit = negative ? UInt128.CreateTruncating(T.MaxValue) + 1 : UInt128.CreateTruncating(T.MaxValue);
foreach (var c in text)
{
if (c == '_')
{
if (underscore || digits == 0 && radix == 10) throw Invalid(s);
underscore = true;
continue;
}

var digit = DigitValue(c);
if (digit >= radix) throw Invalid(s);

underscore = false;
digits++;
magnitude = magnitude * (uint)radix + (uint)digit;
if (magnitude > limit) throw new OverflowException($"Value was either too large or too small for {typeof(T).Name}: '{LiteralExcerpt.Of(s)}'.");
}

if (digits == 0 || underscore) throw Invalid(s);

return negative
? T.CreateTruncating(Int128.CreateTruncating(UInt128.Zero - magnitude))
: T.CreateTruncating(magnitude);
}

private static int DigitValue(char c) => c switch
{
>= '0' and <= '9' => c - '0',
>= 'a' and <= 'f' => c - 'a' + 10,
>= 'A' and <= 'F' => c - 'A' + 10,
_ => int.MaxValue
};

private static FormatException Invalid(ReadOnlySpan<char> s)
=> new("Expected an integer: an optional sign, then decimal digits, or 0x, 0o or 0b and digits in that base, "
+ $"with single underscores between digits, as PostgreSQL 16 reads it: '{LiteralExcerpt.Of(s)}'.");
}
7 changes: 5 additions & 2 deletions src/CodoMetis.ValueRanges/Sets/Int16Set.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ static Int16Set IValueSetFactory<Int16Set, short>.FromTrusted(ImmutableArray<sho
public ImmutableArray<short>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <inheritdoc cref="IValueSetFactory{TSet,T}.ParseValue"/>
/// <remarks>PostgreSQL 16\'s integer grammar — decimal, or <c>0x</c>, <c>0o</c> or <c>0b</c> digits, with single
/// underscores between digits (<see cref="IntegerLiteral"/>); the provider is ignored.</remarks>
public static short ParseValue(ReadOnlySpan<char> s, IFormatProvider? provider)
=> short.Parse(s, NumberStyles.Integer, provider ?? CultureInfo.InvariantCulture);
=> IntegerLiteral.Parse<short>(s);

/// <summary>
/// Parses a PostgreSQL array literal (e.g. <c>{1,2}</c>, <c>{}</c>) into a
Expand Down Expand Up @@ -192,7 +194,8 @@ static Int16Set<TElement> IValueSetFactory<Int16Set<TElement>, TElement>.FromTru
public ImmutableArray<TElement>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <summary>
/// Parses an element with the family's grammar — an optionally signed integer (<see cref="System.Globalization.NumberStyles.Integer"/>, invariant), exactly as
/// Parses an element with the family's grammar — an integer as PostgreSQL 16 reads it (decimal,
/// or <c>0x</c>/<c>0o</c>/<c>0b</c>, with <c>_</c> between digits), exactly as
/// <see cref="Int16Set.ParseValue"/> reads it — and hands the element the parsed
/// <see cref="short"/>'s invariant text via <see cref="IParsable{TSelf}"/>, which re-runs
/// its validation: corrupt data throws rather than materializing.
Expand Down
7 changes: 5 additions & 2 deletions src/CodoMetis.ValueRanges/Sets/Int32Set.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ static Int32Set IValueSetFactory<Int32Set, int>.FromTrusted(ImmutableArray<int>
public ImmutableArray<int>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <inheritdoc cref="IValueSetFactory{TSet,T}.ParseValue"/>
/// <remarks>PostgreSQL 16\'s integer grammar — decimal, or <c>0x</c>, <c>0o</c> or <c>0b</c> digits, with single
/// underscores between digits (<see cref="IntegerLiteral"/>); the provider is ignored.</remarks>
public static int ParseValue(ReadOnlySpan<char> s, IFormatProvider? provider)
=> int.Parse(s, NumberStyles.Integer, provider ?? CultureInfo.InvariantCulture);
=> IntegerLiteral.Parse<int>(s);

/// <summary>
/// Parses a PostgreSQL array literal (e.g. <c>{1,2}</c>, <c>{}</c>) into an
Expand Down Expand Up @@ -187,7 +189,8 @@ static Int32Set<TElement> IValueSetFactory<Int32Set<TElement>, TElement>.FromTru
public ImmutableArray<TElement>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <summary>
/// Parses an element with the family's grammar — an optionally signed integer (<see cref="System.Globalization.NumberStyles.Integer"/>, invariant), exactly as
/// Parses an element with the family's grammar — an integer as PostgreSQL 16 reads it (decimal,
/// or <c>0x</c>/<c>0o</c>/<c>0b</c>, with <c>_</c> between digits), exactly as
/// <see cref="Int32Set.ParseValue"/> reads it — and hands the element the parsed
/// <see cref="int"/>'s invariant text via <see cref="IParsable{TSelf}"/>, which re-runs
/// its validation: corrupt data throws rather than materializing.
Expand Down
7 changes: 5 additions & 2 deletions src/CodoMetis.ValueRanges/Sets/Int64Set.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ static Int64Set IValueSetFactory<Int64Set, long>.FromTrusted(ImmutableArray<long
public ImmutableArray<long>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <inheritdoc cref="IValueSetFactory{TSet,T}.ParseValue"/>
/// <remarks>PostgreSQL 16\'s integer grammar — decimal, or <c>0x</c>, <c>0o</c> or <c>0b</c> digits, with single
/// underscores between digits (<see cref="IntegerLiteral"/>); the provider is ignored.</remarks>
public static long ParseValue(ReadOnlySpan<char> s, IFormatProvider? provider)
=> long.Parse(s, NumberStyles.Integer, provider ?? CultureInfo.InvariantCulture);
=> IntegerLiteral.Parse<long>(s);

/// <summary>
/// Parses a PostgreSQL array literal (e.g. <c>{1,2}</c>, <c>{}</c>) into an
Expand Down Expand Up @@ -187,7 +189,8 @@ static Int64Set<TElement> IValueSetFactory<Int64Set<TElement>, TElement>.FromTru
public ImmutableArray<TElement>.Enumerator GetEnumerator() => _elements.GetEnumerator();

/// <summary>
/// Parses an element with the family's grammar — an optionally signed integer (<see cref="System.Globalization.NumberStyles.Integer"/>, invariant), exactly as
/// Parses an element with the family's grammar — an integer as PostgreSQL 16 reads it (decimal,
/// or <c>0x</c>/<c>0o</c>/<c>0b</c>, with <c>_</c> between digits), exactly as
/// <see cref="Int64Set.ParseValue"/> reads it — and hands the element the parsed
/// <see cref="long"/>'s invariant text via <see cref="IParsable{TSelf}"/>, which re-runs
/// its validation: corrupt data throws rather than materializing.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -523,9 +523,10 @@ private sealed record ElementCorpus(string[] Ascending, (string Text, string Fam

private static ElementCorpus Elements(Kind kind) => kind switch
{
Kind.Int2 => Integers("32767", "-32768", "32768", "-32769"),
Kind.Int4 => Integers("2147483647", "-2147483648", "2147483648", "-2147483649"),
Kind.Int8 => Integers("9223372036854775807", "-9223372036854775808", "9223372036854775808", "-9223372036854775809"),
Kind.Int2 => Integers("32767", "-32768", "32768", "-32769", "0x7FFF", "-0x8000", "0x8000"),
Kind.Int4 => Integers("2147483647", "-2147483648", "2147483648", "-2147483649", "0x7FFFFFFF", "-0x80000000", "0x80000000"),
Kind.Int8 => Integers("9223372036854775807", "-9223372036854775808", "9223372036854775808", "-9223372036854775809",
"0x7FFFFFFFFFFFFFFF", "-0x8000000000000000", "0x8000000000000000"),
Kind.Numeric => new(["1.5", "2", "5.25", "9"],
[
("1.5", "element"), ("+1.5", "sign"), ("-1.5", "sign"), ("-0", "sign"), (".5", "point"), ("5.", "point"),
Expand Down Expand Up @@ -597,11 +598,20 @@ private sealed record ElementCorpus(string[] Ascending, (string Text, string Fam
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};

private static ElementCorpus Integers(string max, string min, string aboveMax, string belowMin) => new(["1", "2", "5", "9"],
private static ElementCorpus Integers(string max, string min, string aboveMax, string belowMin, string hexMax, string hexMin, string hexAboveMax) => new(["1", "2", "5", "9"],
[
("1", "element"), ("+1", "sign"), ("-1", "sign"), ("-0", "sign"), ("007", "leading zeros"), ("1e3", "exponent"), ("1.0", "fraction"),
("1.5", "fraction"), (max, "extreme"), (min, "extreme"), (aboveMax, "overflow"), (belowMin, "overflow"),
("0x1F", "non-decimal integer"), ("0o17", "non-decimal integer"), ("0b101", "non-decimal integer"), ("1_000", "digit separator integer"),
// PostgreSQL 16's integer grammar at its edges (#127), measured on 16 and 18: a prefix in either
// case, a sign before it, one underscore after it, the extremes in hex with the sign applied last.
("0X1F", "non-decimal integer"), ("-0x1F", "non-decimal integer"), ("+0b101", "non-decimal integer"), ("0x_1F", "non-decimal integer"),
("0o_17", "non-decimal integer"), ("0x000000000000001F", "non-decimal integer"), (hexMax, "non-decimal extreme"), (hexMin, "non-decimal extreme"),
(hexAboveMax, "non-decimal overflow"), ("0_1", "digit separator integer"), ("1_000_0", "digit separator integer"),
("0x", "malformed non-decimal integer"), ("0x1__F", "malformed non-decimal integer"), ("0x1F_", "malformed non-decimal integer"),
("00x1", "malformed non-decimal integer"), ("0x-1", "malformed non-decimal integer"), ("0o8", "malformed non-decimal integer"),
("0b2", "malformed non-decimal integer"), ("0x 1F", "malformed non-decimal integer"), ("0_x1", "malformed non-decimal integer"),
("_1", "malformed digit separator"), ("1_", "malformed digit separator"), ("1__000", "malformed digit separator"), ("-_1", "malformed digit separator"),
("\uFF11", "unicode digit"), ("\u0663", "unicode digit"), ("1 2", "malformed element"), ("- 1", "malformed element"),
("NaN", "numeric special"), ("infinity", "numeric special")
]);
Expand Down
Loading