|
| 1 | +//! 'cddlDefinitions' field definition |
| 2 | +
|
| 3 | +use std::{collections::HashMap, fmt::Display}; |
| 4 | + |
| 5 | +use cbork_cddl_parser::validate_cddl; |
| 6 | + |
| 7 | +#[derive(serde::Deserialize)] |
| 8 | +pub struct CddlDefinitions(HashMap<CddlType, CddlDef>); |
| 9 | + |
| 10 | +#[derive(Clone, serde::Deserialize, PartialEq, Eq, Hash)] |
| 11 | +pub struct CddlType(String); |
| 12 | + |
| 13 | +#[derive(serde::Deserialize)] |
| 14 | +struct CddlDef { |
| 15 | + def: String, |
| 16 | + requires: Vec<CddlType>, |
| 17 | +} |
| 18 | + |
| 19 | +impl Display for CddlType { |
| 20 | + fn fmt( |
| 21 | + &self, |
| 22 | + f: &mut std::fmt::Formatter<'_>, |
| 23 | + ) -> std::fmt::Result { |
| 24 | + self.0.fmt(f) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl CddlDef { |
| 29 | + fn get_cddl_spec( |
| 30 | + &self, |
| 31 | + cddl_type: &CddlType, |
| 32 | + ) -> String { |
| 33 | + format!("{cddl_type}={}\n", self.def) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl CddlDefinitions { |
| 38 | + fn find_cddl_def( |
| 39 | + &self, |
| 40 | + cddl_type: &CddlType, |
| 41 | + ) -> anyhow::Result<&CddlDef> { |
| 42 | + self.0.get(cddl_type).ok_or(anyhow::anyhow!( |
| 43 | + "Cannot find a cddl definition for the {cddl_type}" |
| 44 | + )) |
| 45 | + } |
| 46 | + |
| 47 | + /// Returns a full CDDL specification schema. |
| 48 | + /// Performs |
| 49 | + /// |
| 50 | + /// # Errors |
| 51 | + /// - Cannot find a cddl definition |
| 52 | + /// - Not a valid resulted CDDL spec |
| 53 | + pub fn get_cddl_spec( |
| 54 | + &self, |
| 55 | + cddl_type: &CddlType, |
| 56 | + ) -> anyhow::Result<String> { |
| 57 | + let def = self.find_cddl_def(cddl_type)?; |
| 58 | + |
| 59 | + let spec = def.get_cddl_spec(cddl_type); |
| 60 | + let mut requires = def.requires.clone(); |
| 61 | + |
| 62 | + let mut imports = HashMap::new(); |
| 63 | + while let Some(req) = requires.pop() { |
| 64 | + let req_def = self.find_cddl_def(&req)?; |
| 65 | + let req_spec = req_def.get_cddl_spec(&req); |
| 66 | + if imports.insert(req, req_spec).is_none() { |
| 67 | + requires.extend(req_def.requires.clone()); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + let mut spec = imports.values().fold(spec, |mut spec, import_spec| { |
| 72 | + spec.push_str(import_spec); |
| 73 | + spec |
| 74 | + }); |
| 75 | + |
| 76 | + validate_cddl(&mut spec, &cbork_cddl_parser::Extension::CDDL)?; |
| 77 | + Ok(spec) |
| 78 | + } |
| 79 | +} |
0 commit comments