1 unstable release
Uses new Rust 2024
| 0.1.0 | Jan 17, 2026 |
|---|
#672 in Encoding
Used in plait
135KB
2.5K
SLoC
hescape
A fast and lightweight HTML escape/unescape library for Rust.
This crate provides functions to escape and unescape HTML special characters, which is essential for preventing XSS (Cross-Site Scripting) attacks and correctly rendering user-provided content in HTML documents.
Escaping
The escape function converts the following characters to their HTML entity equivalents:
| Character | Entity |
|---|---|
& |
& |
< |
< |
> |
> |
" |
" |
' |
' |
Example
use hescape::escape;
let input = "<script>alert(\"xss\")</script>";
let escaped = escape(input);
assert_eq!(escaped, "<script>alert("xss")</script>");
Unescaping
The unescape function converts HTML entities back to their original characters.
It supports:
- Named references:
&,<,>,",', and many more. - Decimal numeric references:
',<, etc. - Hexadecimal numeric references:
',<, etc.
Example
use hescape::unescape;
let input = "<div>Hello & welcome!</div>";
let unescaped = unescape(input);
assert_eq!(unescaped, "<div>Hello & welcome!</div>");
Writing to a buffer
For performance-sensitive applications, you can use escape_to and unescape_to to write directly to any
type implementing core::fmt::Write:
use hescape::escape_to;
let mut buffer = String::new();
escape_to(&mut buffer, "Hello <world>").unwrap();
assert_eq!(buffer, "Hello <world>");
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.