systemd/unit.rs
1/// Escape a string for use in a systemd unit name.
2///
3/// See [String Escaping for Inclusion in Unit Names][1] for more information.
4///
5/// [1]: https://www.freedesktop.org/software/systemd/man/systemd.unit.html#String%20Escaping%20for%20Inclusion%20in%20Unit%20Names
6pub fn escape_name(s: &str) -> String {
7 let mut escaped = String::with_capacity(s.len() * 2);
8 for (index, b) in s.bytes().enumerate() {
9 match b {
10 b'/' => escaped.push('-'),
11 // Do not escape '.' unless it's the first character
12 b'.' if 0 < index => escaped.push(char::from(b)),
13 // Do not escape _ and : and
14 b'_' | b':' => escaped.push(char::from(b)),
15 // all ASCII alphanumeric characters
16 _ if b.is_ascii_alphanumeric() => escaped.push(char::from(b)),
17 _ => escaped.push_str(&format!("\\x{b:02x}")),
18 }
19 }
20 escaped
21}