public override void WriteString(string text)
{
// The start index of the next substring containing only non-entitized characters.
int start = 0;
// The index of the current character being checked.
for (int curr = 0; curr < text.Length; ++curr)
{
// Check whether the current character should be entitized.
char chr = text[curr];
if (Encoding.UTF8.GetBytes(new[] {chr}).Length != 1)
{
// Write the previous substring of non-entitized characters.
if (start < curr)
base.WriteString(text.Substring(start, curr - start));
if (char.IsHighSurrogate(chr))
{
if (curr + 1 < text.Length)
{
WriteSurrogateCharEntity(text[++curr], chr);
}
else
{
throw new ArgumentException("Invalid surrogate pair");
}
}
else if (char.IsLowSurrogate(chr))
{
throw new ArgumentException("Invalid surrogate pair");
}
else
{
WriteCharEntity(chr);
}
// Next substring of non-entitized characters tentatively starts
// immediately beyond current character.
start = curr + 1;
}
}
// Write the trailing substring of non-entitized characters.
if (start < text.Length)
base.WriteString(text.Substring(start, text.Length - start));
}