xsd_parser/types/
name.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//! Contains the [`Name`] helper type and all related types.

use std::borrow::Cow;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::mem::take;

use inflector::Inflector;

/// Type that represents a name of a XSD element
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Name {
    /// The name was explicitly set to the given value.
    Named(Cow<'static, str>),

    /// The name is unknown and should be generated out of the provided information.
    Unnamed {
        /// Unique id for this name.
        id: usize,

        /// Extension that may be added to the name.
        ext: Option<Cow<'static, str>>,
    },
}

impl Name {
    /// Create a new [`Name::Named`] using the passed `name`.
    #[must_use]
    pub const fn named(name: &'static str) -> Self {
        Self::Named(Cow::Borrowed(name))
    }

    /// Create a new [`Name::Named`] using the passed `name`.
    #[must_use]
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self::Named(Cow::Owned(name.into()))
    }

    /// Remove the provided `suffix` from the [`Name::Named`] or the [`Name::Unnamed::ext`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::borrow::Cow;
    /// # use xsd_parser::types::Name;
    /// let name = Name::new("test-fuu");
    /// let expected = Name::new("test");
    /// assert_eq!(name.remove_suffix("-fuu"), expected);
    ///
    /// let name = Name::Unnamed { id: 123, ext: Some(Cow::Borrowed("test-fuu")) };
    /// let expected = Name::Unnamed { id: 123, ext: Some(Cow::Owned("test".into())) };;
    /// assert_eq!(name.remove_suffix("-fuu"), expected);
    /// ```
    #[must_use]
    pub fn remove_suffix(&self, suffix: &str) -> Self {
        match self {
            Self::Named(s) => {
                if let Some(s) = s.strip_suffix(suffix) {
                    Self::new(s)
                } else {
                    Self::Named(s.clone())
                }
            }
            Self::Unnamed { id, ext: Some(ext) } => {
                if let Some(ext) = ext.strip_suffix(suffix) {
                    Self::Unnamed {
                        id: *id,
                        ext: Some(Cow::Owned(ext.to_owned())),
                    }
                } else {
                    Self::Unnamed {
                        id: *id,
                        ext: Some(ext.clone()),
                    }
                }
            }
            x => x.clone(),
        }
    }

    /// Create a type name from this [`Name`] object.
    ///
    /// This method can be used to generate a rust type name from this name object.
    /// The resulting name is written in pascal case and may or may not contain
    /// additional information depending on the passed arguments.
    ///
    /// # Arguments
    /// - `with_id` Wether to add the unique id of the name to the resulting name or not
    /// - `name` Optional name that should be added to the resulting name
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::borrow::Cow;
    /// # use xsd_parser::types::Name;
    ///
    /// let name = Name::new("test");
    /// assert_eq!(Name::new("Test"), name.to_type_named(false, None));
    /// assert_eq!(Name::new("Test"), name.to_type_named(true, None));
    /// assert_eq!(Name::new("Test"), name.to_type_named(false, Some("extra")));
    /// assert_eq!(Name::new("Test"), name.to_type_named(true, Some("extra")));
    ///
    /// let name = Name::Unnamed { id: 123, ext: None };
    /// assert_eq!(Name::new("Unnamed123"), name.to_type_named(false, None));
    /// assert_eq!(Name::new("Extra"), name.to_type_named(false, Some("extra")));
    /// assert_eq!(Name::new("Unnamed123"), name.to_type_named(true, None));
    /// assert_eq!(Name::new("Extra123"), name.to_type_named(true, Some("extra")));
    ///
    /// let name = Name::Unnamed { id: 123, ext: Some(Cow::Borrowed("ext")) };
    /// assert_eq!(Name::new("ExtUnnamed123"), name.to_type_named(false, None));
    /// assert_eq!(Name::new("ExtExtra"), name.to_type_named(false, Some("extra")));
    /// assert_eq!(Name::new("ExtUnnamed123"), name.to_type_named(true, None));
    /// assert_eq!(Name::new("ExtExtra123"), name.to_type_named(true, Some("extra")));
    /// ```
    #[must_use]
    pub fn to_type_named(&self, with_id: bool, name: Option<&str>) -> Self {
        match (self, name) {
            (Self::Named(s), _) => Self::Named(Cow::Owned(s.to_pascal_case())),
            (Self::Unnamed { id, ext: Some(ext) }, Some(name)) if with_id => {
                Self::Named(Cow::Owned(format!(
                    "{}{}{id}",
                    ext.to_pascal_case(),
                    name.to_pascal_case()
                )))
            }
            (Self::Unnamed { ext: Some(ext), .. }, Some(name)) => Self::Named(Cow::Owned(format!(
                "{}{}",
                ext.to_pascal_case(),
                name.to_pascal_case()
            ))),
            (Self::Unnamed { id, ext: None, .. }, Some(name)) if with_id => {
                Self::Named(Cow::Owned(format!("{}{id}", name.to_pascal_case())))
            }
            (Self::Unnamed { ext: None, .. }, Some(name)) => {
                Self::Named(Cow::Owned(name.to_pascal_case()))
            }
            (
                Self::Unnamed {
                    id, ext: Some(ext), ..
                },
                None,
            ) => Self::Named(Cow::Owned(format!("{}Unnamed{id}", ext.to_pascal_case()))),
            (Self::Unnamed { id, ext: None, .. }, None) => {
                Self::Named(Cow::Owned(format!("Unnamed{id}")))
            }
        }
    }

    /// Returns `true` if this is a [`Name::Named`], `false` otherwise.
    #[must_use]
    pub fn is_named(&self) -> bool {
        matches!(self, Self::Named(_))
    }

    /// Returns `true` if this is a [`Name::Unnamed`], `false` otherwise.
    #[must_use]
    pub fn is_unnamed(&self) -> bool {
        matches!(self, Self::Unnamed { .. })
    }

    /// Returns `true` if this is a [`Name::Unnamed`] with extensions, `false` otherwise.
    #[must_use]
    pub fn has_extension(&self) -> bool {
        matches!(self, Self::Unnamed { ext: Some(_), .. })
    }

    /// Returns the value of [`Name::Named`] as `Some(&str)`, or `None` if it's an [`Name::Unnamed`].
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::Named(s) => Some(s),
            Self::Unnamed { .. } => None,
        }
    }

    /// Adds extensions to this name.
    ///
    /// # Arguments
    /// - `replace` replace any existing extension with the new one
    /// - `iter` iterator of extensions to apply
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::borrow::Cow;
    /// # use xsd_parser::types::Name;
    ///
    /// let name = Name::new("test");
    /// assert_eq!(Name::new("extTest"), name.extend(false, Some("ext")));
    ///
    /// let name = Name::Unnamed { id: 123, ext: Some(Cow::Borrowed("ext")) };
    /// assert_eq!(Name::Unnamed { id: 123, ext: Some(Cow::Owned("fuu".into())) }, name.clone().extend(true, Some("fuu")));
    /// assert_eq!(Name::Unnamed { id: 123, ext: Some(Cow::Owned("fuuExt".into())) }, name.extend(false, Some("fuu")));
    /// ``````
    #[must_use]
    pub fn extend<I>(mut self, mut replace: bool, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: Display,
    {
        for s in iter {
            match &mut self {
                Self::Named(name) => *name = Cow::Owned(format!("{s}{}", name.to_pascal_case())),
                Self::Unnamed { ext: Some(ext), .. } if !take(&mut replace) => {
                    *ext = Cow::Owned(format!("{s}{}", ext.to_pascal_case()));
                }
                Self::Unnamed { ext, .. } => *ext = Some(Cow::Owned(s.to_string())),
            }
        }

        self
    }
}

impl Display for Name {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            Self::Named(x) => write!(f, "{x}"),
            Self::Unnamed { id, ext: None } => write!(f, "Unnamed{id}"),
            Self::Unnamed { id, ext: Some(ext) } => write!(f, "{ext}Unnamed{id}"),
        }
    }
}

impl From<String> for Name {
    fn from(value: String) -> Self {
        Self::Named(Cow::Owned(value))
    }
}

impl From<&'static str> for Name {
    fn from(value: &'static str) -> Self {
        Self::Named(Cow::Borrowed(value))
    }
}