Output: Escape special characters in C# strings properly

This commit is contained in:
Katy Coe
2019-11-15 05:14:49 +01:00
parent e5e77ed791
commit 92b964cd9c

View File

@@ -31,12 +31,37 @@ namespace Il2CppInspector.Reflection
public static string ToAddressString(this (ulong start, ulong end)? address) => ToAddressString(address?.start ?? 0) + "-" + ToAddressString(address?.end ?? 0); public static string ToAddressString(this (ulong start, ulong end)? address) => ToAddressString(address?.start ?? 0) + "-" + ToAddressString(address?.end ?? 0);
// C# string literal escape characters
// Taken from: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#regular-and-verbatim-string-literals
private static Dictionary<char, string> escapeChars = new Dictionary<char, string> {
['\''] = @"\'",
['"'] = @"\""",
['\\'] = @"\\",
['\0'] = @"\0",
['\a'] = @"\a",
['\b'] = @"\b",
['\f'] = @"\f",
['\n'] = @"\n",
['\r'] = @"\r",
['\t'] = @"\t",
['\v'] = @"\v"
};
// Output a value in C#-friendly syntax // Output a value in C#-friendly syntax
public static string ToCSharpValue(this object value) { public static string ToCSharpValue(this object value) {
if (value is bool) if (value is bool)
return (bool) value ? "true" : "false"; return (bool) value ? "true" : "false";
if (value is string) if (value is string str) {
return $"\"{value}\""; // Replace standard escape characters
var s = new StringBuilder();
for (var i = 0; i < str.Length; i++)
// Standard escape characters
s.Append(escapeChars.ContainsKey(str[i]) ? escapeChars[str[i]]
// Replace everything else with UTF-16 Unicode
: str[i] < 32 || str[i] > 126 ? @"\u" + $"{str[i]:X4}"
: str[i].ToString());
return $"\"{s}\"";
}
if (!(value is char)) if (!(value is char))
return (value?.ToString() ?? "null"); return (value?.ToString() ?? "null");
var cValue = (int) (char) value; var cValue = (int) (char) value;