hcl/structure/
attribute.rs

1//! Types to represent and build HCL attributes.
2
3use crate::expr::Expression;
4use crate::{Identifier, Value};
5use serde::Deserialize;
6use std::iter;
7
8/// Represents an HCL attribute which consists of an attribute key and a value expression.
9///
10/// In HCL syntax this is represented as:
11///
12/// ```hcl
13/// key = value
14/// ```
15///
16/// Use [`Attribute::new`] to construct an [`Attribute`] from a value that is convertible to this
17/// crate's [`Expression`] type.
18#[derive(Deserialize, Debug, PartialEq, Eq, Clone)]
19pub struct Attribute {
20    /// The HCL attribute's key.
21    pub key: Identifier,
22    /// The value expression of the HCL attribute.
23    pub expr: Expression,
24}
25
26impl Attribute {
27    /// Creates a new `Attribute` from an attribute key that is convertible into a `String` and an
28    /// attribute value that is convertible into an `Expression`.
29    pub fn new<K, V>(key: K, expr: V) -> Attribute
30    where
31        K: Into<Identifier>,
32        V: Into<Expression>,
33    {
34        Attribute {
35            key: key.into(),
36            expr: expr.into(),
37        }
38    }
39
40    /// Returns a reference to the attribute key.
41    pub fn key(&self) -> &str {
42        &self.key
43    }
44
45    /// Returns a reference to the attribute value expression.
46    pub fn expr(&self) -> &Expression {
47        &self.expr
48    }
49}
50
51impl From<Attribute> for Value {
52    fn from(attr: Attribute) -> Value {
53        iter::once((attr.key.into_inner(), attr.expr)).collect()
54    }
55}
56
57impl<K, V> From<(K, V)> for Attribute
58where
59    K: Into<Identifier>,
60    V: Into<Expression>,
61{
62    fn from((key, expr): (K, V)) -> Attribute {
63        Attribute::new(key, expr)
64    }
65}