rstml_component/
sanitize.rs1use crate::{HtmlContent, HtmlFormatter};
2use ammonia::Builder;
3use std::{fmt, io, sync::OnceLock};
4
5pub type SanitizeConfig = Builder<'static>;
6
7static DEFAULT_SANITIZER: OnceLock<SanitizeConfig> = OnceLock::new();
8
9fn default_sanitizer() -> &'static SanitizeConfig {
10 DEFAULT_SANITIZER.get_or_init(Builder::default)
11}
12
13#[derive(Clone, Copy)]
14enum Sanitizer {
15 Default,
17
18 Builder(&'static SanitizeConfig),
20}
21
22impl Default for Sanitizer {
23 fn default() -> Self {
24 Self::Default
25 }
26}
27
28impl AsRef<SanitizeConfig> for Sanitizer {
29 fn as_ref(&self) -> &SanitizeConfig {
30 match self {
31 Self::Default => default_sanitizer(),
32 Self::Builder(builder) => builder,
33 }
34 }
35}
36
37#[derive(Clone)]
44pub struct Sanitized<V>(V, Sanitizer);
45
46impl<V: fmt::Debug> fmt::Debug for Sanitized<V> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.debug_tuple("Sanitized").field(&self.0).finish()
49 }
50}
51
52impl<V> Sanitized<V>
53where
54 V: AsRef<[u8]>,
55{
56 pub fn new(value: V) -> Self {
66 Self(value, Sanitizer::default())
67 }
68
69 pub fn new_with_sanitizer(value: V, sanitizer: &'static SanitizeConfig) -> Self {
80 Self(value, Sanitizer::Builder(sanitizer))
81 }
82
83 pub fn with_sanitizer(self, sanitizer: &'static SanitizeConfig) -> Self {
95 Self(self.0, Sanitizer::Builder(sanitizer))
96 }
97}
98
99impl<V: AsRef<[u8]>> HtmlContent for Sanitized<V> {
100 fn fmt(self, formatter: &mut HtmlFormatter) -> fmt::Result {
101 let bytes = self.0.as_ref();
102 let bytes = self
103 .1
104 .as_ref()
105 .clean_from_reader(bytes)
106 .map_err(|_| fmt::Error)?;
107 bytes.write_to(IoWrite(formatter)).map_err(|_| fmt::Error)
108 }
109}
110
111struct IoWrite<'a, 'b>(&'a mut HtmlFormatter<'b>);
112
113impl<'a, 'b> io::Write for IoWrite<'a, 'b> {
114 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
115 self.0.write_bytes(buf);
116 Ok(buf.len())
117 }
118
119 fn flush(&mut self) -> io::Result<()> {
120 Ok(())
121 }
122}