private static bool TryReplaceChar(char c, out string replaceWith) { replaceWith = null; switch (c) { case char.MinValue: replaceWith = "\\0"; break; case '\a': replaceWith = "\\a"; break; case '\b': replaceWith = "\\b"; break; case '\t': replaceWith = "\\t"; break; case '\n': replaceWith = "\\n"; break; case '\v': replaceWith = "\\v"; break; case '\f': replaceWith = "\\f"; break; case '\r': replaceWith = "\\r"; break; case '\\': replaceWith = "\\\\"; break; } if (replaceWith != null) { return(true); } if (!ObjectDisplay.NeedsEscaping(CharUnicodeInfo.GetUnicodeCategory(c))) { return(false); } replaceWith = "\\u" + ((int)c).ToString("x4"); return(true); }
public static string FormatLiteral(string value, ObjectDisplayOptions options) { if (value == null) { throw new ArgumentNullException(nameof(value)); } StringBuilder builder = new StringBuilder(); bool flag1 = options.IncludesOption(ObjectDisplayOptions.UseQuotes); bool flag2 = options.IncludesOption(ObjectDisplayOptions.EscapeNonPrintableCharacters); bool flag3 = flag1 && !flag2 && ObjectDisplay.ContainsNewLine(value); if (flag1) { if (flag3) { builder.Append('@'); } builder.Append('"'); } for (int index = 0; index < value.Length; ++index) { char ch = value[index]; if (flag2 && CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.Surrogate) { UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(value, index); if (unicodeCategory == UnicodeCategory.Surrogate) { builder.Append("\\u" + ((int)ch).ToString("x4")); } else if (ObjectDisplay.NeedsEscaping(unicodeCategory)) { int utf32 = char.ConvertToUtf32(value, index); builder.Append("\\U" + utf32.ToString("x8")); ++index; } else { builder.Append(ch); builder.Append(value[++index]); } } else { string replaceWith; if (flag2 && ObjectDisplay.TryReplaceChar(ch, out replaceWith)) { builder.Append(replaceWith); } else if (flag1 && ch == '"') { if (flag3) { builder.Append('"'); builder.Append('"'); } else { builder.Append('\\'); builder.Append('"'); } } else { builder.Append(ch); } } } if (flag1) { builder.Append('"'); } return(builder.ToString()); }