hcl::ser

Function doubly_labeled_block

Source
pub fn doubly_labeled_block<T, K, V, S>(
    value: T,
    serializer: S,
) -> Result<S::Ok, S::Error>
where T: IntoIterator<Item = (K, V)>, K: Serialize + Eq, V: Serialize, S: Serializer,
Expand description

Hints the Serializer to serialize T as an HCL block with two labels.

This function is intended to be used in the #[serde(serialize_with)] attribute and wraps T and each value of T with a LabeledBlock<T>. One use case for this function is terraform configuration where blocks with two labels are common in various places.

See the type-level documentation of LabeledBlock<T> for more.

§Example

The following example shows a very simplified and incomplete way to serialize terraform configuration.

use indexmap::{indexmap, IndexMap};
use serde::Serialize;

#[derive(Serialize)]
struct Config {
    #[serde(serialize_with = "hcl::ser::doubly_labeled_block")]
    resource: IndexMap<String, IndexMap<String, IndexMap<String, String>>>,
}

let config = Config {
    resource: indexmap! {
        "aws_sns_topic".into() => indexmap! {
            "mytopic".into() => indexmap! {
                "name".into() => "mytopic".into(),
            },
        },
    },
};

let expected = r#"
resource "aws_sns_topic" "mytopic" {
  name = "mytopic"
}
"#.trim_start();

assert_eq!(hcl::to_string(&config)?, expected);

§Errors

Serialization fails if the type’s shape makes it impossible to represent it as an HCL block with two labels.