diff --git a/CHANGELOG.md b/CHANGELOG.md index 96154b33..e2d5b255 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ All notable changes to eww will be listed here, starting at changes since versio - Add keyboard support for button presses (By: julianschuler) - Support empty string for safe access operator (By: ModProg) - Add `log` function calls to simplexpr (By: topongo) +- Add `byteshumanreadable` function calls to simplexpr (By: bkueng) ## [0.6.0] (21.04.2024) diff --git a/crates/simplexpr/src/eval.rs b/crates/simplexpr/src/eval.rs index 8ee0d843..e293c39c 100644 --- a/crates/simplexpr/src/eval.rs +++ b/crates/simplexpr/src/eval.rs @@ -508,6 +508,33 @@ fn call_expr_function(name: &str, args: Vec) -> Result Err(EvalError::WrongArgCount(name.to_string())), }, + "byteshumanreadable" => match args.as_slice() { + [size, digits] => { + let mut size = size.as_f64()?; + let digits = if size > 0.0 { digits.as_i32()? } else { 0 }; + let mut suffix = "B"; + while size >= 1024.0 { + match suffix { + "B" => { + suffix = "KB"; + } + "KB" => { + suffix = "MB"; + } + "MB" => { + suffix = "GB"; + } + "GB" => { + suffix = "TB"; + } + _ => break, + } + size /= 1024.0; + } + Ok(DynVal::from(format!("{:.1$} ", size, digits as usize) + suffix)) + } + _ => Err(EvalError::WrongArgCount(name.to_string())), + }, _ => Err(EvalError::UnknownFunction(name.to_string())), } @@ -610,5 +637,7 @@ mod tests { jq_empty_arg(r#"jq("[ \"foo\" ]", ".[0]", "")"#) => Ok(DynVal::from(r#""foo""#)), jq_invalid_arg(r#"jq("[ \"foo\" ]", ".[0]", "hello")"#) => Ok(DynVal::from(r#""foo""#)), jq_no_arg(r#"jq("[ \"foo\" ]", ".[0]")"#) => Ok(DynVal::from(r#""foo""#)), + byteshumanreadable1(r#"byteshumanreadable(2048,1)"#) => Ok(DynVal::from("2.0 KB")), + byteshumanreadable2(r#"byteshumanreadable(10000000000,3)"#) => Ok(DynVal::from("9.313 GB")), } } diff --git a/docs/src/expression_language.md b/docs/src/expression_language.md index 106776ae..f620e7df 100644 --- a/docs/src/expression_language.md +++ b/docs/src/expression_language.md @@ -68,3 +68,4 @@ Supported currently are the following features: Same as other `formattime`, but does not accept timezone. Instead, it uses system's local timezone. Check [chrono's documentation](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) for more information about format string. + - `byteshumanreadable(size, decimal_digits)`: Convert and round a given value in bytes to a human-readable format. E.g. `byteshumanreadable(2048, 2)` returns `"2.00 KB"`.