Parent [>]
1//! Custom Askama filters.
2
3/// Returns `singular` if `count == 1`, otherwise `plural`.
4pub fn pluralize(count: &usize, singular: &str, plural: &str) -> askama::Result<String> {
5    Ok(if *count == 1 {
6        singular.to_string()
7    } else {
8        plural.to_string()
9    })
10}
11
12/// Returns the first 8 characters of `s`, or the whole string if shorter.
13///
14/// Unlike a raw `s[..8]` slice, this never panics on short input, so it is
15/// safe to apply to SHAs and refs taken directly from request paths.
16fn short_chars(s: &str) -> String {
17    s.chars().take(8).collect()
18}
19
20/// Askama filter `{{ value|short }}`: the first 8 characters of the input.
21#[askama::filter_fn]
22pub fn short<T: std::fmt::Display>(s: T, _: &dyn askama::Values) -> askama::Result<String> {
23    Ok(short_chars(&s.to_string()))
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn pluralize_singular() {
32        assert_eq!(pluralize(&1, "item", "items").unwrap(), "item");
33    }
34
35    #[test]
36    fn pluralize_zero() {
37        assert_eq!(pluralize(&0, "item", "items").unwrap(), "items");
38    }
39
40    #[test]
41    fn pluralize_multiple() {
42        assert_eq!(pluralize(&3, "item", "items").unwrap(), "items");
43    }
44
45    #[test]
46    fn short_full() {
47        assert_eq!(short_chars("0123456789abcdef"), "01234567");
48    }
49
50    #[test]
51    fn short_abbreviated() {
52        assert_eq!(short_chars("863a47b"), "863a47b");
53    }
54
55    #[test]
56    fn short_branch_name() {
57        assert_eq!(short_chars("main"), "main");
58    }
59
60    #[test]
61    fn short_empty() {
62        assert_eq!(short_chars(""), "");
63    }
64}