pub fn has_plain_identifier_shape(name: &str) -> bool {
let mut chars = name.chars();
chars
.next()
.is_some_and(|c| c.is_ascii() && (c == '_' || c.is_ascii_alphabetic()))
&& chars.all(|c| c.is_ascii() && (c == '_' || c.is_ascii_alphanumeric()))
}
pub fn quote_identifier_always(name: &str) -> String {
format!("`{}`", name.replace('`', "``"))
}
pub fn quote_identifier_shaped(name: &str) -> String {
if has_plain_identifier_shape(name) {
name.to_string()
} else {
quote_identifier_always(name)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_identifier_shape_is_ascii_only() {
for bare in ["a", "Person", "_x", "a1", "ship_date"] {
assert!(has_plain_identifier_shape(bare), "{bare}");
}
for quoted in ["", "1a", "a b", "a-b", "café", "we`ird", "a.b"] {
assert!(!has_plain_identifier_shape(quoted), "{quoted}");
}
}
#[test]
fn shaped_quoting_leaves_plain_names_bare_and_escapes_the_rest() {
assert_eq!(quote_identifier_shaped("Person"), "Person");
assert_eq!(quote_identifier_shaped("first name"), "`first name`");
assert_eq!(quote_identifier_shaped("we`ird"), "`we``ird`");
assert_eq!(quote_identifier_always("Person"), "`Person`");
}
}