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
/// Escapes XML special characters in a string.
pub struct StringXmlEscaper;
impl StringXmlEscaper {
/// Escapes XML special characters in a string, returning the escaped
/// result.
///
/// The following characters are replaced with their XML entity equivalents:
///
/// | Character | Replacement |
/// |-----------|-------------|
/// | `&` | `&` |
/// | `<` | `<` |
/// | `>` | `>` |
/// | `"` | `"` |
/// | `'` | `'` |
///
/// This makes the output safe for use as XML text content or attribute
/// values.
///
/// # Examples
///
/// ```rust
/// use disposition_input_ir_rt::StringXmlEscaper;
///
/// assert_eq!(StringXmlEscaper::escape("hello"), "hello");
/// assert_eq!(StringXmlEscaper::escape("a & b"), "a & b");
/// assert_eq!(StringXmlEscaper::escape("<tag>"), "<tag>");
/// assert_eq!(
/// StringXmlEscaper::escape(r#"say "hi""#),
/// "say "hi""
/// );
/// assert_eq!(StringXmlEscaper::escape("it's"), "it's");
/// ```
pub fn escape(s: &str) -> String {
let mut result = String::with_capacity(s.len());
s.chars().for_each(|c| match c {
'&' => result.push_str("&"),
'<' => result.push_str("<"),
'>' => result.push_str(">"),
'"' => result.push_str("""),
'\'' => result.push_str("'"),
_ => result.push(c),
});
result
}
}