Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify CharConstants.escapeChar() #171

Merged
merged 1 commit into from
May 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ class CharConstants private constructor(content: String) {
'_' to "\u00A0", // Unicode non-breaking-space
)

/** The reverse of [ESCAPE_REPLACEMENTS]: Map characters to the escaped replacement. */
private val escapedReplacements: Map<String, Char> =
ESCAPE_REPLACEMENTS.entries.associate { (k, v) -> v to k }

/**
* A mapping from a character to a number of bytes to read-ahead for that escape sequence. These
* escape sequences are used to handle unicode escaping in the following formats, where `H` is a
Expand All @@ -122,24 +126,21 @@ class CharConstants private constructor(content: String) {
)

/**
* Replace a single character with its string representation
* Replace a single character with a readable [String] representation
*
* @param char - the char to escape
* @return the same string or its escaped representation
*/
@JvmStatic
fun escapeChar(char: Char): String {
val charString = char.toString()
for (s in ESCAPE_REPLACEMENTS.keys) {
val v = ESCAPE_REPLACEMENTS[s]
if (" " == v || "/" == v || "\"" == v) {
continue
}
if (v == charString) {
return "\\" + s // '<TAB>' -> '\t'
}
}
return charString

// YAML requires these chars are escaped, but here we're just escaping for readability,
// so don't escape these chars:
if (char in " /\"") return charString

val escaped = escapedReplacements[charString] ?: return charString
return "\\${escaped}"
}
}
}
Loading