docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Value to string conversion for document insertion.
//!
//! These rules are the ones the crate has always used, moved into the domain so
//! the evaluator does not depend on the old engine module.

use serde_json::Value;

use super::error::RenderError;

/// Convert a JSON value to text for insertion.
///
/// Strings pass through, numbers keep their natural spelling, booleans become
/// `true` or `false`. Null, arrays and objects have no text form and return an
/// error.
pub(crate) fn value_to_string(value: &Value) -> Result<String, RenderError> {
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::Number(number) => {
            if let Some(integer) = number.as_i64() {
                Ok(integer.to_string())
            } else if let Some(integer) = number.as_u64() {
                Ok(integer.to_string())
            } else if let Some(float) = number.as_f64() {
                Ok(float.to_string())
            } else {
                Ok(number.to_string())
            }
        }
        Value::Bool(value) => Ok(value.to_string()),
        Value::Null => Err(RenderError::CannotConvertToText {
            value_type: "null".to_owned(),
        }),
        Value::Array(_) => Err(RenderError::CannotConvertToText {
            value_type: "array".to_owned(),
        }),
        Value::Object(_) => Err(RenderError::CannotConvertToText {
            value_type: "object".to_owned(),
        }),
    }
}

/// A short name for a JSON value kind, used in error messages.
pub(crate) fn type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::indexing_slicing
    )]

    use super::*;
    use serde_json::json;

    #[test]
    fn formats_scalars() {
        assert_eq!(value_to_string(&json!("hello")).unwrap(), "hello");
        assert_eq!(value_to_string(&json!(42)).unwrap(), "42");
        assert_eq!(value_to_string(&json!(2.5)).unwrap(), "2.5");
        assert_eq!(value_to_string(&json!(true)).unwrap(), "true");
    }

    #[test]
    fn rejects_structured_values() {
        assert!(value_to_string(&json!(null)).is_err());
        assert!(value_to_string(&json!([1, 2])).is_err());
        assert!(value_to_string(&json!({"a": 1})).is_err());
    }
}