Skip to main content

ifc_template_catalog/compliance/
apply.rs

1use crate::definition::{
2    PropertyKind, PropertyTemplate, QuantityTemplate, SetTemplate, SetTemplateKind,
3};
4
5/// Adapter boundary for creating authored data from a catalog template.
6///
7/// A sink owns transactionality: if a callback fails, it must roll back any
8/// partial authored state itself.
9pub trait TemplateSink {
10    /// Failure type raised by any callback; also the type the sink rolls back on.
11    type Error;
12    /// Called once before any member callback for `template`. Sinks that
13    /// open a transaction or authored-set shell should do it here.
14    fn begin(&mut self, template: &SetTemplate) -> Result<(), Self::Error>;
15    /// Called once per property in the template, `path` is the dotted
16    /// ancestor chain for a nested `Complex` property (e.g. `"Usage.Sub"`).
17    fn property(&mut self, path: &str, property: &PropertyTemplate) -> Result<(), Self::Error>;
18    /// Called once per quantity in a quantity-set template. Default is a
19    /// no-op, so sinks that only author property sets need not implement it.
20    fn quantity(&mut self, _quantity: &QuantityTemplate) -> Result<(), Self::Error> {
21        Ok(())
22    }
23    /// Called once after every member callback for `template` has returned `Ok`.
24    fn finish(&mut self, template: &SetTemplate) -> Result<(), Self::Error>;
25}
26
27/// Walk `template`'s properties or quantities in order, calling `sink`'s
28/// `begin`/`property`/`quantity`/`finish` callbacks. Stops and returns the
29/// first callback error; the sink is responsible for any rollback.
30pub fn apply_template<S: TemplateSink>(
31    template: &SetTemplate,
32    sink: &mut S,
33) -> Result<(), S::Error> {
34    sink.begin(template)?;
35    match &template.kind {
36        SetTemplateKind::Property { properties, .. } => {
37            walk_properties("", properties, sink)?;
38        }
39        SetTemplateKind::Quantity { quantities, .. } => {
40            for quantity in quantities {
41                sink.quantity(quantity)?;
42            }
43        }
44    }
45    sink.finish(template)
46}
47
48fn walk_properties<S: TemplateSink>(
49    parent: &str,
50    properties: &[PropertyTemplate],
51    sink: &mut S,
52) -> Result<(), S::Error> {
53    for property in properties {
54        let path = if parent.is_empty() {
55            property.name.clone()
56        } else {
57            format!("{parent}.{}", property.name)
58        };
59        sink.property(&path, property)?;
60        if let PropertyKind::Complex { properties, .. } = &property.kind {
61            walk_properties(&path, properties, sink)?;
62        }
63    }
64    Ok(())
65}