Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider numeric string json for EnumConverter. #79432

Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
5d95f67
Consider numeric string json for EnumConverter.
lateapexearlyspeed Dec 9, 2022
098204a
Fix comment: just use bit operation rather than HasFlag.
lateapexearlyspeed Dec 9, 2022
afeb8e1
Add test.
lateapexearlyspeed Dec 14, 2022
732cb3a
Refine code.
lateapexearlyspeed Dec 17, 2022
58dc738
Merge remote-tracking branch 'origin/main' into lateapexearlyspeed-Co…
lateapexearlyspeed Jan 13, 2023
05555d9
Fix comment: refine comment.
lateapexearlyspeed Jan 16, 2023
180c9bb
Revert EnumConverter change.
lateapexearlyspeed Feb 20, 2023
44029a9
Complete check if current value is numeric string value, and then byp…
lateapexearlyspeed Feb 23, 2023
d745c60
Add more tests.
lateapexearlyspeed Feb 23, 2023
5886f87
Fix issue on non-netcoreapp target.
lateapexearlyspeed Mar 9, 2023
1201c89
Merge branch 'main' into lateapexearlyspeed-ConsiderNumericStringEnum
lateapexearlyspeed Jul 8, 2023
cca8cc2
Use new CreateStringEnumOptionsForType() in tests.
lateapexearlyspeed Jul 10, 2023
045f851
Merge remote-tracking branch 'upstream/main' into lateapexearlyspeed-…
lateapexearlyspeed Sep 26, 2023
ec0024d
Fix comment: move check logic into TryParseEnumCore; turn to use RegEx.
lateapexearlyspeed Sep 28, 2023
1d15cce
use regex generator.
lateapexearlyspeed Sep 30, 2023
92ca867
Add fs test cases about Enum with numeric labels.
lateapexearlyspeed Sep 30, 2023
541f3c5
Update fs test case.
lateapexearlyspeed Sep 30, 2023
c214d39
Fix comment: refine test cases in F#.
lateapexearlyspeed Oct 2, 2023
002f5d5
Fix comment: refine test cases in F#.
lateapexearlyspeed Oct 2, 2023
cd997df
Fix comment: refine Regex usage.
lateapexearlyspeed Oct 4, 2023
f07828b
Update src/libraries/System.Text.Json/src/System/Text/Json/Serializat…
eiriktsarpalis Oct 4, 2023
f29e91f
Move Regex to non-generic helper class
eiriktsarpalis Oct 4, 2023
5ceba05
Update src/libraries/System.Text.Json/src/System/Text/Json/Serializat…
eiriktsarpalis Oct 5, 2023
ee9efd0
Remove duplicated logic
eiriktsarpalis Oct 5, 2023
357d84c
Remove raw pointer usage.
eiriktsarpalis Oct 5, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ internal override unsafe void WriteAsPropertyNameCore(Utf8JsonWriter writer, T v
}

