### Handle conflicting attribute configurations Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Examples demonstrating configurations that cause panics versus valid configurations. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .generic_attributes(hashset!["rel"]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .generic_attributes(hashset!["rel"]) .link_rel(None) .clean(""); ``` ```rust use ammonia::Builder; use maplit::{hashmap, hashset}; Builder::default() .generic_attributes(hashset!["class"]) .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::{hashmap, hashset}; Builder::default() .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .clean_content_tags(hashset!["aside"]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .rm_tags(&["aside"]) .clean_content_tags(hashset!["aside"]) .clean(""); ``` -------------------------------- ### Basic HTML Sanitization Example Source: https://docs.rs/ammonia/latest/ammonia/fn.clean.html?search= Demonstrates the removal of script tags from an input string using default settings. ```rust assert_eq!(ammonia::clean("XSS"), "XSS") ``` -------------------------------- ### Get host string representation Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the string representation of the host, handling punycode for non-ASCII domains and brackets for IPv6. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert_eq!(url.host_str(), Some("127.0.0.1")); let url = Url::parse("https://subdomain.example.com")?; assert_eq!(url.host_str(), Some("subdomain.example.com")); let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.host_str(), Some("example.com")); let url = Url::parse("unix:/run/foo.socket")?; assert_eq!(url.host_str(), None); let url = Url::parse("data:text/plain,Stuff")?; assert_eq!(url.host_str(), None); ``` -------------------------------- ### Get URL Scheme Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the lower-cased ASCII scheme without the colon delimiter. ```rust use url::Url; let url = Url::parse("file:///tmp/foo")?; assert_eq!(url.scheme(), "file"); ``` -------------------------------- ### Get domain name Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the domain name if the host is a domain, excluding IP addresses. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/")?; assert_eq!(url.domain(), None); let url = Url::parse("mailto:rms@example.net")?; assert_eq!(url.domain(), None); let url = Url::parse("https://example.com/")?; assert_eq!(url.domain(), Some("example.com")); let url = Url::parse("https://subdomain.example.com/")?; assert_eq!(url.domain(), Some("subdomain.example.com")); ``` -------------------------------- ### Custom URL Evaluation Source: https://docs.rs/ammonia/latest/ammonia/enum.UrlRelative.html Example of using the Custom variant to provide a user-defined function for URL transformation. ```rust use std::borrow::Cow; fn is_absolute_path(url: &str) -> bool { let u = url.as_bytes(); // `//a/b/c` is "protocol-relative", meaning "a" is a hostname // `/a/b/c` is an absolute path, and what we want to do stuff to. u.get(0) == Some(&b'/') && u.get(1) != Some(&b'/') } fn evaluate(url: &str) -> Option> { if is_absolute_path(url) { Some(Cow::Owned(String::from("/root") + url)) } else { Some(Cow::Borrowed(url)) } } fn main() { let a = ammonia::Builder::new() .url_relative(ammonia::UrlRelative::Custom(Box::new(evaluate))) .clean("fixedpassedskipped") .to_string(); assert_eq!(a, "fixedpassedskipped"); } ``` -------------------------------- ### Get URL port Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the explicit port number, ignoring default ports. ```rust use url::Url; let url = Url::parse("https://example.com")?; assert_eq!(url.port(), None); let url = Url::parse("https://example.com:443/")?; assert_eq!(url.port(), None); let url = Url::parse("ssh://example.com:22")?; assert_eq!(url.port(), Some(22)); ``` -------------------------------- ### Retrieving link relationship settings Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Gets the current link relationship attribute configuration. ```rust use ammonia::{Builder, UrlRelative}; let mut a = Builder::default(); a.link_rel(Some("a b")); assert_eq!(a.get_link_rel(), Some("a b")); ``` -------------------------------- ### Construct new Builder Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Creates a Builder instance with default configuration options. ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the new() function."; let output = "This is an Ammonia example using the new() function."; let result = Builder::new() // <-- .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output); ``` -------------------------------- ### pub fn password(&self) -> Option<&str> Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the password for the URL, if any, as a percent-encoded ASCII string. ```APIDOC ## pub fn password(&self) -> Option<&str> ### Description Returns the password for this URL, if any, as a percent-encoded ASCII string. ``` -------------------------------- ### Builder::new() Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=u32+-%3E+bool Constructs a new Builder instance with default configuration options. ```APIDOC ## pub fn new() -> Self ### Description Constructs a `Builder` instance configured with the default options. ``` -------------------------------- ### Get parsed host representation Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the parsed Host enum representation of the URL host. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert!(url.host().is_some()); let url = Url::parse("ftp://rms@example.com")?; assert!(url.host().is_some()); let url = Url::parse("unix:/run/foo.socket")?; assert!(url.host().is_none()); let url = Url::parse("data:text/plain,Stuff")?; assert!(url.host().is_none()); ``` -------------------------------- ### Url::join Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Parses a string as a URL, using the current instance as the base URL. ```APIDOC ## pub fn join(&self, input: &str) -> Result ### Description Parses a string as an URL, with this URL as the base URL. ### Parameters - **input** (&str) - The relative or absolute URL string to join with the base. ### Returns - **Result** - Returns the joined Url or a ParseError. ``` -------------------------------- ### Get tag attribute value Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Retrieves the value currently set for a specific tag attribute. ```rust let mut b = ammonia::Builder::default(); b.set_tag_attribute_value("a", "target", "_blank"); let value = b.get_set_tag_attribute_value("a", "target"); assert_eq!(value, Some("_blank")); ``` -------------------------------- ### pub fn host(&self) -> Option> Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the parsed representation of the host for this URL. ```APIDOC ## pub fn host(&self) -> Option> ### Description Returns the parsed representation of the host for this URL. Non-ASCII domain labels are handled according to IDNA or percent-encoding rules. ``` -------------------------------- ### Serialize URL to String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the string representation of the URL. ```rust use url::Url; let url_str = "https://example.net/"; let url = Url::parse(url_str)?; assert_eq!(url.as_str(), url_str); ``` -------------------------------- ### pub fn host_str(&self) -> Option<&str> Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the string representation of the host for this URL, if any. ```APIDOC ## pub fn host_str(&self) -> Option<&str> ### Description Returns the string representation of the host (domain or IP address) for this URL, if any. Non-ASCII domains are punycode-encoded or percent-encoded depending on the URL type. ``` -------------------------------- ### pub fn into_string(self) -> String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Returns the serialization of this URL. This consumes the Url and takes ownership of the String stored in it. ```APIDOC ## pub fn into_string(self) -> String ### Description Returns the serialization of this URL. This consumes the `Url` and takes ownership of the `String` stored in it. ### Note Deprecated since 2.3.0: use Into. ``` -------------------------------- ### Get port or known default Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the port number, including known defaults for common schemes like http and https. ```rust use url::Url; let url = Url::parse("foo://example.com")?; assert_eq!(url.port_or_known_default(), None); let url = Url::parse("foo://example.com:1456")?; assert_eq!(url.port_or_known_default(), Some(1456)); let url = Url::parse("https://example.com")?; assert_eq!(url.port_or_known_default(), Some(443)); ``` -------------------------------- ### pub fn from_directory_path

