Skip to content

Commit

Permalink
Fix 32-bit floating point JSON parsing of maximal values for C#
Browse files Browse the repository at this point in the history
Fixes #10509.
  • Loading branch information
jskeet committed Sep 9, 2022
1 parent 687fbff commit fc1dbc6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
10 changes: 8 additions & 2 deletions csharp/src/Google.Protobuf.Test/JsonParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,10 @@ public void NumberToDouble_Invalid(string jsonValue)
[TestCase("-3.402823e38", -3.402823e38f)]
[TestCase("1.5e1", 15f)]
[TestCase("15e-1", 1.5f)]
[TestCase("3.4028235e38", float.MaxValue)]
[TestCase("-3.4028235e38", float.MinValue)]
[TestCase("3.4028235e+38", float.MaxValue)]
[TestCase("-3.4028235e+38", float.MinValue)]
public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue)
{
string json = "{ \"singleFloat\": " + jsonValue + "}";
Expand All @@ -584,8 +588,10 @@ public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue)
}

[Test]
[TestCase("3.402824e38", typeof(InvalidProtocolBufferException))]
[TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))]
[TestCase("3.4028236e38", typeof(InvalidProtocolBufferException))]
[TestCase("-3.4028236e38", typeof(InvalidProtocolBufferException))]
[TestCase("3.4028236e+38", typeof(InvalidProtocolBufferException))]
[TestCase("-3.4028236e+38", typeof(InvalidProtocolBufferException))]
[TestCase("1,0", typeof(InvalidJsonException))]
[TestCase("1.0.0", typeof(InvalidJsonException))]
[TestCase("+1", typeof(InvalidJsonException))]
Expand Down
16 changes: 6 additions & 10 deletions csharp/src/Google.Protobuf/JsonParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -642,19 +642,15 @@ private static object ParseSingleNumberValue(FieldDescriptor field, JsonToken to
{
return float.NaN;
}
if (value > float.MaxValue || value < float.MinValue)
float converted = (float) value;
// If the value is out of range of float, the cast representation will be infinite.
// If the original value was infinite as well, that's fine - we'll return the 32-bit
// version (with the correct sign).
if (float.IsInfinity(converted) && !double.IsInfinity(value))
{
if (double.IsPositiveInfinity(value))
{
return float.PositiveInfinity;
}
if (double.IsNegativeInfinity(value))
{
return float.NegativeInfinity;
}
throw new InvalidProtocolBufferException($"Value out of range: {value}");
}
return (float) value;
return converted;
case FieldType.Enum:
CheckInteger(value);
// Just return it as an int, and let the CLR convert it.
Expand Down

0 comments on commit fc1dbc6

Please sign in to comment.