-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCharUtils.cs
More file actions
91 lines (83 loc) · 2.72 KB
/
CharUtils.cs
File metadata and controls
91 lines (83 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
namespace GameDialog.Lang
{
/// <summary>
/// Utility methods for character and string operations.
/// </summary>
internal static class CharUtils
{
/// <summary>
/// Checks if the character is a newline character.
/// </summary>
public static bool IsNewLine(this char c)
{
return c is '\n' or '\r' or '\u2028' or '\u2029' or '\u0085';
}
/// <summary>
/// Formats a character as a readable C-style literal, escaping control characters when necessary.
/// </summary>
/// <param name="c">The character to format.</param>
public static string ToPrintable(this char c)
{
return c switch
{
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
'\b' => "\\b",
'\f' => "\\f",
'\0' => "\\0",
' ' => "' '",
_ when char.IsControl(c) => $"\\u{(int)c:X4}",
_ => c.ToString(),
};
}
/// <summary>
/// Formats an integer as a readable C-style literal, escaping control characters when necessary.
/// </summary>
/// <param name="n">The integer to format.</param>
public static string ToPrintable(this int n)
{
return n is -1 ? "<EOF>" : ((char)n).ToPrintable();
}
/// <summary>
/// Checks if the integer represents a newline character.
/// </summary>
public static bool IsNewLine(this int n)
{
return n is not -1 && ((char)n).IsNewLine();
}
/// <summary>
/// Checks if the integer represents the end of source code.
/// </summary>
public static bool IsEndOfSource(this int n)
{
return n is -1;
}
/// <summary>
/// Checks if the integer represents a whitespace character that is not a newline.
/// </summary>
public static bool IsWhiteSpace(this int n)
{
return n is not -1 && char.IsWhiteSpace((char)n) && !((char)n).IsNewLine();
}
/// <summary>
/// Checks if the integer represents a valid identifier character.
/// </summary>
public static bool IsLetterOrDigit(this int n)
{
if (n is -1)
{
return false;
}
var c = (char)n;
return c is '_' || char.IsLetterOrDigit(c);
}
/// <summary>
/// Checks if the integer represents a digit character.
/// </summary>
public static bool IsDigit(this int n)
{
return n is not -1 && char.IsDigit((char)n);
}
}
}