Skip to content

Commit

Permalink
Remove unsafe code from System.Web.HttpUtility (#43422)
Browse files Browse the repository at this point in the history
  • Loading branch information
GrabYourPitchforks authored Oct 15, 2020
1 parent 32a2976 commit b7998b2
Showing 1 changed file with 39 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<char> 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("&lt;");
break;
case '"':
output.Write("&quot;");
break;
case '\'':
output.Write("&#39;");
break;
case '&':
output.Write("&amp;");
break;
default:
output.Write(ch);
break;
}
}
else
switch (ch)
{
output.Write(ch);
case '<':
output.Write("&lt;");
break;
case '"':
output.Write("&quot;");
break;
case '\'':
output.Write("&#39;");
break;
case '&':
output.Write("&amp;");
break;
default:
output.Write(ch);
break;
}
}
else
{
output.Write(ch);
}
}
}
}
Expand Down Expand Up @@ -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<char> 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;
}
}
}
Expand Down

0 comments on commit b7998b2

Please sign in to comment.