private static void Escape(TextWriter writer, string value)
{
if (string.IsNullOrEmpty(value))
return;
var startIndex = 0;
var currentIndex = 0;
var valueLength = value.Length;
char currentChar;
if (valueLength < 50)
{
// For short string, we can just pump each char directly to the writer
for (; currentIndex < valueLength; ++currentIndex)
{
currentChar = value[currentIndex];
switch (currentChar)
{
case '&':
writer.Write("&");
break;
case '<':
writer.Write("<");
break;
case '>':
writer.Write(">");
break;
case '"':
writer.Write(""");
break;
case '\'':
writer.Write("'");
break;
default:
writer.Write(currentChar);
break;
}
}
}
else
{
// For longer strings, the number of Write calls becomes prohibitive, so sacrifice a call to ToCharArray to allos us to buffer the Write calls
char[] chars = null;
for (; currentIndex < valueLength; ++currentIndex)
{
currentChar = value[currentIndex];
switch (currentChar)
{
case '&':
case '<':
case '>':
case '"':
case '\'':
if (chars == null) chars = value.ToCharArray();
if (currentIndex != startIndex) writer.Write(chars, startIndex, currentIndex - startIndex);
startIndex = currentIndex + 1;
switch (currentChar)
{
case '&':
writer.Write("&");
break;
case '<':
writer.Write("<");
break;
case '>':
writer.Write(">");
break;
case '"':
writer.Write(""");
break;
case '\'':
writer.Write("'");
break;
}
break;
}
}
if (startIndex == 0)
{
writer.Write(value);
return;
}
if (currentIndex != startIndex)
writer.Write(chars, startIndex, currentIndex - startIndex);
}
}