From ec5a2ebbb375d5ad49daeba72ec6aeb874d4a81e Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Mon, 21 Aug 2017 20:57:38 +0200 Subject: Change filters to return Result --- askama/src/filters.rs | 51 +++++++++++++++++++++--------------------- askama_derive/src/generator.rs | 3 +++ 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/askama/src/filters.rs b/askama/src/filters.rs index ccbf1a0..b8673e6 100644 --- a/askama/src/filters.rs +++ b/askama/src/filters.rs @@ -3,13 +3,14 @@ //! Contains all the built-in filter functions for use in templates. //! Currently, there is no way to define filters outside this module. use std::fmt; +use super::Result; fn escapable(b: &u8) -> bool { *b == b'<' || *b == b'>' || *b == b'&' } /// Escapes `&`, `<` and `>` in strings -pub fn escape(s: &fmt::Display) -> String { +pub fn escape(s: &fmt::Display) -> Result { let s = format!("{}", s); let mut found = Vec::new(); for (i, b) in s.as_bytes().iter().enumerate() { @@ -18,7 +19,7 @@ pub fn escape(s: &fmt::Display) -> String { } } if found.is_empty() { - return s; + return Ok(s); } let bytes = s.as_bytes(); @@ -41,11 +42,11 @@ pub fn escape(s: &fmt::Display) -> String { res.extend(&bytes[start..]); } - String::from_utf8(res).unwrap() + Ok(String::from_utf8(res).unwrap()) } /// Alias for the `escape()` filter -pub fn e(s: &fmt::Display) -> String { +pub fn e(s: &fmt::Display) -> Result { escape(s) } @@ -58,31 +59,31 @@ pub fn e(s: &fmt::Display) -> String { pub fn format() { } /// Converts to lowercase. -pub fn lower(s: &fmt::Display) -> String { +pub fn lower(s: &fmt::Display) -> Result { let s = format!("{}", s); - s.to_lowercase() + Ok(s.to_lowercase()) } /// Alias for the `lower()` filter. -pub fn lowercase(s: &fmt::Display) -> String { +pub fn lowercase(s: &fmt::Display) -> Result { lower(s) } /// Converts to uppercase. -pub fn upper(s: &fmt::Display) -> String { +pub fn upper(s: &fmt::Display) -> Result { let s = format!("{}", s); - s.to_uppercase() + Ok(s.to_uppercase()) } /// Alias for the `upper()` filter. -pub fn uppercase(s: &fmt::Display) -> String { +pub fn uppercase(s: &fmt::Display) -> Result { upper(s) } /// Strip leading and trailing whitespace. -pub fn trim(s: &fmt::Display) -> String { +pub fn trim(s: &fmt::Display) -> Result { let s = format!("{}", s); - s.trim().to_owned() + Ok(s.trim().to_owned()) } #[cfg(test)] @@ -90,30 +91,30 @@ mod tests { use super::*; #[test] fn test_escape() { - assert_eq!(escape(&""), ""); - assert_eq!(escape(&"<&>"), "<&>"); - assert_eq!(escape(&"bla&"), "bla&"); - assert_eq!(escape(&"").unwrap(), "<&>"); + assert_eq!(escape(&"bla&").unwrap(), "bla&"); + assert_eq!(escape(&" Generator<'a> { self.visit_expr(arg); } self.write(")"); + if name != "format" { + self.write("?"); + } } fn visit_binop(&mut self, op: &str, left: &Expr, right: &Expr) { -- cgit