hcl::ser

Function labeled_block

Source
pub fn labeled_block<T, S>(value: T, serializer: S) -> Result<S::Ok, S::Error>
where T: Serialize, S: Serializer,
Expand description

Hints the Serializer to serialize T as a labeled HCL block.

This function is intended to be used in the #[serde(serialize_with)] attribute and wraps T with a LabeledBlock<T>.

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

§Example

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

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

#[derive(Serialize)]
struct User {
    email: String,
}

let config = Config {
    user: indexmap! {
        "john".into() => User {
            email: "johndoe@example.com".into(),
        },
        "jane".into() => User {
            email: "janedoe@example.com".into(),
        },
    },
};

let expected = r#"
user "john" {
  email = "johndoe@example.com"
}

user "jane" {
  email = "janedoe@example.com"
}
"#.trim_start();

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

§Errors

Serialization fails if the type’s shape makes it impossible to represent it as a labeled HCL block.