From 1a4c249008e2210f470dba09a3da6eb973091a21 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Sat, 5 Oct 2024 17:10:55 +0100 Subject: [PATCH] Avoid `OverflowException` in `Boolean.TryFormat` `MemoryMarshal.AsBytes` would throw unnecessarily when `destination.Length` exceeds 0x3FFFFFFF. --- .../System.Private.CoreLib/src/System/Boolean.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs index 07db907c2b1ed..f8773d47ecf04 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs @@ -96,20 +96,20 @@ public bool TryFormat(Span 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(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(ref MemoryMarshal.GetReference(destination)), fals_val); destination[4] = 'e'; charsWritten = 5; return true;