Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 10 additions & 113 deletions src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,11 +268,11 @@ internal static partial class Number
300;
#endif
/// <summary>Lazily-populated cache of strings for uint values in the range [0, <see cref="SmallNumberCacheLength"/>).</summary>
private static readonly string[] s_smallNumberCache = new string[SmallNumberCacheLength];
private static readonly string?[] s_smallNumberCache = new string[SmallNumberCacheLength];

// Optimizations using "TwoDigits" inspired by:
// https://engineering.fb.com/2013/03/15/developer-tools/three-optimization-tips-for-c/
private static readonly byte[] TwoDigitsCharsAsBytes =
private static ReadOnlySpan<byte> TwoDigitsCharsAsBytes =>
MemoryMarshal.AsBytes<char>("00010203040506070809" +
"10111213141516171819" +
"20212223242526272829" +
Expand All @@ -282,9 +282,9 @@ internal static partial class Number
"60616263646566676869" +
"70717273747576777879" +
"80818283848586878889" +
"90919293949596979899").ToArray();
private static readonly byte[] TwoDigitsBytes =
("00010203040506070809"u8 +
"90919293949596979899");
private static ReadOnlySpan<byte> TwoDigitsBytes =>
"00010203040506070809"u8 +
"10111213141516171819"u8 +
"20212223242526272829"u8 +
"30313233343536373839"u8 +
Expand All @@ -293,7 +293,7 @@ internal static partial class Number
"60616263646566676869"u8 +
"70717273747576777879"u8 +
"80818283848586878889"u8 +
"90919293949596979899"u8).ToArray();
"90919293949596979899"u8;

