8000 Refactor `indent` Filter Implementation by strickczq · Pull Request #466 · askama-rs/askama · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Refactor indent Filter Implementation #466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
333 changes: 0 additions & 333 deletions askama/src/filters/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
use alloc::borrow::Cow;
use alloc::str;
use alloc::string::String;
use core::cell::Cell;
use core::convert::Infallible;
use core::fmt::{self, Write};
use core::ops::Deref;
use core::pin::Pin;

use super::MAX_LEN;
use super::escape::HtmlSafeOutput;
use crate::{FastWritable, Result};

Expand Down Expand Up @@ -507,125 +503,6 @@ fn flush_trim(dest: &mut (impl fmt::Write + ?Sized), collector: TrimCollector) -
dest.write_str(collector.0.trim_end())
}

/// Indent lines with spaces or a prefix.
///
/// The first line and blank lines are not indented by default.
/// The filter has two optional [`bool`] arguments, `first` and `blank`, that can be set to `true`
/// to indent the first and blank lines, resp.
///
/// ### Example of `indent` with spaces
///
/// ```
/// # #[cfg(feature = "code-in-doc")] {
/// # use askama::Template;
/// /// ```jinja
/// /// <div>{{ example|indent(4) }}</div>
/// /// ```
/// #[derive(Template)]
/// #[template(ext = "html", in_doc = true)]
/// struct Example<'a> {
/// example: &'a str,
/// }
///
/// assert_eq!(
/// Example { example: "hello\nfoo\nbar" }.to_string(),
/// "<div>hello\n foo\n bar</div>"
/// );
/// # }
/// ```
///
/// ### Example of `indent` with prefix a custom prefix
///
/// ```
/// # #[cfg(feature = "code-in-doc")] {
/// # use askama::Template;
/// /// ```jinja
/// /// <div>{{ example|indent("$$$ ") }}</div>
/// /// ```
/// #[derive(Template)]
/// #[template(ext = "html", in_doc = true)]
/// struct Example<'a> {
/// example: &'a str,
/// }
///
/// assert_eq!(
/// Example { example: "hello\nfoo\nbar" }.to_string(),
/// "<div>hello\n$$$ foo\n$$$ bar</div>"
/// );
/// # }
/// ```
#[inline]
pub fn indent<S, I: AsIndent>(
source: S,
indent: I,
first: bool,
blank: bool,
) -> Result<Indent<S, I>, Infallible> {
Ok(Indent {
source,
indent,
first,
blank,
})
}

pub struct Indent<S, I> {
source: S,
indent: I,
first: bool,
blank: bool,
}

impl<S: fmt::Display, I: AsIndent> fmt::Display for Indent<S, I> {
fn fmt(&self, dest: &mut fmt::Formatter<'_>) -> fmt::Result {
let indent = self.indent.as_indent();
if indent.len() >= MAX_LEN || indent.is_empty() {
write!(dest, "{}", self.source)
} else {
let mut buffer;
let buffer = try_to_str!(self.source => buffer);
flush_indent(dest, indent, buffer, self.first, self.blank)
}
}
}

impl<S: FastWritable, I: AsIndent> FastWritable for Indent<S, I> {
fn write_into<W: fmt::Write + ?Sized>(
&self,
dest: &mut W,
values: &dyn crate::Values,
) -> crate::Result<()> {
let indent = self.indent.as_indent();
if indent.len() >= MAX_LEN || indent.is_empty() {
self.source.write_into(dest, values)
} else {
let mut buffer = String::new();
self.source.write_into(&mut buffer, values)?;
Ok(flush_indent(dest, indent, &buffer, self.first, self.blank)?)
}
}
}

fn flush_indent(
dest: &mut (impl fmt::Write + ?Sized),
indent: &str,
s: &str,
first: bool,
blank: bool,
) -> fmt::Result {
if s.len() >= MAX_LEN {
return dest.write_str(s);
}

for (idx, line) in s.split_inclusive('\n').enumerate() {
if (first || idx > 0) && (blank || !matches!(line, "\n" | "\r\n")) {
dest.write_str(indent)?;
}
dest.write_str(line)?;
}
Ok(())
}

/// Capitalize a value. The first character will be uppercase, all others lowercase.
///
/// ```
Expand Down Expand Up @@ -845,97 +722,9 @@ pub fn titlecase<S: fmt::Display>(source: S) -> Result<Title<S>, Infallible> {
title(source)
}

/// A prefix usable for indenting [prettified JSON data](super::json::json_pretty) and
/// [`|indent`](indent)
///
/// ```
/// # use askama::filters::AsIndent;
/// assert_eq!(4.as_indent(), " ");
/// assert_eq!(" -> ".as_indent(), " -> ");
/// ```
pub trait AsIndent {
/// Borrow `self` as prefix to use.
fn as_indent(&self) -> &str;
}

impl AsIndent for str {
#[inline]
fn as_indent(&self) -> &str {
self
}
}

#[cfg(feature = "alloc")]
impl AsIndent for alloc::string::String {
#[inline]
fn as_indent(&self) -> &str {
self
}
}

