Skip to content

Commit

Permalink
Avoid OverflowException in Boolean.TryFormat
Browse files Browse the repository at this point in the history
`MemoryMarshal.AsBytes` would throw unnecessarily when `destination.Length` exceeds 0x3FFFFFFF.
  • Loading branch information
xtqqczze committed Oct 5, 2024
1 parent 3bcaadb commit 1a4c249
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/libraries/System.Private.CoreLib/src/System/Boolean.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,20 +96,20 @@ public bool TryFormat(Span<char> destination, out int charsWritten)
{
if (m_value)
{
if (destination.Length > 3)
if (destination.Length >= 4)
{
ulong true_val = BitConverter.IsLittleEndian ? 0x65007500720054ul : 0x54007200750065ul; // "True"
MemoryMarshal.Write(MemoryMarshal.AsBytes(destination), in true_val);
Unsafe.WriteUnaligned(ref Unsafe.As<char, byte>(ref MemoryMarshal.GetReference(destination)), true_val);
charsWritten = 4;
return true;
}
}
else
{
if (destination.Length > 4)
if (destination.Length >= 5)
{
ulong fals_val = BitConverter.IsLittleEndian ? 0x73006C00610046ul : 0x460061006C0073ul; // "Fals"
MemoryMarshal.Write(MemoryMarshal.AsBytes(destination), in fals_val);
Unsafe.WriteUnaligned(ref Unsafe.As<char, byte>(ref MemoryMarshal.GetReference(destination)), fals_val);
destination[4] = 'e';
charsWritten = 5;
return true;
Expand Down

0 comments on commit 1a4c249

Please sign in to comment.