ninja_writer/
variable.rs

1//! Implementation of variables
2
3use alloc::string::String;
4use core::fmt::{Display, Formatter, Result};
5
6use crate::ToArg;
7
8/// A variable declaration (`name = value`)
9///
10/// See <https://ninja-build.org/manual.html#_variables>
11///
12/// # Escaping
13/// Escaping must be done when constructing the variable. No escaping is done when serializing.
14/// ```rust
15/// use ninja_writer::Variable;
16///
17/// let var = Variable::new("foo", "I have a $ in me");
18///
19/// assert_eq!(var.to_string(), "foo = I have a $ in me");
20/// ```
21#[derive(Debug, Clone, PartialEq, Default)]
22pub struct Variable {
23    /// The name of the variable
24    pub name: String,
25    /// The value of the variable
26    pub value: String,
27}
28
29impl Variable {
30    /// Create a new variable declaration
31    pub fn new(name: impl ToArg, value: impl ToArg) -> Self {
32        Self {
33            name: name.to_arg(),
34            value: value.to_arg(),
35        }
36    }
37}
38
39impl Display for Variable {
40    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
41        write!(f, "{} = {}", self.name, self.value)
42    }
43}
44
45/// Convienience trait to implement types that supports variables
46pub trait Variables: Sized {
47    /// Add a variable
48    ///
49    /// This is an internal method to add a variable to the current scope.
50    fn add_variable_internal(&self, v: Variable);
51
52    /// Add a variable to the current scope
53    fn variable(self, name: impl ToArg, value: impl ToArg) -> Self {
54        self.add_variable_internal(Variable::new(name, value));
55        self
56    }
57}