Skip to content

Commit

Permalink
Avoid an allocation in BigInteger.Parse("-2147483648") (dotnet#104666)
Browse files Browse the repository at this point in the history
Co-authored-by: Dan Moseley <[email protected]>
  • Loading branch information
kzrnm and danmoseley authored Dec 4, 2024
1 parent 8672edd commit 11031c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -511,16 +511,23 @@ internal BigInteger(ReadOnlySpan<uint> value, bool negative)
{
this = default;
}
else if (value.Length == 1 && value[0] < kuMaskHighBit)
else if (value.Length == 1)
{
// Values like (Int32.MaxValue+1) are stored as "0x80000000" and as such cannot be packed into _sign
_sign = negative ? -(int)value[0] : (int)value[0];
_bits = null;
if (_sign == int.MinValue)
if (value[0] < kuMaskHighBit)
{
_sign = negative ? -(int)value[0] : (int)value[0];
_bits = null;
}
else if (negative && value[0] == kuMaskHighBit)
{
// Although Int32.MinValue fits in _sign, we represent this case differently for negate
this = s_bnMinInt;
}
else
{
_sign = negative ? -1 : +1;
_bits = [value[0]];
}
}
else
{
Expand Down
21 changes: 17 additions & 4 deletions src/libraries/System.Runtime.Numerics/tests/BigInteger/parse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,23 @@ private static void VerifyDefaultParse(Random random)
// BasicTests
VerifyFailParseToString(null, typeof(ArgumentNullException));
VerifyFailParseToString(string.Empty, typeof(FormatException));
VerifyParseToString("0");
VerifyParseToString("000");
VerifyParseToString("1");
VerifyParseToString("001");

foreach (var value in new string[]
{
"0",
"000",
"1",
"001",
int.MaxValue.ToString(),
int.MinValue.ToString(),
long.MaxValue.ToString(),
long.MinValue.ToString(),
Int128.MaxValue.ToString(),
Int128.MinValue.ToString(),
})
{
VerifyParseToString(value);
}

// SimpleNumbers - Small
for (int i = 0; i < s_samples; i++)
Expand Down

0 comments on commit 11031c4

Please sign in to comment.