public static unsafe string FormatDecimal(decimal value, ReadOnlySpan<char> format, NumberFormatInfo info)
{
Expand Down Expand Up @@ -387,9 +387,8 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci

int maxDigits = precision;

switch (fmt)
switch (fmt | 0x20)
{
case 'C':
case 'c':
{
// The currency format uses the precision specifier to indicate the number of
Expand All @@ -404,7 +403,6 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
break;
}

case 'E':
case 'e':
{
// The exponential format uses the precision specifier to indicate the number of
Expand All @@ -423,9 +421,7 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
break;
}

case 'F':
case 'f':
case 'N':
case 'n':
{
// The fixed-point and number formats use the precision specifier to indicate the number
Expand All @@ -440,7 +436,6 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
break;
}

case 'G':
case 'g':
{
// The general format uses the precision specifier to indicate the number of significant
Expand All @@ -457,7 +452,6 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
break;
}

case 'P':
case 'p':
{
// The percent format uses the precision specifier to indicate the number of
Expand All @@ -476,7 +470,6 @@ private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int preci
break;
}

case 'R':
case 'r':
{
// The roundtrip format ignores the precision specifier and always returns the shortest
Expand Down Expand Up @@ -1579,7 +1572,7 @@ internal static unsafe void WriteTwoDigits<TChar>(uint value, TChar* ptr) where

Unsafe.CopyBlockUnaligned(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is basically just doing span.CopyTo, right?

Is the codegen significantly different if we switch to the safe version? Should we log an issue if there's some places that can't be constant folded down here?

Copy link
Member Author

@EgorBo EgorBo Dec 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tannergooding yep, that was my initial intent, but looks like for that we need to change too many methods from TChar* to Span in Number.Formatting. My initial attempt to do so had a terrible perf impact so I decided to file a general clean up first.

Should we log an issue

I guess we can specifically for this, but it all part of the general issue #94941

Copy link
Member

@tannergooding tannergooding Dec 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion of logging an issue was mainly for the consideration of if Span.CopyTo was slower than Unsafe.CopyBlockUnaligned, no need for an issue to track the switch to using Span in general I don't think

Is it worth doing new Span(ptr, length).CopyTo(dest, length) in the meantime which should get us slightly better and then we can track the switch to use span everywhere separately?

ref *(byte*)ptr,
ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(typeof(TChar) == typeof(char) ? TwoDigitsCharsAsBytes : TwoDigitsBytes), (uint)sizeof(TChar) * 2 * value),
ref Unsafe.Add(ref MemoryMarshal.GetReference(typeof(TChar) == typeof(char) ? TwoDigitsCharsAsBytes : TwoDigitsBytes), (uint)sizeof(TChar) * 2 * value),
(uint)sizeof(TChar) * 2);
}

Expand All @@ -1595,7 +1588,7 @@ internal static unsafe void WriteFourDigits<TChar>(uint value, TChar* ptr) where

(value, uint remainder) = Math.DivRem(value, 100);

ref byte charsArray = ref MemoryMarshal.GetArrayDataReference(typeof(TChar) == typeof(char) ? TwoDigitsCharsAsBytes : TwoDigitsBytes);
ref byte charsArray = ref MemoryMarshal.GetReference(typeof(TChar) == typeof(char) ? TwoDigitsCharsAsBytes : TwoDigitsBytes);

Unsafe.CopyBlockUnaligned(
ref *(byte*)ptr,
Expand Down Expand Up @@ -1677,7 +1670,7 @@ internal static unsafe void WriteDigits<TChar>(uint value, TChar* ptr, int count
return bufferEnd;
}

internal static unsafe string UInt32ToDecStr(uint value)
internal static string UInt32ToDecStr(uint value)
{
// For small numbers, consult a lazily-populated cache.
if (value < SmallNumberCacheLength)
Expand Down Expand Up @@ -2540,102 +2533,6 @@ private static unsafe bool TryUInt128ToDecStr<TChar>(UInt128 value, int digits,
return false;
}

private static ulong ExtractFractionAndBiasedExponent(double value, out int exponent)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was all just dead code?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep!

{
ulong bits = BitConverter.DoubleToUInt64Bits(value);
ulong fraction = (bits & 0xFFFFFFFFFFFFF);
exponent = ((int)(bits >> 52) & 0x7FF);

if (exponent != 0)
{
// For normalized value, according to https://en.wikipedia.org/wiki/Double-precision_floating-point_format
// value = 1.fraction * 2^(exp - 1023)
// = (1 + mantissa / 2^52) * 2^(exp - 1023)
// = (2^52 + mantissa) * 2^(exp - 1023 - 52)
//
// So f = (2^52 + mantissa), e = exp - 1075;

fraction |= (1UL << 52);
exponent -= 1075;
}
else
{
// For denormalized value, according to https://en.wikipedia.org/wiki/Double-precision_floating-point_format
// value = 0.fraction * 2^(1 - 1023)
// = (mantissa / 2^52) * 2^(-1022)
// = mantissa * 2^(-1022 - 52)
// = mantissa * 2^(-1074)
// So f = mantissa, e = -1074
exponent = -1074;
}

return fraction;
}

private static ushort ExtractFractionAndBiasedExponent(Half value, out int exponent)
{
ushort bits = BitConverter.HalfToUInt16Bits(value);
ushort fraction = (ushort)(bits & 0x3FF);
exponent = ((int)(bits >> 10) & 0x1F);

if (exponent != 0)
{
// For normalized value, according to https://en.wikipedia.org/wiki/Half-precision_floating-point_format
// value = 1.fraction * 2^(exp - 15)
// = (1 + mantissa / 2^10) * 2^(exp - 15)
// = (2^10 + mantissa) * 2^(exp - 15 - 10)
//
// So f = (2^10 + mantissa), e = exp - 25;

fraction |= (ushort)(1U << 10);
exponent -= 25;
}
else
{
// For denormalized value, according to https://en.wikipedia.org/wiki/Half-precision_floating-point_format
// value = 0.fraction * 2^(1 - 15)
// = (mantissa / 2^10) * 2^(-14)
// = mantissa * 2^(-14 - 10)
// = mantissa * 2^(-24)
// So f = mantissa, e = -24
exponent = -24;
}

return fraction;
}

private static uint ExtractFractionAndBiasedExponent(float value, out int exponent)
{
uint bits = BitConverter.SingleToUInt32Bits(value);
uint fraction = (bits & 0x7FFFFF);
exponent = ((int)(bits >> 23) & 0xFF);

if (exponent != 0)
{
// For normalized value, according to https://en.wikipedia.org/wiki/Single-precision_floating-point_format
// value = 1.fraction * 2^(exp - 127)
// = (1 + mantissa / 2^23) * 2^(exp - 127)
// = (2^23 + mantissa) * 2^(exp - 127 - 23)
//
// So f = (2^23 + mantissa), e = exp - 150;

fraction |= (1U << 23);
exponent -= 150;
}
else
{
// For denormalized value, according to https://en.wikipedia.org/wiki/Single-precision_floating-point_format
// value = 0.fraction * 2^(1 - 127)
// = (mantissa / 2^23) * 2^(-126)
// = mantissa * 2^(-126 - 23)
// = mantissa * 2^(-149)
// So f = mantissa, e = -149
exponent = -149;
}

return fraction;
}

private static ulong ExtractFractionAndBiasedExponent<TNumber>(TNumber value, out int exponent)
where TNumber : unmanaged, IBinaryFloatParseAndFormatInfo<TNumber>
{
Expand Down
Loading