(path: P) -> Result Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Converts a directory path into a URL with a trailing slash. ```APIDOC ## pub fn from_directory_path

(path: P) -> Result ### Description Convert a directory name as `std::path::Path` into an URL in the `file` scheme. Ensures the URL path has a trailing slash to correctly handle base URL resolution. ### Parameters - **path** (P) - Required - The directory path to convert. ``` -------------------------------- ### Retrieve URL Path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the percent-encoded ASCII path of the URL. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Convert URL to String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Consumes the Url instance and returns the underlying String representation. ```rust use url::Url; let url_str = "https://example.net/"; let url = Url::parse(url_str)?; assert_eq!(String::from(url), url_str); ``` -------------------------------- ### pub fn cannot_be_a_base(&self) -> bool Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Return whether this URL is a cannot-be-a-base URL. ```APIDOC ## pub fn cannot_be_a_base(&self) -> bool ### Description Return whether this URL is a cannot-be-a-base URL, meaning that parsing a relative URL string with this URL as the base will return an error. ``` -------------------------------- ### Add URL Schemes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Appends new URL schemes to the existing whitelist. ```rust let a = ammonia::Builder::default() .add_url_schemes(&["my-scheme"]) .clean("mess").to_string(); assert_eq!("mess", a); ``` -------------------------------- ### Configure Tag Attribute Values Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=u32+-%3E+bool Demonstrates setting and cleaning tag-specific attributes using the Builder. ```rust let tags = hashset!["my-tag"]; let set_tag_attribute_values = hashmap![ "my-tag" => hashmap![ "my-attr" => "val", ], ]; let a = Builder::new().tags(tags).set_tag_attribute_values(set_tag_attribute_values) .clean("") .to_string(); assert_eq!(a, ""); ``` ```rust let a = ammonia::Builder::default() .add_tags(&["my-tag"]) .set_tag_attribute_value("my-tag", "my-attr", "val") .clean("test mess").to_string(); assert_eq!("test mess", a); ``` -------------------------------- ### path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the path for the URL as a percent-encoded ASCII string. ```APIDOC ## pub fn path(&self) -> &str ### Description Return the path for this URL, as a percent-encoded ASCII string. For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with ‘/’. ``` -------------------------------- ### pub fn has_host(&self) -> bool Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Checks if the URL has a host component. ```APIDOC ## pub fn has_host(&self) -> bool ### Description Checks if the URL has a host component. This is equivalent to checking if the host is present. ``` -------------------------------- ### Panic on Contradictory Link Settings Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html Shows a configuration that triggers a panic due to conflicting link attribute settings. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .generic_attributes(hashset!["rel"]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .generic_attributes(hashset!["rel"]) .link_rel(None) .clean(""); ``` -------------------------------- ### Create Relative URL Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Attempts to create a relative path from a base URL to a target URL. ```rust use url::Url; let base = Url::parse("https://example.net/a/b.html")?; let url = Url::parse("https://example.net/a/c.png")?; let relative = base.make_relative(&url); assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png")); let base = Url::parse("https://example.net/a/b/")?; let url = Url::parse("https://example.net/a/b/c.png")?; let relative = base.make_relative(&url); assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png")); let base = Url::parse("https://example.net/a/b/")?; let url = Url::parse("https://example.net/a/d/c.png")?; let relative = base.make_relative(&url); assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("../d/c.png")); let base = Url::parse("https://example.net/a/b.html?c=d")?; let url = Url::parse("https://example.net/a/b.html?e=f")?; let relative = base.make_relative(&url); assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("?e=f")); ``` -------------------------------- ### pub fn from_file_path

