]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/escape.rs
New upstream version 1.34.2+dfsg1
[rustc.git] / src / librustdoc / html / escape.rs
1 //! HTML escaping.
2 //!
3 //! This module contains one unit struct, which can be used to HTML-escape a
4 //! string of text (for use in a format string).
5
6 use std::fmt;
7
8 /// Wrapper struct which will emit the HTML-escaped version of the contained
9 /// string when passed to a format string.
10 pub struct Escape<'a>(pub &'a str);
11
12 impl<'a> fmt::Display for Escape<'a> {
13 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
14 // Because the internet is always right, turns out there's not that many
15 // characters to escape: http://stackoverflow.com/questions/7381974
16 let Escape(s) = *self;
17 let pile_o_bits = s;
18 let mut last = 0;
19 for (i, ch) in s.bytes().enumerate() {
20 match ch as char {
21 '<' | '>' | '&' | '\'' | '"' => {
22 fmt.write_str(&pile_o_bits[last.. i])?;
23 let s = match ch as char {
24 '>' => "&gt;",
25 '<' => "&lt;",
26 '&' => "&amp;",
27 '\'' => "&#39;",
28 '"' => "&quot;",
29 _ => unreachable!()
30 };
31 fmt.write_str(s)?;
32 last = i + 1;
33 }
34 _ => {}
35 }
36 }
37
38 if last < s.len() {
39 fmt.write_str(&pile_o_bits[last..])?;
40 }
41 Ok(())
42 }
43 }