xsd_parser/types/info/
union.rs

1//! Contains the [`UnionInfo`] type information and all related types.
2
3use std::hash::{Hash, Hasher};
4use std::ops::{Deref, DerefMut};
5
6use crate::types::{Ident, TypeEq, Types};
7
8use super::Base;
9
10/// Type information that defines a union type.
11#[derive(Default, Debug, Clone)]
12pub struct UnionInfo {
13    /// Base type of the union type.
14    pub base: Base,
15
16    /// Types that are unified in this union type.
17    pub types: UnionTypesInfo,
18}
19
20/// Type information that represents one type unified by a [`UnionInfo`].
21#[derive(Debug, Clone)]
22pub struct UnionTypeInfo {
23    /// Target type of this type variant.
24    pub type_: Ident,
25
26    /// Name of the variant to use inside the generated code.
27    pub display_name: Option<String>,
28}
29
30/// Type information that represents a list of [`UnionTypeInfo`] instances.
31#[derive(Default, Debug, Clone)]
32pub struct UnionTypesInfo(pub Vec<UnionTypeInfo>);
33
34/* UnionInfo */
35
36impl TypeEq for UnionInfo {
37    fn type_hash<H: Hasher>(&self, hasher: &mut H, ctx: &Types) {
38        let Self { base, types } = self;
39
40        base.type_hash(hasher, ctx);
41        types.type_hash(hasher, ctx);
42    }
43
44    fn type_eq(&self, other: &Self, ctx: &Types) -> bool {
45        let Self { base, types } = self;
46
47        base.type_eq(&other.base, ctx) && types.type_eq(&other.types, ctx)
48    }
49}
50
51/* UnionTypeInfo */
52
53impl UnionTypeInfo {
54    /// Create a new [`UnionTypeInfo`] from the passed `type_`.
55    #[must_use]
56    pub fn new(type_: Ident) -> Self {
57        Self {
58            type_,
59            display_name: None,
60        }
61    }
62}
63
64impl TypeEq for UnionTypeInfo {
65    fn type_hash<H: Hasher>(&self, hasher: &mut H, types: &Types) {
66        let Self {
67            type_,
68            display_name,
69        } = self;
70
71        type_.type_hash(hasher, types);
72        display_name.hash(hasher);
73    }
74
75    fn type_eq(&self, other: &Self, types: &Types) -> bool {
76        let Self {
77            type_,
78            display_name,
79        } = self;
80
81        type_.type_eq(&other.type_, types) && display_name.eq(&other.display_name)
82    }
83}
84
85/* UnionTypesInfo */
86
87impl Deref for UnionTypesInfo {
88    type Target = Vec<UnionTypeInfo>;
89
90    fn deref(&self) -> &Self::Target {
91        &self.0
92    }
93}
94
95impl DerefMut for UnionTypesInfo {
96    fn deref_mut(&mut self) -> &mut Self::Target {
97        &mut self.0
98    }
99}
100
101impl TypeEq for UnionTypesInfo {
102    fn type_hash<H: Hasher>(&self, hasher: &mut H, types: &Types) {
103        TypeEq::type_hash_slice(&self.0, hasher, types);
104    }
105
106    fn type_eq(&self, other: &Self, types: &Types) -> bool {
107        TypeEq::type_eq_iter(self.0.iter(), other.0.iter(), types)
108    }
109}