From 962c24eaed9bcf30e82dc5ed06c6513b00dba3cf Mon Sep 17 00:00:00 2001 From: Tomas Date: Mon, 5 Nov 2018 14:07:19 +0100 Subject: Add f64 filter --- askama_shared/src/filters/mod.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'askama_shared/src') diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 404abd7..a6d2ba6 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -22,7 +22,7 @@ use escaping::{self, MarkupDisplay}; // Askama or should refer to a local `filters` module. It should contain all the // filters shipped with Askama, even the optional ones (since optional inclusion // in the const vector based on features seems impossible right now). -pub const BUILT_IN_FILTERS: [&str; 20] = [ +pub const BUILT_IN_FILTERS: [&str; 21] = [ "abs", "capitalize", "center", @@ -30,6 +30,7 @@ pub const BUILT_IN_FILTERS: [&str; 20] = [ "escape", "format", "indent", + "into_f64", "into_isize", "join", "linebreaks", @@ -161,6 +162,14 @@ pub fn indent(s: &fmt::Display, width: &usize) -> Result { Ok(indented) } +/// Casts number to f64 +pub fn into_f64(number: T) -> Result +where + T: NumCast, +{ + number.to_f64().ok_or(Fmt(fmt::Error)) +} + /// Casts number to isize pub fn into_isize(number: T) -> Result where @@ -312,6 +321,15 @@ mod tests { ); } + #[test] + fn test_into_f64() { + assert_eq!(into_f64(1).unwrap(), 1.0 as f64); + assert_eq!(into_f64(1.9).unwrap(), 1.9 as f64); + assert_eq!(into_f64(-1.9).unwrap(), -1.9 as f64); + assert_eq!(into_f64(INFINITY as f32).unwrap(), INFINITY); + assert_eq!(into_f64(-INFINITY as f32).unwrap(), -INFINITY); + } + #[test] fn test_into_isize() { assert_eq!(into_isize(1).unwrap(), 1 as isize); -- cgit