Fix 32-bit floating point JSON parsing of maximal values for C#

Fixes #10509.
pull/10514/head
Jon Skeet 2 years ago
parent 687fbffd9b
commit fc1dbc6fac
  1. 10
      csharp/src/Google.Protobuf.Test/JsonParserTest.cs
  2. 16
      csharp/src/Google.Protobuf/JsonParser.cs

@ -576,6 +576,10 @@ namespace Google.Protobuf
[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 + "}";
@ -584,8 +588,10 @@ namespace Google.Protobuf
}
[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))]

@ -642,19 +642,15 @@ namespace Google.Protobuf
{
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.

Loading…
Cancel
Save