Skip to main content

yog_codegen/
quote.rs

1//! Quoting text as a literal, by a language's own escapes.
2
3/// `text` between `delimiter`s, each character as `escape` says (`None`:
4/// as itself).
5pub fn quoted(text: &str, delimiter: char, escape: impl Fn(char) -> Option<String>) -> String {
6    let mut out = String::with_capacity(text.len() + 2);
7    out.push(delimiter);
8    for c in text.chars() {
9        match escape(c) {
10            Some(escaped) => out.push_str(&escaped),
11            None => out.push(c),
12        }
13    }
14    out.push(delimiter);
15    out
16}
17
18/// `c` as its UTF-16 units, each `prefix` and four hex digits (`é`).
19pub fn utf16_units(c: char, prefix: &str) -> String {
20    let mut units = [0u16; 2];
21    c.encode_utf16(&mut units)
22        .iter()
23        .map(|unit| format!("{prefix}{unit:04x}"))
24        .collect()
25}
26
27#[cfg(test)]
28mod tests;