From 0469e0afac455049c65ab0a1b047d65e78de1c0a Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Thu, 14 Nov 2024 20:14:26 +0200 Subject: [PATCH] Detect double.PositiveInfinity when parsing dates on full framework --- Jint.Tests/Runtime/NumberTests.cs | 18 ++++++++++++++++-- Jint/Runtime/TypeConverter.cs | 20 +++++++++++++++++++- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/Jint.Tests/Runtime/NumberTests.cs b/Jint.Tests/Runtime/NumberTests.cs index 63e82052b..ec68bb4af 100644 --- a/Jint.Tests/Runtime/NumberTests.cs +++ b/Jint.Tests/Runtime/NumberTests.cs @@ -137,11 +137,25 @@ public void ToLocaleString(string parseNumber, string culture, string result) } [Theory] - // Does not add extra zeros of there is no cuture argument. + // Does not add extra zeros of there is no culture argument. [InlineData("123456")] public void ToLocaleStringNoArg(string parseNumber) { var value = _engine.Evaluate($"({parseNumber}).toLocaleString()").AsString(); Assert.DoesNotContain(".0", value); } -} \ No newline at end of file + + [Fact] + public void CoercingFromString() + { + var engine = new Engine(); + + Assert.Equal(double.PositiveInfinity, engine.Evaluate("Number(1e1000)").ToObject()); + Assert.Equal(double.PositiveInfinity, engine.Evaluate("+1e1000").ToObject()); + Assert.Equal("Infinity", engine.Evaluate("(+1e1000).toString()").ToObject()); + + Assert.Equal(double.PositiveInfinity, engine.Evaluate("Number('1e1000')").ToObject()); + Assert.Equal(double.PositiveInfinity, engine.Evaluate("+'1e1000'").ToObject()); + Assert.Equal("Infinity", engine.Evaluate("(+'1e1000').toString()").ToObject()); + } +} diff --git a/Jint/Runtime/TypeConverter.cs b/Jint/Runtime/TypeConverter.cs index f11ec3d98..46bafdcbf 100644 --- a/Jint/Runtime/TypeConverter.cs +++ b/Jint/Runtime/TypeConverter.cs @@ -274,12 +274,30 @@ private static double ToNumber(string input) } } +#if NETFRAMEWORK + // if we are on full framework, one extra check for whether it was actually over the bounds of double + // in modern NET parsing was fixed to be IEEE 754 compliant, full framework is not and cannot detect positive infinity + try + { + var n = double.Parse(input, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture); + return n == 0 && firstChar == '-' ? -0.0 : n; + } + catch (Exception e) when (e is OverflowException) + { + return double.PositiveInfinity; + } + catch + { + return double.NaN; + } +#else if (double.TryParse(input, NumberStyles, CultureInfo.InvariantCulture, out var n)) { return n == 0 && firstChar == '-' ? -0.0 : n; } return double.NaN; +#endif } /// @@ -1014,4 +1032,4 @@ public static void CheckObjectCoercible(Engine engine, JsValue o) ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o); } } -} \ No newline at end of file +}