diff --git a/csharp/src/Google.Protobuf/WritingPrimitives.cs b/csharp/src/Google.Protobuf/WritingPrimitives.cs index 8d8dccc394ad..b6ed90cdf5f6 100644 --- a/csharp/src/Google.Protobuf/WritingPrimitives.cs +++ b/csharp/src/Google.Protobuf/WritingPrimitives.cs @@ -202,7 +202,8 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st ? WriteAsciiStringToBuffer(ref sourceChars, ref destinationBytes, value, length) : 0; - // This avoids bound checks + // Process any remaining, 1 char at a time. + // Avoid bounds checking with ref + Unsafe for (; currentIndex < length; currentIndex++) { Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = (byte)Unsafe.AddByteOffset(ref sourceChars, (IntPtr)(currentIndex * 2));