diff --git a/src/libraries/System.Web.HttpUtility/src/System.Web.HttpUtility.csproj b/src/libraries/System.Web.HttpUtility/src/System.Web.HttpUtility.csproj index f62eca42ec097..5da18b0fae6c8 100644 --- a/src/libraries/System.Web.HttpUtility/src/System.Web.HttpUtility.csproj +++ b/src/libraries/System.Web.HttpUtility/src/System.Web.HttpUtility.csproj @@ -17,6 +17,8 @@ Link="Common\System\HexConverter.cs" /> + diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs index eb4cc68ca8c24..d03236dd9909c 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs @@ -141,56 +141,63 @@ internal static string JavaScriptStringEncode(string? value, bool addDoubleQuote return addDoubleQuotes ? $"\"{value}\"" : value; } - var vsb = new ValueStringBuilder(stackalloc char[512]); - if (addDoubleQuotes) - { - vsb.Append('"'); - } - ReadOnlySpan chars = value; - do + return EncodeCore(value, i, addDoubleQuotes); + + static string EncodeCore(ReadOnlySpan value, int i, bool addDoubleQuotes) { - vsb.Append(chars.Slice(0, i)); - char c = chars[i]; - chars = chars.Slice(i + 1); - switch (c) + var vsb = new ValueStringBuilder(stackalloc char[512]); + if (addDoubleQuotes) { - case '\r': - vsb.Append("\\r"); - break; - case '\t': - vsb.Append("\\t"); - break; - case '\"': - vsb.Append("\\\""); - break; - case '\\': - vsb.Append("\\\\"); - break; - case '\n': - vsb.Append("\\n"); - break; - case '\b': - vsb.Append("\\b"); - break; - case '\f': - vsb.Append("\\f"); - break; - default: - vsb.Append($"\\u{(int)c:x4}"); - break; + vsb.Append('"'); } - i = chars.IndexOfAny(s_invalidJavaScriptChars); - } while (i >= 0); + ReadOnlySpan chars = value; + do + { + vsb.Append(chars.Slice(0, i)); + char c = chars[i]; + chars = chars.Slice(i + 1); + switch (c) + { + case '\r': + vsb.Append("\\r"); + break; + case '\t': + vsb.Append("\\t"); + break; + case '\"': + vsb.Append("\\\""); + break; + case '\\': + vsb.Append("\\\\"); + break; + case '\n': + vsb.Append("\\n"); + break; + case '\b': + vsb.Append("\\b"); + break; + case '\f': + vsb.Append("\\f"); + break; + default: + vsb.Append("\\u"); + vsb.AppendSpanFormattable((int)c, "x4"); + break; + } - vsb.Append(chars); + i = chars.IndexOfAny(s_invalidJavaScriptChars); + } while (i >= 0); - if (addDoubleQuotes) - { - vsb.Append('"'); - } + vsb.Append(chars); - return vsb.ToString(); + if (addDoubleQuotes) + { + vsb.Append('"'); + } + + return vsb.ToString(); + } } [return: NotNullIfNotNull(nameof(bytes))]