yaml_schema/schemas/
one_of.rs

1use saphyr::AnnotatedMapping;
2use saphyr::MarkedYaml;
3use saphyr::YamlData;
4
5use crate::YamlSchema;
6use crate::loader;
7use crate::utils::format_vec;
8
9/// The `oneOf` schema is a schema that matches if one, and only one of the schemas in the `oneOf` array match.
10/// The schemas are tried in order, and the first match is used. If no match is found, an error is added
11/// to the context.
12#[derive(Debug, Default, PartialEq)]
13pub struct OneOfSchema {
14    pub one_of: Vec<YamlSchema>,
15}
16
17impl std::fmt::Display for OneOfSchema {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        write!(f, "oneOf:{}", format_vec(&self.one_of))
20    }
21}
22
23impl TryFrom<&MarkedYaml<'_>> for OneOfSchema {
24    type Error = crate::Error;
25
26    fn try_from(value: &MarkedYaml) -> Result<Self, Self::Error> {
27        if let YamlData::Mapping(mapping) = &value.data {
28            OneOfSchema::try_from(mapping)
29        } else {
30            Err(expected_mapping!(value))
31        }
32    }
33}
34
35impl TryFrom<&AnnotatedMapping<'_, MarkedYaml<'_>>> for OneOfSchema {
36    type Error = crate::Error;
37
38    fn try_from(mapping: &AnnotatedMapping<'_, MarkedYaml<'_>>) -> crate::Result<Self> {
39        match mapping.get(&MarkedYaml::value_from_str("oneOf")) {
40            Some(value) => {
41                let one_of = loader::load_array_of_schemas_marked(value)?;
42                Ok(OneOfSchema { one_of })
43            }
44            None => Err(generic_error!("No `oneOf` key found!")),
45        }
46    }
47}