Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit ed36542

Browse files
committed
Avoid always using ToByteArray in FormatBigIntegerToHex
Use stack space if possible
1 parent a913bc7 commit ed36542

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -514,10 +514,24 @@ internal static char ParseFormatSpecifier(string format, out int digits)
514514
return (char)0; // Custom format
515515
}
516516

517-
private static string FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info)
517+
private static string FormatBigIntegerToHex(BigInteger value, char format, int digits, NumberFormatInfo info)
518518
{
519+
// Get the bytes that make up the BigInteger.
520+
int byteCount = value.GetByteCount();
521+
Span<byte> bits = stackalloc byte[0]; // TODO: Remove the initialization once C# compiler is fixed to allow it.
522+
if (byteCount <= 128) // arbitrary limit to switch from stack to heap
523+
{
524+
bits = stackalloc byte[byteCount];
525+
bool formatted = value.TryWriteBytes(bits, out int bytesWritten);
526+
Debug.Assert(formatted);
527+
Debug.Assert(bytesWritten == byteCount);
528+
}
529+
else
530+
{
531+
bits = value.ToByteArray();
532+
}
533+
519534
StringBuilder sb = new StringBuilder();
520-
byte[] bits = value.ToByteArray();
521535
string fmt = null;
522536
int cur = bits.Length - 1;
523537

@@ -563,7 +577,7 @@ internal static string FormatBigInteger(BigInteger value, string format, NumberF
563577
int digits = 0;
564578
char fmt = ParseFormatSpecifier(format, out digits);
565579
if (fmt == 'x' || fmt == 'X')
566-
return FormatBigIntegerToHexString(value, fmt, digits, info);
580+
return FormatBigIntegerToHex(value, fmt, digits, info);
567581

568582
bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R');
569583

0 commit comments

Comments
 (0)