diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs index cb2e6e1c81feeb..b42cb7861e1c26 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs @@ -156,8 +156,12 @@ public static void EscapeString(ReadOnlySpan value, Span destination } } - private static void EscapeNextBytes(byte value, Span destination, ref int written) + private static void EscapeNextBytes(byte value, Span destination, ref int totalWritten) { + // Slice the span so the JIT can see that no bounds checks are needed below + destination = destination.Slice(totalWritten, JsonConstants.MaxExpansionFactorWhileEscaping); + int written = 0; + destination[written++] = (byte)'\\'; switch (value) { @@ -196,6 +200,8 @@ private static void EscapeNextBytes(byte value, Span destination, ref int written += bytesWritten; break; } + + totalWritten += written; } private static bool IsAsciiValue(byte value) => value <= LastAsciiCharacter; @@ -274,10 +280,14 @@ public static void EscapeString(ReadOnlySpan value, Span destination } } - private static void EscapeNextChars(char value, Span destination, ref int written) + private static void EscapeNextChars(char value, Span destination, ref int totalWritten) { Debug.Assert(IsAsciiValue(value)); + // Slice the span so the JIT can see that no bounds checks are needed below + destination = destination.Slice(totalWritten, JsonConstants.MaxExpansionFactorWhileEscaping); + int written = 0; + destination[written++] = '\\'; switch ((byte)value) { @@ -319,6 +329,8 @@ private static void EscapeNextChars(char value, Span destination, ref int #endif break; } + + totalWritten += written; } #if !NET