html_escape/lib.rs
1/*!
2# HTML Escape
3
4This library is for encoding/escaping special characters in HTML and decoding/unescaping HTML entities as well.
5
6## Usage
7
8### Encoding
9
10This crate provides some `encode_*` functions to encode HTML text in different situations.
11
12Escaping is context-sensitive.
13Use `encode_text` for text, quoted attribute encoders for quoted attributes, `encode_unquoted_attribute` for unquoted attributes, and script or style encoders for raw-text elements.
14`encode_safe` is not a context-independent sanitizer.
15
16For example, to put a text between a start tag `<foo>` and an end tag `</foo>`, use the `encode_text` function to escape every `&`, `<`, and `>` in the text.
17
18```rust
19assert_eq!("a > b && a < c", html_escape::encode_text("a > b && a < c"));
20```
21
22The functions suffixed with `_to_writer`, `_to_vec` or `_to_string` are useful to generate HTML.
23
24```rust
25let mut html = String::from("<input value=");
26assert_eq!("Hello world!", html_escape::encode_unquoted_attribute_to_string("Hello world!", &mut html));
27html.push_str(" placeholder=\"");
28assert_eq!("The default value is "Hello world!".", html_escape::encode_double_quoted_attribute_to_string("The default value is \"Hello world!\".", &mut html));
29html.push_str("\"/><script>alert('");
30assert_eq!(r"<script>\'s end tag is <\/script>", html_escape::encode_script_single_quoted_text_to_string("<script>'s end tag is </script>", &mut html));
31html.push_str("');</script>");
32
33assert_eq!("<input value=Hello world! placeholder=\"The default value is "Hello world!".\"/><script>alert(\'<script>\\\'s end tag is <\\/script>\');</script>", html);
34```
35
36### Decoding
37
38Decoding accepts exact named and numeric character references ending with `;`.
39It does not apply legacy semicolonless references or C1 control replacements used by browser tokenizers.
40
41```rust
42assert_eq!("Hello world!", html_escape::decode_html_entities("Hello world!"));
43```
44
45```rust
46assert_eq!("alert('<script></script>');", html_escape::decode_script(r"alert('<script><\/script>');"));
47```
48
49## No Std
50
51Disable the default features to compile this crate without std.
52
53```toml
54[dependencies.html-escape]
55version = "*"
56default-features = false
57```
58
59## Benchmark
60
61```bash
62cargo bench
63```
64*/
65
66#![cfg_attr(not(feature = "std"), no_std)]
67#![cfg_attr(docsrs, feature(doc_cfg))]
68
69extern crate alloc;
70
71mod decode;
72mod encode;
73mod functions;
74
75pub use decode::*;
76pub use encode::*;