aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--askama_shared/Cargo.toml1
-rw-r--r--askama_shared/src/filters/mod.rs19
-rw-r--r--askama_shared/src/lib.rs1
3 files changed, 20 insertions, 1 deletions
diff --git a/askama_shared/Cargo.toml b/askama_shared/Cargo.toml
index 4be4971..39ee358 100644
--- a/askama_shared/Cargo.toml
+++ b/askama_shared/Cargo.toml
@@ -10,6 +10,7 @@ workspace = ".."
[dependencies]
askama_escape = { version = "0.1.0", path = "../askama_escape" }
+humansize = "1.1.0"
num-traits = "0.2.6"
serde = "1.0"
serde_derive = "1.0"
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs
index 35166ff..672c5b3 100644
--- a/askama_shared/src/filters/mod.rs
+++ b/askama_shared/src/filters/mod.rs
@@ -12,6 +12,7 @@ pub use self::json::json;
use askama_escape::MarkupDisplay;
use error::Error::Fmt;
+use humansize::{file_size_opts, FileSize};
use num_traits::cast::NumCast;
use num_traits::Signed;
use std::fmt;
@@ -22,12 +23,13 @@ use super::Result;
// 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; 21] = [
+pub const BUILT_IN_FILTERS: [&str; 22] = [
"abs",
"capitalize",
"center",
"e",
"escape",
+ "filesizeformat",
"format",
"indent",
"into_f64",
@@ -77,6 +79,12 @@ where
escape(i)
}
+/// Returns adequate string representation (in KB, ..) of number of bytes
+pub fn filesizeformat(b: usize) -> Result<String> {
+ b.file_size(file_size_opts::DECIMAL)
+ .map_err(|_| Fmt(fmt::Error))
+}
+
/// Formats arguments according to the specified format
///
/// The first argument to this filter must be a string literal (as in normal
@@ -268,6 +276,15 @@ mod tests {
use std::f64::INFINITY;
#[test]
+ fn test_filesizeformat() {
+ assert_eq!(filesizeformat(0).unwrap(), "0 B");
+ assert_eq!(filesizeformat(999).unwrap(), "999 B");
+ assert_eq!(filesizeformat(1000).unwrap(), "1 KB");
+ assert_eq!(filesizeformat(1023).unwrap(), "1.02 KB");
+ assert_eq!(filesizeformat(1024).unwrap(), "1.02 KB");
+ }
+
+ #[test]
fn test_linebreaks() {
assert_eq!(
linebreaks(&"Foo\nBar Baz").unwrap(),
diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs
index 9e2ba6c..a8839fa 100644
--- a/askama_shared/src/lib.rs
+++ b/askama_shared/src/lib.rs
@@ -1,6 +1,7 @@
#![cfg_attr(feature = "cargo-clippy", allow(unused_parens))]
extern crate askama_escape;
+extern crate humansize;
extern crate num_traits;
extern crate serde;
#[macro_use]