Skip to content

Commit

Permalink
Avoid OverflowException in Boolean.TryFormat (#108572)
Browse files Browse the repository at this point in the history
* Avoid `OverflowException` in `Boolean.TryFormat`

`MemoryMarshal.AsBytes` would throw unnecessarily when `destination.Length` exceeds 0x3FFFFFFF.

* Use `string.TryCopyTo`

---------

Co-authored-by: Egor Bogatov <[email protected]>
  • Loading branch information
2 people authored and pull[bot] committed Oct 24, 2024
1 parent 91a13f5 commit 8c2efc2
Showing 1 changed file with 4 additions and 9 deletions.
13 changes: 4 additions & 9 deletions src/libraries/System.Private.CoreLib/src/System/Boolean.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,17 @@ public bool TryFormat(Span<char> destination, out int charsWritten)
{
if (m_value)
{
if (destination.Length > 3)
if (TrueLiteral.TryCopyTo(destination))
{
ulong true_val = BitConverter.IsLittleEndian ? 0x65007500720054ul : 0x54007200750065ul; // "True"
MemoryMarshal.Write(MemoryMarshal.AsBytes(destination), in true_val);
charsWritten = 4;
charsWritten = TrueLiteral.Length;
return true;
}
}
else
{
if (destination.Length > 4)
if (FalseLiteral.TryCopyTo(destination))
{
ulong fals_val = BitConverter.IsLittleEndian ? 0x73006C00610046ul : 0x460061006C0073ul; // "Fals"
MemoryMarshal.Write(MemoryMarshal.AsBytes(destination), in fals_val);
destination[4] = 'e';
charsWritten = 5;
charsWritten = FalseLiteral.Length;
return true;
}
}
Expand Down

0 comments on commit 8c2efc2

Please sign in to comment.