### Default HtmlSanitizer Instance
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/lib.rs.html
Provides a globally accessible, lazily initialized `HtmlSanitizer` instance using the default allow list. This is useful for quick sanitization without explicit setup.
```rust
fn default_sanitizer() -> &'static HtmlSanitizer {
static INSTANCE: OnceLock = OnceLock::new();
INSTANCE.get_or_init(HtmlSanitizer::new)
}
```
--------------------------------
### Get Allowed Tag
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Retrieves the allowed `Tag` configuration based on the current `tag_idx`. Returns `None` if `tag_idx` is not set.
```rust
fn tag(&self) -> Option<&Tag> {
self.tag_idx.map(|i| &self.allow_list.tags[i])
}
```
--------------------------------
### Handle Less-Than Sign State
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Manages the state immediately after encountering a '<' character. It determines if it's the start of a closing tag ('/'), a non-HTML tag, or a new tag name.
```rust
fn s_lt_sign(&mut self, data: &[u8], off: &mut usize) -> io::Result<()> {
let b = data[*off];
match b {
b'/' => {
*off += 1;
self.state = State::ETagStart;
self.tag_name.clear();
}
_ if self.non_html_tag_idx.is_some() => {
self.state = State::NonHtml;
if self.keep_non_html {
self.buf.extend_from_slice(b"<");
}
}
_ => {
*off += 1;
if legal_keyword_byte(b) {
self.state = State::TagName;
self.tag_name.clear();
self.tag_name.push(b);
self.tag_idx = None;
return Ok(());
}
self.state = State::ErrTag;
}
}
Ok(())
}
```
--------------------------------
### Start of an End Tag
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Initiates the processing of an end tag, checking for valid keyword bytes and handling non-HTML tags.
```rust
fn s_etag_start(&mut self, data: &[u8], off: &mut usize) -> io::Result<()> {
let b = data[*off];
if legal_keyword_byte(b) {
*off += 1;
self.tag_name.clear();
self.tag_name.push(b);
self.state = State::ETagName;
} else if self.non_html_tag_idx.is_some() {
self.state = State::NonHtml;
if self.keep_non_html {
self.buf.extend_from_slice(b"</");
}
} else {
self.state = State::ErrTag;
}
Ok(())
}
```
--------------------------------
### Try Unescape HTML Entity
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Attempts to unescape a single HTML entity starting at the given byte position. It distinguishes between numeric and named entities.
```rust
fn try_unescape_entity(bytes: &[u8], start: usize) -> Option<(String, usize)> {
let rest = &bytes[start..];
if rest.len() < 2 {
return None;
}
// Numeric character reference: ...
if rest[1] == b'#' {
return try_unescape_numeric(rest);
}
// Named character reference
try_unescape_named(rest)
}
```
--------------------------------
### Create Default HTML Allow List
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/tags.rs.html
Initializes a default `AllowList` that mirrors the Go `DefaultAllowList`, pre-populating it with common HTML tags and their allowed attributes.
```rust
pub fn default_allow_list() -> AllowList {
AllowList {
tags: vec![
Tag::new("address", &[], &[]),
Tag::new("article", &[], &[]),
Tag::new("aside", &[], &[]),
Tag::new("footer", &[], &[]),
Tag::new("header", &[], &[]),
Tag::new("h1", &[], &[]),
Tag::new("h2", &[], &[]),
Tag::new("h3", &[], &[]),
Tag::new("h4", &[], &[]),
Tag::new("h5", &[], &[]),
Tag::new("h6", &[], &[]),
Tag::new("hgroup", &[], &[]),
Tag::new("main", &[], &[]),
Tag::new("nav", &[], &[]),
Tag::new("section", &[], &[]),
Tag::new("blockquote", &[], &["cite"]),
Tag::new("dd", &[], &[]),
Tag::new("div", &[], &[]),
Tag::new("dl", &[], &[]),
Tag::new("dt", &[], &[]),
Tag::new("figcaption", &[], &[]),
Tag::new("figure", &[], &[]),
Tag::new("hr", &[], &[]),
Tag::new("li", &[], &[]),
Tag::new("ol", &[], &[]),
],
global_attr: vec![],
non_html_tags: vec![],
tag_map: None,
non_html_tag_map: None,
}
}
```
--------------------------------
### Get Non-HTML Tag Name
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Retrieves the name of the current non-HTML tag being processed. Returns `None` if `non_html_tag_idx` is not set.
```rust
fn non_html_tag_name(&self) -> Option<&str> {
self.non_html_tag_idx
.map(|i| self.allow_list.non_html_tags[i].name.as_str())
}
```
--------------------------------
### default_allow_list
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/fn.default_allow_list.html
Creates the default allow list matching the Go `DefaultAllowList`.
```APIDOC
## Function default_allow_list
### Summary
```rust
pub fn default_allow_list() -> AllowList
```
### Description
Create the default allow list matching the Go `DefaultAllowList`.
```
--------------------------------
### Create New HtmlSanitizer
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/struct.HtmlSanitizer.html
Instantiate a new HtmlSanitizer with the default allow list.
```rust
pub fn new() -> Self
```
--------------------------------
### HtmlSanitizer::new
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/lib.rs.html
Creates a new HtmlSanitizer instance with the default allow list and a default URL sanitizer.
```APIDOC
/// Create a new sanitizer with a clone of the default allow list.
pub fn new() -> Self
```
--------------------------------
### HtmlSanitizer::new
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/struct.HtmlSanitizer.html
Creates a new HtmlSanitizer instance with a clone of the default allow list.
```APIDOC
## HtmlSanitizer::new
### Description
Create a new sanitizer with a clone of the default allow list.
### Method
`pub fn new() -> Self`
```
--------------------------------
### Try Convert AllowList
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.AllowList.html
Attempts to convert a value into `AllowList`. Returns `Ok(AllowList)` on success or an error if the conversion fails.
```rust
type Error = Infallible;
fn try_from(value: U) -> Result>::Error>
```
--------------------------------
### Tag::new
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.Tag.html
Constructs a new Tag instance with the specified name and allowed attributes.
```APIDOC
### impl Tag
#### pub fn new(name: &str, attr: &[&str], url_attr: &[&str]) -> Self
Creates a new Tag.
```
--------------------------------
### Create a New Tag Instance
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.Tag.html
Constructs a new Tag instance with specified allowed attributes. Ensure attribute names are lowercase for consistency.
```rust
pub fn new(name: &str, attr: &[&str], url_attr: &[&str]) -> Self
```
--------------------------------
### Initialize SanitizeWriter
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/dfa.rs.html
Creates a new `SanitizeWriter` instance with the provided writer, allow list, and URL sanitizer function. Initializes the internal state for HTML sanitization.
```rust
pub fn new(w: W, allow_list: AllowList, url_sanitizer: UrlSanitizerFn) -> Self {
Self {
allow_list,
url_sanitizer,
w,
state: State::Normal,
tag_name: Vec::new(),
tag_idx: None,
non_html_tag_idx: None,
keep_non_html: false,
attr: Vec::new(),
val: Vec::new(),
quote: 0,
last_byte: 0,
buf: Vec::new(),
}
}
```
--------------------------------
### Configure HtmlSanitizer with Custom URL Sanitizer
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/lib.rs.html
Creates a new `HtmlSanitizer` and sets a custom URL sanitizer function. The function should return `Some(String)` with the sanitized URL or `None` to disallow it.
```rust
pub fn with_url_sanitizer(mut self, f: F) -> Self
where
F: Fn(&str) -> Option + Send + Sync + 'static,
{
self.url_sanitizer = Arc::new(f);
self
}
```
--------------------------------
### URL Path and Query Parsing
Source: https://docs.rs/htmlsanitizer/latest/src/htmlsanitizer/url.rs.html
Parses a raw URL string to separate the path, query, and fragment components. Handles potential encoding issues before further processing.
```rust
let (raw_url, fragment) = match raw_url.find('#') {
Some(pos) => (&raw_url[..pos], Some(&raw_url[pos + 1..])),
None => (raw_url, None),
};
let (path_part, query) = match rest.find('?') {
Some(pos) => (&rest[..pos], Some(&rest[pos + 1..])),
None => (rest, None),
};
// Percent-decode the path first (in case it had existing encoding),
// then re-encode using Go rules
let decoded = percent_decode(path_part);
let mut result = go_path_encode(&decoded);
if let Some(q) = query {
result.push('?');
result.push_str(q);
}
if let Some(f) = fragment {
result.push('#');
result.push_str(f);
}
Some(result)
}
Err(_) => None,
}
}
```
--------------------------------
### Create HtmlSanitizer with Custom URL Sanitizer
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/struct.HtmlSanitizer.html
Create a new sanitizer instance and provide a custom URL sanitizer function. The function takes a URL string and returns an optional sanitized URL string.
```rust
pub fn with_url_sanitizer(self, f: F) -> Self
where F: Fn(&str) -> Option + Send + Sync + 'static,
```
--------------------------------
### Clone AllowList
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.AllowList.html
Creates a deep copy of the `AllowList`. Use this when you need an independent copy of the sanitization rules.
```rust
fn clone(&self) -> AllowList
```
--------------------------------
### impl AllowList
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.AllowList.html
Methods available for the AllowList struct.
```APIDOC
pub fn attr_exists(&self, name: &[u8]) -> bool
Check whether a global attribute exists.
pub fn check_non_html_tag(&mut self, name: &str) -> Option
Check if a tag name is a non-HTML tag (e.g. `script`, `style`). The name must already be lowercased.
pub fn add_tag(&mut self, tag: Tag)
Add a tag to the allow list.
pub fn remove_tag(&mut self, name: &str)
Remove all tags with the given name (must be lowercase).
pub fn find_tag(&mut self, name: &str) -> Option
Find a tag by its lowercased name.
```
--------------------------------
### Unsafe Clone to Uninit
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.AllowList.html
Nightly-only experimental function to clone the `AllowList` into an uninitialized memory location. Use with extreme caution.
```rust
unsafe fn clone_to_uninit(&self, dest: *mut u8)
```
--------------------------------
### SanitizeWriter::new Constructor
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/dfa/struct.SanitizeWriter.html
Creates a new SanitizeWriter instance. It requires a writer, an AllowList, and a URL sanitizer function.
```rust
pub fn new( w: W, allow_list: AllowList, url_sanitizer: Arc Option + Send + Sync>, ) -> Self
```
--------------------------------
### impl Default for HtmlSanitizer
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/struct.HtmlSanitizer.html
Provides a default value for HtmlSanitizer, which is equivalent to calling `HtmlSanitizer::new()`.
```APIDOC
## impl Default for HtmlSanitizer
### Description
Returns the “default value” for a type.
### Method
`fn default() -> Self`
```
--------------------------------
### SanitizeWriter::new
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/dfa/struct.SanitizeWriter.html
Constructs a new SanitizeWriter. It takes an underlying writer, an AllowList for sanitization rules, and a URL sanitizer function.
```APIDOC
## fn new(w: W, allow_list: AllowList, url_sanitizer: Arc Option + Send + Sync>) -> Self
Constructs a new SanitizeWriter.
### Parameters
- `w`: The underlying writer to which sanitized content will be written.
- `allow_list`: An `AllowList` specifying which HTML tags and attributes are permitted.
- `url_sanitizer`: A function that sanitizes URLs found in attributes like `href` or `src`.
```
--------------------------------
### AllowList Fields
Source: https://docs.rs/htmlsanitizer/latest/htmlsanitizer/tags/struct.AllowList.html
Details the fields within the AllowList struct.
```APIDOC
tags: Vec - Allowed tags.
global_attr: Vec - Globally allowed attributes (e.g. `class`, `id`).
non_html_tags: Vec - Non-HTML tags like `