(path: P) -> Result Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Converts a file path into a URL using the 'file' scheme. ```APIDOC ## pub fn from_file_path

(path: P) -> Result ### Description Convert a file name as `std::path::Path` into an URL in the `file` scheme. Returns an error if the path is not absolute or, on Windows, if the prefix is not a disk or UNC prefix. ### Parameters - **path** (P) - Required - The file path to convert. ``` -------------------------------- ### pub fn username(&self) -> &str Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Return the username for this URL as a percent-encoded ASCII string. ```APIDOC ## pub fn username(&self) -> &str ### Description Return the username for this URL (typically the empty string) as a percent-encoded ASCII string. ``` -------------------------------- ### Configure Generic Attributes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Demonstrates setting custom whitelisted attributes for HTML elements. ```rust let attributes = hashset!["data-val"]; let a = Builder::new() .generic_attributes(attributes) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### Convert Document to String using Display Source: https://docs.rs/ammonia/latest/ammonia/struct.Document.html?search= Demonstrates converting a cleaned Document to a String using the Display trait implementation. ```rust use ammonia::Builder; let input = "Some HTML here"; let output = "Some HTML here"; let document = Builder::new() .clean(input); assert_eq!(document.to_string(), output); ``` -------------------------------- ### Configure Parse Options Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Uses ParseOptions to configure the URL parser, such as setting a base URL. ```rust use url::Url; let options = Url::options(); let api = Url::parse("https://api.example.com")?; let base_url = options.base_url(Some(&api)); let version_url = base_url.parse("version.json")?; assert_eq!(version_url.as_str(), "https://api.example.com/version.json"); ``` -------------------------------- ### pub fn port(&self) -> Option Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the port number for this URL, if any. ```APIDOC ## pub fn port(&self) -> Option ### Description Return the port number for this URL, if any. Note that default port numbers are not reflected in the serialization. ``` -------------------------------- ### Retrieve Query String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the URL query string as a percent-encoded ASCII string. ```rust use url::Url; fn run() -> Result<(), ParseError> { let url = Url::parse("https://example.com/products?page=2")?; let query = url.query(); assert_eq!(query, Some("page=2")); let url = Url::parse("https://example.com/products")?; let query = url.query(); assert!(query.is_none()); let url = Url::parse("https://example.com/?country=español")?; let query = url.query(); assert_eq!(query, Some("country=espa%C3%B1ol")); ``` -------------------------------- ### Configure Generic Attributes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=std%3A%3Avec Demonstrates setting generic attributes on the builder. ```rust let attributes = hashset!["data-val"]; let a = Builder::new() .generic_attributes(attributes) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### Configure Generic Attribute Prefixes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=u32+-%3E+bool Methods for setting, adding, removing, and cloning whitelisted attribute prefixes. ```rust use ammonia::Builder; use maplit::hashset; let prefixes = hashset!["data-"]; let a = Builder::new() .generic_attribute_prefixes(prefixes) .clean("") .to_string(); assert_eq!(a, ""); ``` ```rust let a = ammonia::Builder::default() .add_generic_attribute_prefixes(&["my-"]) .clean("mess").to_string(); assert_eq!("mess", a); ``` ```rust let a = ammonia::Builder::default() .add_generic_attribute_prefixes(&["data-", "code-"]) .rm_generic_attribute_prefixes(&["data-"]) .clean("").to_string(); assert_eq!("", a); ``` ```rust use maplit::hashset; let generic_attribute_prefixes = hashset!["my-prfx-1-", "my-prfx-2-"]; let mut b = ammonia::Builder::default(); b.generic_attribute_prefixes(Clone::clone(&generic_attribute_prefixes)); assert_eq!(Some(generic_attribute_prefixes), b.clone_generic_attribute_prefixes()); ``` -------------------------------- ### Construct empty Builder Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Creates a Builder instance with no allowed tags. ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the empty() function."; let output = "This is an Ammonia example using the empty() function."; ``` -------------------------------- ### Panic on Contradictory Class Settings Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html Shows a configuration that triggers a panic due to conflicting class attribute settings. ```rust use ammonia::Builder; use maplit::{hashmap, hashset}; Builder::default() .generic_attributes(hashset!["class"]) .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::{hashmap, hashset}; Builder::default() .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean(""); ``` -------------------------------- ### Sanitize HTML with Builder Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Demonstrates sanitizing an HTML fragment using the Builder configuration, including URL rewriting. ```rust let result = Builder::empty() // <-- .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output); ``` ```rust use ammonia::{Builder, Url, UrlRelative}; let input = "This is an Ammonia example using the new() function."; let output = "This is an Ammonia example using the new() function."; let result = Builder::new() .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); // <-- assert_eq!(result, output); ``` -------------------------------- ### Parse URL with Parameters Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Parses a URL and appends query parameters without removing existing ones. ```rust use url::Url; let url = Url::parse_with_params("https://example.net?dont=clobberme", &[("lang", "rust"), ("browser", "servo")])?; assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str()); ``` -------------------------------- ### from_str Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Parses a string into a Url object. ```APIDOC ## fn from_str(input: &str) -> Result ### Description Parses a string slice into a `Url` instance without requiring a base URL or encoding override. ### Parameters - **input** (str) - The string to parse as a URL. ### Returns - **Result** - The parsed URL or a parsing error. ``` -------------------------------- ### Configure allowed tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Methods for managing the whitelist of allowed HTML tags. ```rust use ammonia::Builder; use maplit::hashset; let tags = hashset!["my-tag"]; let a = Builder::new() .tags(tags) .clean("") .to_string(); assert_eq!(a, ""); ``` ```rust let a = ammonia::Builder::default() .add_tags(&["my-tag"]) .clean("test mess").to_string(); assert_eq!("test mess", a); ``` ```rust let a = ammonia::Builder::default() .rm_tags(&["span"]) .clean("").to_string(); assert_eq!("", a); ``` ```rust use maplit::hashset; let tags = hashset!["my-tag-1", "my-tag-2"]; ``` -------------------------------- ### Builder::empty() Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=u32+-%3E+bool Constructs a Builder instance with no allowed tags. ```APIDOC ## pub fn empty() -> Self ### Description Constructs a `Builder` instance configured with no allowed tags. ``` -------------------------------- ### Retrieve URL Origin Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the origin of the URL. Note that file URLs return an opaque origin. ```rust use url::{Host, Origin, Url}; let url = Url::parse("ftp://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("ftp".into(), Host::Domain("example.com".into()), 21)); ``` ```rust use url::{Host, Origin, Url}; let url = Url::parse("blob:https://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("https".into(), Host::Domain("example.com".into()), 443)); ``` ```rust use url::{Host, Origin, Url}; let url = Url::parse("file:///tmp/foo")?; assert!(!url.origin().is_tuple()); let other_url = Url::parse("file:///tmp/foo")?; assert!(url.origin() != other_url.origin()); ``` ```rust use url::{Host, Origin, Url}; let url = Url::parse("foo:bar")?; assert!(!url.origin().is_tuple()); ``` -------------------------------- ### pub fn domain(&self) -> Option<&str> Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the domain name if the URL has a host and it is a domain name. ```APIDOC ## pub fn domain(&self) -> Option<&str> ### Description If this URL has a host and it is a domain name (not an IP address), return it. Non-ASCII domains are encoded appropriately. ``` -------------------------------- ### Configure URL Schemes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Sets the permitted URL schemes for href and src attributes. ```rust use ammonia::Builder; use maplit::hashset; let url_schemes = hashset![ "http", "https", "mailto", "magnet" ]; let a = Builder::new().url_schemes(url_schemes) .clean("zero-length file") .to_string(); // See `link_rel` for information on the rel=\"noopener noreferrer\" attribute // in the cleaned HTML. assert_eq!(a, "zero-length file"); ``` -------------------------------- ### Parse URL from String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Parses an absolute URL from a string, returning a Result. ```rust use url::Url; let url = Url::parse("https://example.net")?; ``` -------------------------------- ### Url::join Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Resolves a relative URL against a base URL. ```APIDOC ## pub fn join(&self, input: &str) -> Result ### Description Parses a string as a URL, using the current instance as the base URL. The behavior depends on whether the base URL has a trailing slash. ``` -------------------------------- ### Configure Allowed Tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html Sets a specific whitelist of allowed tags. ```rust use ammonia::Builder; use maplit::hashset; let tags = hashset!["my-tag"]; let a = Builder::new() .tags(tags) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### pub fn port_or_known_default(&self) -> Option Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the port number for this URL, or the default port number if it is known. ```APIDOC ## pub fn port_or_known_default(&self) -> Option ### Description Return the port number for this URL, or the default port number if it is known. This method supports http, https, ws, wss, and ftp schemes. ``` -------------------------------- ### Configure allowed classes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Sets the allowed classes for specific tags using a hashmap of hashsets. ```rust let allowed_classes = hashmap![ "code" => hashset!["rs", "ex", "c", "cxx", "js"] ]; let a = Builder::new() .allowed_classes(allowed_classes) .clean("fn main() {}") .to_string(); assert_eq!( a, "fn main() {}"); ``` -------------------------------- ### Add Additional Whitelisted Tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html Appends new tags to the existing whitelist. ```rust let a = ammonia::Builder::default() .add_tags(&["my-tag"]) .clean("test mess").to_string(); assert_eq!("test mess", a); ``` -------------------------------- ### pub fn scheme(&self) -> &str Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Return the scheme of this URL, lower-cased, as an ASCII string without the ‘:’ delimiter. ```APIDOC ## pub fn scheme(&self) -> &str ### Description Return the scheme of this URL, lower-cased, as an ASCII string without the ‘:’ delimiter. ``` -------------------------------- ### Set URL Path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Updates the URL path. The method automatically handles percent-encoding for non-encoded strings. ```rust use url::Url; let mut url = Url::parse("https://example.com")?; url.set_path("api/comments"); assert_eq!(url.as_str(), "https://example.com/api/comments"); assert_eq!(url.path(), "/api/comments"); let mut url = Url::parse("https://example.com/api")?; url.set_path("data/report.csv"); assert_eq!(url.as_str(), "https://example.com/data/report.csv"); assert_eq!(url.path(), "/data/report.csv"); // `set_path` percent-encodes the given string if it's not already percent-encoded. let mut url = Url::parse("https://example.com")?; url.set_path("api/some comments"); assert_eq!(url.as_str(), "https://example.com/api/some%20comments"); assert_eq!(url.path(), "/api/some%20comments"); // `set_path` will not double percent-encode the string if it's already percent-encoded. let mut url = Url::parse("https://example.com")?; url.set_path("api/some%20comments"); assert_eq!(url.as_str(), "https://example.com/api/some%20comments"); assert_eq!(url.path(), "/api/some%20comments"); ``` -------------------------------- ### from_str Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Parses a string as a URL without a base URL or encoding override. ```APIDOC ## fn from_str(input: &str) -> Result ### Description Parses a string s to return a value of this type. ### Parameters - input (str): The string to parse as a URL. ### Returns - Result: Returns the parsed Url or a ParseError if parsing fails. ``` -------------------------------- ### Cloning Tag Configuration Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=std%3A%3Avec Retrieving a copy of the current whitelisted tags. ```rust use maplit::hashset; let tags = hashset!["my-tag-1", "my-tag-2"]; ``` -------------------------------- ### URL Relative Resolver Status Methods Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Methods to check the current configuration of the relative URL resolver. ```APIDOC ## is_url_relative_deny Returns `true` if the relative URL resolver is set to `Deny`. ## is_url_relative_pass_through Returns `true` if the relative URL resolver is set to `PassThrough`. ## is_url_relative_custom Returns `true` if the relative URL resolver is set to `Custom`. ``` -------------------------------- ### Configure clean-content tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Sets the tags whose contents will be completely removed from the output. Adding tags that are already whitelisted will cause a panic. ```rust use ammonia::Builder; use maplit::hashset; let tag_blacklist = hashset!["script", "style"]; let a = Builder::new() .clean_content_tags(tag_blacklist) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### pub fn clean(&self, src: &str) -> Document Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sanitizes an HTML fragment in a string according to the configured options. ```APIDOC ## pub fn clean(&self, src: &str) -> Document ### Description Sanitizes an HTML fragment in a string according to the configured options. ### Parameters - **src** (&str) - The HTML fragment string to sanitize. ### Returns - **Document** - The sanitized HTML document. ``` -------------------------------- ### Manage Clean Content Tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for setting, adding, removing, and cloning tags whose contents should be stripped from the output. ```rust use ammonia::Builder; use maplit::hashset; let tag_blacklist = hashset!["script", "style"]; let a = Builder::new() .clean_content_tags(tag_blacklist) .clean("") .to_string(); assert_eq!(a, ""); ``` ```rust let a = ammonia::Builder::default() .add_clean_content_tags(&["my-tag"]) .clean("testmess").to_string(); assert_eq!("mess", a); ``` ```rust use ammonia::Builder; use maplit::hashset; let tag_blacklist = hashset!["script"]; let a = ammonia::Builder::default() .clean_content_tags(tag_blacklist) .rm_clean_content_tags(&["script"]) .clean("").to_string(); assert_eq!("XSS", a); ``` ```rust let tags = hashset!["my-tag-1", "my-tag-2"]; let mut b = ammonia::Builder::default(); b.clean_content_tags(Clone::clone(&tags)); assert_eq!(tags, b.clone_clean_content_tags()); ``` -------------------------------- ### Panic on Contradictory Tag Settings Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html Shows a configuration that triggers a panic due to conflicting tag whitelist and blacklist settings. ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .clean_content_tags(hashset!["aside"]) .clean(""); ``` ```rust use ammonia::Builder; use maplit::hashset; Builder::default() .rm_tags(&["aside"]) .clean_content_tags(hashset!["aside"]) .clean(""); ``` -------------------------------- ### Add generic attribute prefixes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Appends new whitelisted attribute prefixes to the existing configuration. ```rust let a = ammonia::Builder::default() .add_generic_attribute_prefixes(&["my-"]) .clean("mess").to_string(); assert_eq!("mess", a); ``` -------------------------------- ### Join URLs Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Resolves a relative URL against a base URL. Note that trailing slashes in the base URL affect path resolution. ```rust use url::Url; // Base without a trailing slash let base = Url::parse("https://example.net/a/b.html")?; let url = base.join("c.png")?; assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png // Base with a trailing slash let base = Url::parse("https://example.net/a/b/")?; let url = base.join("c.png")?; assert_eq!(url.as_str(), "https://example.net/a/b/c.png"); // Input as scheme relative special URL let base = Url::parse("https://alice.com/a")?; let url = base.join("//eve.com/b")?; assert_eq!(url.as_str(), "https://eve.com/b"); // Input as base url relative special URL let base = Url::parse("https://alice.com/a")?; let url = base.join("/v1/meta")?; assert_eq!(url.as_str(), "https://alice.com/v1/meta"); // Input as absolute URL let base = Url::parse("https://alice.com/a")?; let url = base.join("http://eve.com/b")?; assert_eq!(url.as_str(), "http://eve.com/b"); // http instead of https ``` -------------------------------- ### query Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the URL’s query string as a percent-encoded ASCII string. ```APIDOC ## pub fn query(&self) -> Option<&str> ### Description Return this URL’s query string, if any, as a percent-encoded ASCII string. ``` -------------------------------- ### Retrieve URL Username Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the percent-encoded username component of the URL. ```rust use url::Url; let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.username(), "rms"); let url = Url::parse("ftp://:secret123@example.com")?; assert_eq!(url.username(), ""); let url = Url::parse("https://example.com")?; assert_eq!(url.username(), ""); ``` -------------------------------- ### pub fn is_special(&self) -> bool Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Return whether the URL is special (has a special scheme). ```APIDOC ## pub fn is_special(&self) -> bool ### Description Return whether the URL is special (has a special scheme). ``` -------------------------------- ### pub fn clean(src: &str) -> String Source: https://docs.rs/ammonia/latest/ammonia/fn.clean.html?search=std%3A%3Avec Sanitizes an HTML string using a conservative set of default security rules. ```APIDOC ## pub fn clean(src: &str) -> String ### Description Cleans HTML input with a conservative set of defaults. It strips script and style tags, blocks class attributes, and enforces security policies on links. ### Parameters - **src** (&str) - The input HTML string to be cleaned. ### Returns - **String** - The sanitized HTML string. ### Example ```rust use ammonia::clean; let input = "XSS"; let output = clean(input); assert_eq!(output, "XSS"); ``` ``` -------------------------------- ### Set URL Query String Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Updates the query string of a URL. Passing None clears the existing query. ```rust use url::Url; let mut url = Url::parse("https://example.com/products")?; assert_eq!(url.as_str(), "https://example.com/products"); url.set_query(Some("page=2")); assert_eq!(url.as_str(), "https://example.com/products?page=2"); assert_eq!(url.query(), Some("page=2")); ``` -------------------------------- ### Clone URL Schemes Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Retrieves a copy of the current URL scheme whitelist. ```rust use maplit::hashset; let url_schemes = hashset!["my-scheme-1", "my-scheme-2"]; let mut b = ammonia::Builder::default(); b.url_schemes(Clone::clone(&url_schemes)); assert_eq!(url_schemes, b.clone_url_schemes()); ``` -------------------------------- ### Retrieve URL Authority Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the authority component as an ASCII string, handling punycode or percent-encoding as necessary. ```rust use url::Url; let url = Url::parse("unix:/run/foo.socket")?; assert_eq!(url.authority(), ""); let url = Url::parse("file:///tmp/foo")?; assert_eq!(url.authority(), ""); let url = Url::parse("https://user:password@example.com/tmp/foo")?; assert_eq!(url.authority(), "user:password@example.com"); let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?; assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667"); let url = Url::parse("http://àlex.рф.example.com:80/foo")?; assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com"); ``` -------------------------------- ### Convert File Path to URL Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Converts a file system path to a file scheme URL. Requires the std feature and absolute paths. ```rust use url::Url; let url = Url::from_file_path("/tmp/foo.txt")?; assert_eq!(url.as_str(), "file:///tmp/foo.txt"); let url = Url::from_file_path("../foo.txt"); assert!(url.is_err()); let url = Url::from_file_path("https://google.com/"); assert!(url.is_err()); ``` -------------------------------- ### ammonia::clean Source: https://docs.rs/ammonia/latest/ammonia/fn.clean.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sanitizes an HTML string using default security configurations. ```APIDOC ## pub fn clean(src: &str) -> String ### Description Cleans HTML input with a conservative set of defaults. It strips dangerous tags like `script` and `style`, blocks `class` attributes, and enforces security attributes on links. ### Parameters - **src** (&str) - The raw HTML string to be cleaned. ### Returns - **String** - The sanitized HTML string. ### Example ```rust assert_eq!(ammonia::clean("XSS"), "XSS"); ``` ``` -------------------------------- ### Set ID prefix Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Prepends a string to all ID attribute values. ```rust use ammonia::Builder; use maplit::hashset; let attributes = hashset!["id"]; let a = Builder::new() .generic_attributes(attributes) .id_prefix(Some("safe-")) .clean("") .to_string(); assert_eq!(a, ""); ``` -------------------------------- ### origin Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html Returns the origin of the URL. ```APIDOC ## pub fn origin(&self) -> Origin ### Description Return the origin of this URL. Note: this returns an opaque origin for `file:` URLs. ``` -------------------------------- ### add_tags Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Adds additional whitelisted tags to the existing configuration without overwriting previous settings. ```APIDOC ## pub fn add_tags, I: IntoIter>( &mut self, it: I, ) -> &mut Self ### Description Add additional whitelisted tags without overwriting old ones. Does nothing if the tag is already there. ``` -------------------------------- ### Convert URL to file path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Converts a URL to an absolute path. Ensure the URL scheme is checked before calling this method. ```rust let path = url.to_file_path(); ``` -------------------------------- ### Url::as_str Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Returns the string serialization of the URL. ```APIDOC ## pub fn as_str(&self) -> &str ### Description Return the serialization of this URL. ### Returns - **&str** - The serialized URL string. ``` -------------------------------- ### clean Source: https://docs.rs/ammonia/latest/ammonia/struct.Builder.html?search= Sanitizes an HTML fragment in a string according to the configured options. ```APIDOC ## pub fn clean(&self, src: &str) -> Document ### Description Sanitizes an HTML fragment in a string according to the configured options. ### Parameters - **src** (&str) - Required - The HTML fragment string to sanitize. ### Returns - **Document** - The sanitized HTML document. ``` -------------------------------- ### to_file_path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=u32+-%3E+bool Converts the URL path to an absolute std::path::Path, assuming the URL is in the file scheme. ```APIDOC ## pub fn to_file_path(&self) -> Result ### Description Assuming the URL is in the file scheme or similar, convert its path to an absolute std::path::Path. Note that this does not check the URL scheme and may give nonsensical results for other schemes. ### Returns - Result: Returns the path on success, or an error if the host is invalid or the path cannot be converted. ``` -------------------------------- ### set_path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html?search=std%3A%3Avec Changes the URL's path component. ```APIDOC ## pub fn set_path(&mut self, path: &str) ### Description Change this URL’s path. This method will percent-encode the string if it is not already encoded. ### Parameters - **path** (&str) - The new path string. ``` -------------------------------- ### from_directory_path Source: https://docs.rs/ammonia/latest/ammonia/struct.Url.html Converts a directory path into a URL with the 'file' scheme, ensuring a trailing slash. ```APIDOC ## pub fn from_directory_path

(path: P) -> Result ### Description Convert a directory name as `std::path::Path` into an URL in the `file` scheme. This ensures the URL path has a trailing slash, which is important when using the URL as a base. This method requires the `std` Cargo feature. ### Parameters - **path** (P) - Required - The absolute directory path to convert. ### Returns - **Result** - Returns the URL on success, or Err(()) if the path is not absolute or has an invalid prefix. ```