Skip to main content

Crate hl7_3_derive

Crate hl7_3_derive 

Source
Expand description

Derive macro for hl7-3: map a struct’s fields to XML element attributes and children once, in the type definition, instead of writing the same accessor calls at every call site.

This crate is not used directly. hl7-3 re-exports the macro behind its derive feature, so the dependency to add is:

hl7-3 = { version = "0.1", features = ["derive"] }

Keeping the macro in a crate of their own is what lets the default build of hl7-3 keep exactly one dependency: syn and quote are compiled only for callers who ask for the macro.

use hl7_3::FromElement;
use hl7_3::rim::Act;

#[derive(FromElement, Default)]
struct Observation {
    #[element("classCode")]     class_code: String,
    #[element("moodCode")]      mood_code: String,
    #[element(child = "note")]  note: Option<String>,
    #[element(nested = "component")] component: Act, // its own FromElement
    #[element(raw)]             raw: hl7_3::xml::Element, // the escape hatch
}

One attribute per field, and a field with none is Default::default():

attributereads
#[element("classCode")]the classCode attribute, via FromElementValue::from_attribute
#[element(child = "note")]the note child’s text, via FromElementValue::from_child_text
#[element(nested = "component")]the component child, via the field type’s own FromElement
#[element(raw)]the whole element (field type must be hl7_3::xml::Element)
noneDefault::default()

There is no #[derive(ToElement)]: hl7-3 has no XML-writing capability yet (see its spec/index.md §1), so a write-direction macro would have nothing real to generate.

§When hl7-3 is not called hl7_3

The generated code names the crate absolutely, as ::hl7_3, so that it works wherever the type is defined without the caller importing anything. A caller who renames the dependency — hl7 = { package = "hl7-3" } in Cargo.toml, or a workspace that aliases it — has no ::hl7_3 for the macro to reach, and the generated code stops compiling. Say where it is instead, once, on the struct:

#[derive(FromElement)]
#[element(crate = hl7)]        // or `crate = "::some::path::to::hl7_3"`
struct Author {
    #[element("classCode")] class_code: String,
}

Derive Macros§

FromElement
Derive FromElement: read each annotated field from an XML element’s attributes or children.