docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Truthiness rules for conditional expressions.
//!
//! Falsy values are null, false, zero, the empty string, the empty array and
//! the empty object. Everything else is truthy.

use serde_json::Value;

/// Whether a JSON value counts as true in a conditional.
pub(crate) fn is_truthy(value: &Value) -> bool {
    match value {
        Value::Null => false,
        Value::Bool(value) => *value,
        Value::Number(number) => number.as_f64() != Some(0.0),
        Value::String(text) => !text.is_empty(),
        Value::Array(items) => !items.is_empty(),
        Value::Object(map) => !map.is_empty(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn empty_values_are_falsy() {
        for value in [
            json!(null),
            json!(false),
            json!(0),
            json!(""),
            json!([]),
            json!({}),
        ] {
            assert!(!is_truthy(&value), "{value} should be falsy");
        }
    }

    #[test]
    fn non_empty_values_are_truthy() {
        for value in [
            json!(true),
            json!(1),
            json!(-1),
            json!("x"),
            json!([0]),
            json!({"a": 1}),
        ] {
            assert!(is_truthy(&value), "{value} should be truthy");
        }
    }
}