xsd_parser/models/meta/
reference.rs

1//! Contains the [`ReferenceMeta`] type information and all related types.
2
3use std::hash::{Hash, Hasher};
4
5use crate::models::{
6    schema::{MaxOccurs, MinOccurs},
7    Ident,
8};
9
10use super::{MetaTypes, TypeEq};
11
12/// Type information that defines a reference to another type.
13#[derive(Debug, Clone)]
14pub struct ReferenceMeta {
15    /// Type that is referenced.
16    pub type_: Ident,
17
18    /// Minimum occurrence of the referenced type.
19    pub min_occurs: MinOccurs,
20
21    /// Maximum occurrence of the referenced type.
22    pub max_occurs: MaxOccurs,
23}
24
25impl ReferenceMeta {
26    /// Create a new [`ReferenceMeta`] instance from the passed `type_`.
27    #[must_use]
28    pub fn new<T>(type_: T) -> Self
29    where
30        T: Into<Ident>,
31    {
32        Self {
33            type_: type_.into(),
34            min_occurs: 1,
35            max_occurs: MaxOccurs::Bounded(1),
36        }
37    }
38
39    /// Returns `true` if this is a reference references a single type, `false` otherwise.
40    ///
41    /// This means that it is more or less just a type definition or renaming of an
42    /// existing type.
43    #[must_use]
44    pub fn is_single(&self) -> bool {
45        self.min_occurs == 1 && self.max_occurs == MaxOccurs::Bounded(1)
46    }
47
48    /// Sets the minimum occurrence of the referenced type.
49    #[must_use]
50    pub fn min_occurs(mut self, min: MinOccurs) -> Self {
51        self.min_occurs = min;
52
53        self
54    }
55
56    /// Sets the maximum occurrence of the referenced type.
57    #[must_use]
58    pub fn max_occurs(mut self, max: MaxOccurs) -> Self {
59        self.max_occurs = max;
60
61        self
62    }
63}
64
65impl TypeEq for ReferenceMeta {
66    fn type_hash<H: Hasher>(&self, hasher: &mut H, types: &MetaTypes) {
67        let Self {
68            type_,
69            min_occurs,
70            max_occurs,
71        } = self;
72
73        type_.type_hash(hasher, types);
74        min_occurs.hash(hasher);
75        max_occurs.hash(hasher);
76    }
77
78    fn type_eq(&self, other: &Self, types: &MetaTypes) -> bool {
79        let Self {
80            type_,
81            min_occurs,
82            max_occurs,
83        } = self;
84
85        type_.type_eq(&other.type_, types)
86            && min_occurs.eq(&other.min_occurs)
87            && max_occurs.eq(&other.max_occurs)
88    }
89}