From 46ef5502b3b66fe90b0457fe0298c83a4ca4c1dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Kijewski?= Date: Mon, 5 Aug 2024 09:47:40 +0200 Subject: [PATCH] Implement FastWritable for `|urlencode` --- rinja/src/filters/mod.rs | 53 +++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/rinja/src/filters/mod.rs b/rinja/src/filters/mod.rs index 4342fe94..33ee4ace 100644 --- a/rinja/src/filters/mod.rs +++ b/rinja/src/filters/mod.rs @@ -105,8 +105,13 @@ impl fmt::Display for FilesizeFormatFilter { /// /// [`urlencode_strict`]: ./fn.urlencode_strict.html #[inline] -pub fn urlencode(s: impl fmt::Display) -> Result, Infallible> { - Ok(HtmlSafeOutput(UrlencodeFilter(s, URLENCODE_SET))) +pub fn urlencode( + s: T, +) -> Result>, Infallible> { + Ok(HtmlSafeOutput(_urlencode_filter::UrlencodeFilter( + s, + URLENCODE_SET, + ))) } #[cfg(feature = "urlencode")] @@ -125,28 +130,42 @@ pub fn urlencode(s: impl fmt::Display) -> Result Result, Infallible> { - Ok(HtmlSafeOutput(UrlencodeFilter(s, URLENCODE_STRICT_SET))) +pub fn urlencode_strict( + s: T, +) -> Result>, Infallible> { + Ok(HtmlSafeOutput(_urlencode_filter::UrlencodeFilter( + s, + URLENCODE_STRICT_SET, + ))) } #[cfg(feature = "urlencode")] -struct UrlencodeFilter(T, &'static AsciiSet); +mod _urlencode_filter { + use super::*; -#[cfg(feature = "urlencode")] -impl fmt::Display for UrlencodeFilter { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - struct Writer<'a, 'b>(&'a mut fmt::Formatter<'b>, &'static AsciiSet); + pub struct UrlencodeFilter(pub T, pub &'static AsciiSet); - impl fmt::Write for Writer<'_, '_> { - #[inline] - fn write_str(&mut self, s: &str) -> fmt::Result { - write!(self.0, "{}", utf8_percent_encode(s, self.1)) - } + impl fmt::Display for UrlencodeFilter { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(UrlencodeWriter(f, self.1), "{}", self.0) } + } + + impl FastWritable for UrlencodeFilter { + #[inline] + fn write_into(&self, f: &mut W) -> fmt::Result { + self.0.write_into(&mut UrlencodeWriter(f, self.1)) + } + } - write!(Writer(f, self.1), "{}", self.0) + struct UrlencodeWriter(W, &'static AsciiSet); + + impl fmt::Write for UrlencodeWriter { + #[inline] + fn write_str(&mut self, s: &str) -> fmt::Result { + write!(self.0, "{}", utf8_percent_encode(s, self.1)) + } } }