Veil.Helpers.Escape C# (CSharp) Method

Escape() private static method

private static Escape ( TextWriter writer, string value ) : void
writer System.IO.TextWriter
value string
return void
		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("&amp;");
							break;
						case '<':
							writer.Write("&lt;");
							break;
						case '>':
							writer.Write("&gt;");
							break;
						case '"':
							writer.Write("&quot;");
							break;
						case '\'':
							writer.Write("&#39;");
							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("&amp;");
									break;
								case '<':
									writer.Write("&lt;");
									break;
								case '>':
									writer.Write("&gt;");
									break;
								case '"':
									writer.Write("&quot;");
									break;
								case '\'':
									writer.Write("&#39;");
									break;
							}
							break;
					}
				}

				if (startIndex == 0)
				{
					writer.Write(value);
					return;
				}

				if (currentIndex != startIndex)
					writer.Write(chars, startIndex, currentIndex - startIndex);
			}
		}