impl AsIndent for usize {
#[inline]
fn as_indent(&self) -> &str {
spaces(*self)
}
}

impl AsIndent for core::num::Wrapping<usize> {
#[inline]
fn as_indent(&self) -> &str {
spaces(self.0)
}
}

impl AsIndent for core::num::NonZeroUsize {
#[inline]
fn as_indent(&self) -> &str {
spaces(self.get())
}
}

fn spaces(width: usize) -> &'static str {
const MAX_SPACES: usize = 16;
const SPACES: &str = match str::from_utf8(&[b' '; MAX_SPACES]) {
Ok(spaces) => spaces,
Err(_) => panic!(),
};

&SPACES[..width.min(SPACES.len())]
}

#[cfg(feature = "alloc")]
impl<T: AsIndent + alloc::borrow::ToOwned + ?Sized> AsIndent for Cow<'_, T> {
#[inline]
fn as_indent(&self) -> &str {
T::as_indent(self)
}
}

crate::impl_for_ref! {
impl AsIndent for T {
#[inline]
fn as_indent(&self) -> &str {
<T>::as_indent(self)
}
}
}

impl<T> AsIndent for Pin<T>
where
T: Deref,
<T as Deref>::Target: AsIndent,
{
#[inline]
fn as_indent(&self) -> &str {
self.as_ref().get_ref().as_indent()
}
}

#[cfg(test)]
mod tests {
use alloc::string::ToString;
use std::borrow::ToOwned;

use super::*;
use crate::NO_VALUES;
Expand Down Expand Up @@ -1000,122 +789,6 @@ mod tests {
assert_eq!(trim(" Hello\tworld\t").unwrap().to_string(), "Hello\tworld");
}

#[test]
fn test_indent() {
assert_eq!(
indent("hello", 2, false, false).unwrap().to_string(),
"hello"
);
assert_eq!(
indent("hello\n", 2, false, false).unwrap().to_string(),
"hello\n"
);
assert_eq!(
indent("hello\nfoo", 2, false, false).unwrap().to_string(),
"hello\n foo"
);
assert_eq!(
indent("hello\nfoo\n bar", 4, false, false)
.unwrap()
.to_string(),
"hello\n foo\n bar"
);
assert_eq!(
indent("hello", 267_332_238_858, false, false)
.unwrap()
.to_string(),
"hello"
);

assert_eq!(
indent("hello\n\n bar", 4, false, false)
.unwrap()
.to_string(),
"hello\n\n bar"
);
assert_eq!(
indent("hello\n\n bar", 4, false, true).unwrap().to_string(),
"hello\n \n bar"
);
assert_eq!(
indent("hello\n\n bar", 4, true, false).unwrap().to_string(),
" hello\n\n bar"
);
assert_eq!(
indent("hello\n\n bar", 4, true, true).unwrap().to_string(),
" hello\n \n bar"
);
}

#[test]
fn test_indent_str() {
assert_eq!(
indent("hello\n\n bar", "❗❓", false, false)
.unwrap()
.to_string(),
"hello\n\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", "❗❓", false, true)
.unwrap()
.to_string(),
"hello\n❗❓\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", "❗❓", true, false)
.unwrap()
.to_string(),
"❗❓hello\n\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", "❗❓", true, true)
.unwrap()
.to_string(),
"❗❓hello\n❗❓\n❗❓ bar"
);
}

#[test]
#[allow(clippy::arc_with_non_send_sync)] // it's only a test, it does not have to make sense
#[allow(clippy::type_complexity)] // it's only a test, it does not have to be pretty
fn test_indent_complicated() {
use std::boxed::Box;
use std::cell::{RefCell, RefMut};
use std::rc::Rc;
use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockWriteGuard};

let prefix = Mutex::new(Box::pin("❗❓".to_owned()));
let prefix = RefCell::new(Arc::new(prefix.try_lock().unwrap()));
let prefix = RwLock::new(Rc::new(prefix.borrow_mut()));
let prefix: RwLockWriteGuard<'_, Rc<RefMut<'_, Arc<MutexGuard<'_, Pin<Box<String>>>>>>> =
prefix.try_write().unwrap();

assert_eq!(
indent("hello\n\n bar", &prefix, false, false)
.unwrap()
.to_string(),
"hello\n\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", &prefix, false, true)
.unwrap()
.to_string(),
"hello\n❗❓\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", &prefix, true, false)
.unwrap()
.to_string(),
"❗❓hello\n\n❗❓ bar"
);
assert_eq!(
indent("hello\n\n bar", &prefix, true, true)
.unwrap()
.to_string(),
"❗❓hello\n❗❓\n❗❓ bar"
);
}

#[test]
fn test_capitalize() {
assert_eq!(capitalize("foo").unwrap().to_string(), "Foo".to_string());
Expand Down Expand Up @@ -1172,10 +845,4 @@ mod tests {
"Fo\x0bOo\x0cOo\u{2002}Oo\u{3000}Bar"
);
}

#[test]
fn fuzzed_indent_filter() {
let s = "hello\nfoo\nbar".to_string().repeat(1024);
assert_eq!(indent(s.clone(), 4, false, false).unwrap().to_string(), s);
}
}
Loading
0