From 2370355b3013474b3730e4125fb1259991c5c093 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Wed, 14 Oct 2020 14:38:23 -0700 Subject: [PATCH] Remove unsafe code from HttpEncoder --- .../src/System/Web/Util/HttpEncoder.cs | 87 +++++++++---------- 1 file changed, 39 insertions(+), 48 deletions(-) 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 68cc875b29d86..b97df74673f80 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 @@ -64,7 +64,7 @@ internal static void HtmlAttributeEncode(string? value, TextWriter output) HtmlAttributeEncodeInternal(value, output); } - private static unsafe void HtmlAttributeEncodeInternal(string s, TextWriter output) + private static void HtmlAttributeEncodeInternal(string s, TextWriter output) { int index = IndexOfHtmlAttributeEncodingChars(s, 0); if (index == -1) @@ -73,44 +73,37 @@ private static unsafe void HtmlAttributeEncodeInternal(string s, TextWriter outp } else { - int cch = s.Length - index; - fixed (char* str = s) - { - char* pch = str; - while (index-- > 0) - { - output.Write(*pch++); - } + output.Write(s.AsSpan(0, index)); - while (cch-- > 0) + ReadOnlySpan remaining = s.AsSpan(index); + for (int i = 0; i < remaining.Length; i++) + { + char ch = remaining[i]; + if (ch <= '<') { - char ch = *pch++; - if (ch <= '<') - { - switch (ch) - { - case '<': - output.Write("<"); - break; - case '"': - output.Write("""); - break; - case '\'': - output.Write("'"); - break; - case '&': - output.Write("&"); - break; - default: - output.Write(ch); - break; - } - } - else + switch (ch) { - output.Write(ch); + case '<': + output.Write("<"); + break; + case '"': + output.Write("""); + break; + case '\'': + output.Write("'"); + break; + case '&': + output.Write("&"); + break; + default: + output.Write(ch); + break; } } + else + { + output.Write(ch); + } } } } @@ -141,25 +134,23 @@ internal static void HtmlEncode(string? value, TextWriter output) output.Write(WebUtility.HtmlEncode(value)); } - private static unsafe int IndexOfHtmlAttributeEncodingChars(string s, int startPos) + private static int IndexOfHtmlAttributeEncodingChars(string s, int startPos) { Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length"); - int cch = s.Length - startPos; - fixed (char* str = s) + + ReadOnlySpan span = s.AsSpan(startPos); + for (int i = 0; i < span.Length; i++) { - for (char* pch = &str[startPos]; cch > 0; pch++, cch--) + char ch = span[i]; + if (ch <= '<') { - char ch = *pch; - if (ch <= '<') + switch (ch) { - switch (ch) - { - case '<': - case '"': - case '\'': - case '&': - return s.Length - cch; - } + case '<': + case '"': + case '\'': + case '&': + return startPos + i; } } }