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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//! [`NCName`].
//!
//! [`NCName`]: https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName

use core::convert::TryFrom;

use crate::names::chars;
use crate::names::error::{NameError, TargetNameType};
use crate::names::{Name, Nmtoken, Qname};

/// String slice for [`NCName`].
///
/// [`NCName`]: https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Ncname(str);

impl Ncname {
    /// Creates a new `&Ncname`.
    ///
    /// # Failures
    ///
    /// Fails if the given string is not a valid [`NCName`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let name = Ncname::from_str("hello")?;
    /// assert_eq!(name, "hello");
    ///
    /// assert!(Ncname::from_str("").is_err(), "Empty string is not an NCName");
    /// assert!(Ncname::from_str("foo bar").is_err(), "Whitespace is not allowed");
    /// assert!(Ncname::from_str("foo:bar").is_err(), "Colon is not allowed");
    /// assert!(Ncname::from_str("0foo").is_err(), "ASCII digit at the beginning is not allowed");
    /// # Ok::<_, xml_string::names::NameError>(())
    /// ```
    ///
    /// [`NCName`]: https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName
    // `FromStr` can be implemented only for types with static lifetime.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn from_str(s: &str) -> Result<&Self, NameError> {
        <&Self>::try_from(s)
    }

    /// Creates a new `&Ncname` without validation.
    ///
    /// # Safety
    ///
    /// The given string should be a valid [`NCName`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let name = unsafe {
    ///     Ncname::new_unchecked("hello")
    /// };
    /// assert_eq!(name, "hello");
    /// ```
    ///
    /// [`NCName`]: https://www.w3.org/TR/2009/REC-xml-names-20091208/#NT-NCName
    #[inline]
    #[must_use]
    pub unsafe fn new_unchecked(s: &str) -> &Self {
        &*(s as *const str as *const Self)
    }

    /// Validates the given string.
    fn validate(s: &str) -> Result<(), NameError> {
        let mut chars = s.char_indices();

        // Check the first character.
        if !chars
            .next()
            .map_or(false, |(_, c)| chars::is_ncname_start(c))
        {
            return Err(NameError::new(TargetNameType::Ncname, 0));
        }

        // Check the following characters.
        if let Some((i, _)) = chars.find(|(_, c)| !chars::is_ncname_continue(*c)) {
            return Err(NameError::new(TargetNameType::Ncname, i));
        }

        Ok(())
    }

    /// Returns the string as `&str`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let name = Ncname::from_str("hello")?;
    /// assert_eq!(name, "hello");
    ///
    /// let s: &str = name.as_str();
    /// assert_eq!(s, "hello");
    /// # Ok::<_, xml_string::names::NameError>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parses the leading `Ncname` and returns the value and the rest input.
    ///
    /// # Exmaples
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let input = "hello:world";
    /// let expected = Ncname::from_str("hello").expect("valid NCName");
    /// assert_eq!(
    ///     Ncname::parse_next(input),
    ///     Ok((expected, ":world"))
    /// );
    /// # Ok::<_, xml_string::names::NameError>(())
    /// ```
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let input = "012";
    /// assert!(Ncname::parse_next(input).is_err());
    /// # Ok::<_, xml_string::names::NameError>(())
    /// ```
    pub fn parse_next(s: &str) -> Result<(&Self, &str), NameError> {
        match Self::from_str(s) {
            Ok(v) => Ok((v, &s[s.len()..])),
            Err(e) if e.valid_up_to() == 0 => Err(e),
            Err(e) => {
                let valid_up_to = e.valid_up_to();
                let v = unsafe {
                    let valid = &s[..valid_up_to];
                    debug_assert!(Self::validate(valid).is_ok());
                    // This is safe because the substring is valid.
                    Self::new_unchecked(valid)
                };
                Ok((v, &s[valid_up_to..]))
            }
        }
    }

    /// Converts a `Box<Ncname>` into a `Box<str>` without copying or allocating.
    ///
    /// # Examples
    ///
    /// ```
    /// # use xml_string::names::Ncname;
    /// let name = Ncname::from_str("ncname")?;
    /// let boxed_name: Box<Ncname> = name.into();
    /// assert_eq!(&*boxed_name, name);
    /// let boxed_str: Box<str> = boxed_name.into_boxed_str();
    /// assert_eq!(&*boxed_str, name.as_str());
    /// # Ok::<_, xml_string::names::NameError>(())
    /// ```
    #[cfg(feature = "alloc")]
    pub fn into_boxed_str(self: alloc::boxed::Box<Self>) -> Box<str> {
        unsafe {
            // This is safe because `Ncname` has the same memory layout as `str`
            // (thanks to `#[repr(transparent)]`).
            alloc::boxed::Box::<str>::from_raw(alloc::boxed::Box::<Self>::into_raw(self) as *mut str)
        }
    }
}

impl_traits_for_custom_string_slice!(Ncname);

impl AsRef<Nmtoken> for Ncname {
    #[inline]
    fn as_ref(&self) -> &Nmtoken {
        unsafe {
            debug_assert!(
                Nmtoken::from_str(self.as_str()).is_ok(),
                "NCName {:?} must be a valid Nmtoken",
                self.as_str()
            );
            // This is safe because an NCName is also a valid Nmtoken.
            Nmtoken::new_unchecked(self.as_str())
        }
    }
}

impl AsRef<Name> for Ncname {
    #[inline]
    fn as_ref(&self) -> &Name {
        unsafe {
            debug_assert!(
                Name::from_str(self.as_str()).is_ok(),
                "An NCName is also a Name"
            );
            Name::new_unchecked(self.as_str())
        }
    }
}

impl AsRef<Qname> for Ncname {
    #[inline]
    fn as_ref(&self) -> &Qname {
        unsafe {
            debug_assert!(
                Qname::from_str(self.as_str()).is_ok(),
                "An NCName is also a Qname"
            );
            Qname::new_unchecked(self.as_str())
        }
    }
}

impl<'a> TryFrom<&'a str> for &'a Ncname {
    type Error = NameError;

    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
        Ncname::validate(s)?;
        Ok(unsafe {
            // This is safe because the string is validated.
            Ncname::new_unchecked(s)
        })
    }
}

impl<'a> TryFrom<&'a Name> for &'a Ncname {
    type Error = NameError;

    fn try_from(s: &'a Name) -> Result<Self, Self::Error> {
        if let Some(colon_pos) = s.as_str().find(':') {
            return Err(NameError::new(TargetNameType::Ncname, colon_pos));
        }

        unsafe {
            debug_assert!(
                Ncname::validate(s.as_str()).is_ok(),
                "Name {:?} without colons is also a valid NCName",
                s.as_str()
            );
            Ok(Ncname::new_unchecked(s.as_str()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ensure_eq(s: &str) {
        assert_eq!(
            Ncname::from_str(s).expect("Should not fail"),
            s,
            "String: {:?}",
            s
        );
    }

    fn ensure_error_at(s: &str, valid_up_to: usize) {
        let err = Ncname::from_str(s).expect_err("Should fail");
        assert_eq!(err.valid_up_to(), valid_up_to, "String: {:?}", s);
    }

    #[test]
    fn ncname_str_valid() {
        ensure_eq("hello");
        ensure_eq("abc123");
    }

    #[test]
    fn ncname_str_invalid() {
        ensure_error_at("", 0);
        ensure_error_at("-foo", 0);
        ensure_error_at("0foo", 0);
        ensure_error_at("foo bar", 3);
        ensure_error_at("foo/bar", 3);

        ensure_error_at("foo:bar", 3);
        ensure_error_at(":foo", 0);
        ensure_error_at("foo:", 3);
    }
}