#if NETCOREAPP
private static bool TryParseEnumCore(ref Utf8JsonReader reader, JsonSerializerOptions options, out T value)
private bool TryParseEnumCore(ref Utf8JsonReader reader, JsonSerializerOptions options, out T value)
{
char[]? rentedBuffer = null;
int bufferLength = reader.ValueLength;
Expand All @@ -369,8 +369,22 @@ private static bool TryParseEnumCore(ref Utf8JsonReader reader, JsonSerializerOp
int charsWritten = reader.CopyString(charBuffer);
ReadOnlySpan<char> source = charBuffer.Slice(0, charsWritten);

// Try parsing case sensitive first
bool success = Enum.TryParse(source, out T result) || Enum.TryParse(source, ignoreCase: true, out result);
bool success = true;
if ((_converterOptions & EnumConverterOptions.AllowNumbers) == 0)
{
success = CheckIfValidNamedEnumLiteral(source);
}

T result;
if (success)
{
// Try parsing case sensitive first
success = Enum.TryParse(source, out result) || Enum.TryParse(source, ignoreCase: true, out result);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This predates your changes, but I'm kind of puzzled as to why we do this. Couldn't this just have been a single parse call with ignoreCase set to true?

Copy link
Contributor Author

@lateapexearlyspeed lateapexearlyspeed Sep 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just guess it was for performance. Considering more common case is source is exactly same as Enum name, and case-sensitive comparing of Enum.TryParse may be faster than obscure comparing ?
Also there is STJ doc sample with same code pattern and the comment said

For performance, parse with ignoreCase:false first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, thanks. I'll see if I can validate that claim with a benchmark :-)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BenchmarkRunner.Run<Benchmark>(args: args);

public class Benchmark
{
    [Params("GetProperty", "getproperty")]
    public string EnumStringValue;

    [Benchmark]
    public BindingFlags CaseInsensitive()
    {
        _ = Enum.TryParse(EnumStringValue, ignoreCase: true, out BindingFlags result);
        return result;
    }

    [Benchmark]
    public BindingFlags CaseSensitiveThenCaseInsensitive()
    {
        _ = Enum.TryParse(EnumStringValue, out BindingFlags result) || Enum.TryParse(EnumStringValue, ignoreCase: true, out result);
        return result;
    }
}

Gives

Method EnumStringValue Mean Error StdDev
CaseInsensitive getproperty 40.44 ns 0.460 ns 0.384 ns
CaseSensitiveThenCaseInsensitive getproperty 80.20 ns 1.615 ns 1.586 ns
CaseInsensitive GetProperty 38.47 ns 0.636 ns 0.595 ns
CaseSensitiveThenCaseInsensitive GetProperty 35.09 ns 0.506 ns 0.473 ns

While it's true that the current approach is marginally faster, it drastically regresses performance in case insensitive cases. I think we should just use a single method call. cc @stephentoub

}
else
{
result = default;
}

if (rentedBuffer != null)
{
Expand All @@ -382,15 +396,39 @@ private static bool TryParseEnumCore(ref Utf8JsonReader reader, JsonSerializerOp
return success;
}
#else
private static bool TryParseEnumCore(string? enumString, JsonSerializerOptions _, out T value)
private bool TryParseEnumCore(string? enumString, JsonSerializerOptions _, out T value)
{
if ((_converterOptions & EnumConverterOptions.AllowNumbers) == 0 && (enumString is null || !CheckIfValidNamedEnumLiteral(enumString.AsSpan())))
{
value = default;
return false;
}

// Try parsing case sensitive first
bool success = Enum.TryParse(enumString, out T result) || Enum.TryParse(enumString, ignoreCase: true, out result);
value = result;
return success;
}
#endif

// By just checking first char, will filter out all numeric value, and other named ones which is invalid for named enum literal
private static bool CheckIfValidNamedEnumLiteral(ReadOnlySpan<char> source)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
ReadOnlySpan<char> trimmedSource = source.TrimStart();
if (trimmedSource.IsEmpty)
{
return false;
}

char c = trimmedSource[0];
if ((uint)(c - '0') <= 9 || c is '-' or '+')
{
return false;
}

return true;
}

private T ReadEnumUsingNamingPolicy(string? enumString)
{
if (_namingPolicy == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,26 @@ public void ConvertDayOfWeek()
options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false));
Assert.Throws<JsonException>(() => JsonSerializer.Serialize((DayOfWeek)(-1), options));

// Quoted numbers should throw
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>("1", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>("-1", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>(@"""1""", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>(@"""+1""", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>(@"""-1""", options));

day = JsonSerializer.Deserialize<DayOfWeek>(@"""Monday""", options);
Assert.Equal(DayOfWeek.Monday, day);

// Numbers-formatted json string should first consider naming policy
options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false, namingPolicy: new ToEnumNumberNamingPolicy<DayOfWeek>()));
day = JsonSerializer.Deserialize<DayOfWeek>(@"""1""", options);
Assert.Equal(DayOfWeek.Monday, day);

options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false, namingPolicy: new ToLowerNamingPolicy()));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DayOfWeek>(@"""1""", options));
}

public class ToLowerNamingPolicy : JsonNamingPolicy
Expand Down Expand Up @@ -107,11 +127,21 @@ public void ConvertFileAttributes()
json = JsonSerializer.Serialize((FileAttributes)(-1), options);
Assert.Equal(@"-1", json);

// Not permitting integers should throw
options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false));
// Not permitting integers should throw
Assert.Throws<JsonException>(() => JsonSerializer.Serialize((FileAttributes)(-1), options));

// Numbers should throw
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<FileAttributes>("1", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<FileAttributes>("-1", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<FileAttributes>(@"""1""", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<FileAttributes>(@"""+1""", options));
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<FileAttributes>(@"""-1""", options));

attributes = JsonSerializer.Deserialize<FileAttributes>(@"""ReadOnly""", options);
Assert.Equal(FileAttributes.ReadOnly, attributes);

// Flag values honor naming policy correctly
options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(new SimpleSnakeCasePolicy()));
Expand Down Expand Up @@ -631,6 +661,11 @@ public static void EnumDictionaryKeySerialization()
JsonTestHelper.AssertJsonEqual(expected, JsonSerializer.Serialize(dict, options));
}

private class ToEnumNumberNamingPolicy<T> : JsonNamingPolicy where T : struct, Enum
{
public override string ConvertName(string name) => Enum.TryParse(name, out T value) ? value.ToString("D") : name;
}

private class ZeroAppenderPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) => name + "0";
Expand Down