#![cfg_attr(not(test), no_std)] //! Internal support code used by the [Maud] template engine. //! //! You should not need to depend on this crate directly. //! //! [Maud]: https://maud.lambda.xyz #![doc(html_root_url = "https://docs.rs/maud_htmlescape/0.17.1")] extern crate alloc; use alloc::string::String; use core::fmt; /// An adapter that escapes HTML special characters. /// /// The following characters are escaped: /// /// * `&` is escaped as `&` /// * `<` is escaped as `<` /// * `>` is escaped as `>` /// * `"` is escaped as `"` /// /// All other characters are passed through unchanged. /// /// **Note:** In versions prior to 0.13, the single quote (`'`) was /// escaped as well. /// /// # Example /// /// ```rust,ignore /// use std::fmt::Write; /// let mut s = String::new(); /// write!(Escaper::new(&mut s), "").unwrap(); /// assert_eq!(s, "<script>launchMissiles()</script>"); /// ``` pub struct Escaper<'a>(&'a mut String); impl<'a> Escaper<'a> { /// Creates an `Escaper` from a `String`. pub fn new(buffer: &'a mut String) -> Escaper<'a> { Escaper(buffer) } } impl<'a> fmt::Write for Escaper<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { for b in s.bytes() { match b { b'&' => self.0.push_str("&"), b'<' => self.0.push_str("<"), b'>' => self.0.push_str(">"), b'"' => self.0.push_str("""), _ => unsafe { self.0.as_mut_vec().push(b) }, } } Ok(()) } } #[cfg(test)] mod test { use crate::Escaper; use std::fmt::Write; #[test] fn it_works() { let mut s = String::new(); write!(Escaper::new(&mut s), "").unwrap(); assert_eq!(s, "<script>launchMissiles()</script>"); } }