From a58410fc4bda35867caf8b003ec7c5b47964d7a4 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 8 Jul 2026 04:20:05 +0000 Subject: [PATCH] Port span-based Encoding.GetBytes to Write(string) and Write(ReadOnlySpan) (#1004) * Port MessagePack-CSharp PR #2258: use span-based Encoding.GetBytes in Write(string) and Write(ReadOnlySpan) Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> * Remove unnecessary .AsSpan() in Write(string) - string implicitly converts to ReadOnlySpan Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> * Fix legacy path buffer size: use bufferSize - useOffset in GetBytes calls Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: AArnott <3548+AArnott@users.noreply.github.com> --- src/Nerdbank.MessagePack/MessagePackWriter.cs | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/Nerdbank.MessagePack/MessagePackWriter.cs b/src/Nerdbank.MessagePack/MessagePackWriter.cs index 31655e51..0c54c448 100644 --- a/src/Nerdbank.MessagePack/MessagePackWriter.cs +++ b/src/Nerdbank.MessagePack/MessagePackWriter.cs @@ -674,13 +674,18 @@ public unsafe void Write(string? value) } ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) + fixed (byte* pBuffer = &buffer) { - fixed (byte* pBuffer = &buffer) + int byteCount; +#if NET + byteCount = StringEncoding.UTF8.GetBytes(value, new Span(pBuffer + useOffset, bufferSize - useOffset)); +#else + fixed (char* pValue = value) { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); + byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize - useOffset); } +#endif + this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); } } @@ -695,13 +700,18 @@ public unsafe void Write(string? value) public unsafe void Write(scoped ReadOnlySpan value) { ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) + fixed (byte* pBuffer = &buffer) { - fixed (byte* pBuffer = &buffer) + int byteCount; +#if NET + byteCount = StringEncoding.UTF8.GetBytes(value, new Span(pBuffer + useOffset, bufferSize - useOffset)); +#else + fixed (char* pValue = value) { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); + byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize - useOffset); } +#endif + this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); } }