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
48
49
50
51
//! A lightweight layer on top of [Hyper](https://hyper.rs/)
//! to facilitate building web applications.

#![cfg_attr(docsrs, feature(doc_cfg))]

use std::borrow::Cow;

pub use httpdate;
pub use mime;

pub mod request;
pub mod response;

#[cfg(feature = "hyper_body")]
#[cfg_attr(docsrs, doc(cfg(feature = "hyper_body")))]
pub mod hyper_body;

#[cfg(not(feature = "hyper_body"))]
use http;
#[cfg(feature = "hyper_body")]
use hyper::http;

/// HTML escapes the given string.
///
/// The following characters are escaped: `<`, `>`, `&`, `"`, `'`.
/// To mitigate the risks of forgetting to HTML escape something,
/// it is recommended to additionally set a strict [Content Security
/// Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).
pub fn html_escape<'a, S: Into<Cow<'a, str>>>(input: S) -> Cow<'a, str> {
    let input = input.into();
    fn is_trouble(c: char) -> bool {
        c == '<' || c == '>' || c == '&' || c == '"' || c == '\''
    }

    if input.contains(is_trouble) {
        let mut output = String::with_capacity(input.len());
        for c in input.chars() {
            match c {
                '<' => output.push_str("&lt;"),
                '>' => output.push_str("&gt;"),
                '&' => output.push_str("&amp;"),
                '"' => output.push_str("&quot;"),
                '\'' => output.push_str("&#x27;"),
                _ => output.push(c),
            }
        }
        Cow::Owned(output)
    } else {
        input
    }
}