Skip to content

Commit

Permalink
Add int filter
Browse files Browse the repository at this point in the history
  • Loading branch information
youmouse committed Nov 3, 2018
1 parent 940f90b commit 7dce5de
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion askama_shared/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ mod json;
#[cfg(feature = "serde-json")]
pub use self::json::json;

use error::Error::Fmt;
use num_traits::cast::NumCast;
use num_traits::Signed;
use std::fmt;

Expand All @@ -20,14 +22,15 @@ 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; 19] = [
pub const BUILT_IN_FILTERS: [&str; 20] = [
"abs",
"capitalize",
"center",
"e",
"escape",
"format",
"indent",
"int",
"join",
"linebreaks",
"linebreaksbr",
Expand Down Expand Up @@ -158,6 +161,14 @@ pub fn indent(s: &fmt::Display, width: &usize) -> Result<String> {
Ok(indented)
}

/// Casts number to i32
pub fn int<T>(number: T) -> Result<i32>
where
T: NumCast,
{
number.to_i32().ok_or(Fmt(fmt::Error))
}

/// Joins iterable into a string separated by provided argument
pub fn join<T, I, S>(input: I, separator: S) -> Result<String>
where
Expand Down Expand Up @@ -246,6 +257,7 @@ pub fn wordcount(s: &fmt::Display) -> Result<usize> {
#[cfg(test)]
mod tests {
use super::*;
use std::f32::INFINITY;

#[test]
fn test_linebreaks() {
Expand Down Expand Up @@ -300,6 +312,19 @@ mod tests {
);
}

#[test]
fn test_int() {
assert_eq!(int(1).unwrap(), 1 as i32);
assert_eq!(int(1.9).unwrap(), 1 as i32);
assert_eq!(int(-1.9).unwrap(), -1 as i32);
assert_eq!(int(1.5 as f64).unwrap(), 1 as i32);
assert_eq!(int(-1.5 as f64).unwrap(), -1 as i32);
match int(INFINITY) {
Err(Fmt(fmt::Error)) => assert!(true),
_ => assert!(false, "Should return error of type Err(Fmt(fmt::Error))"),
};
}

#[test]
fn test_join() {
assert_eq!(
Expand Down

0 comments on commit 7dce5de

Please sign in to comment.