hcl_primitives/
ident.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//! Construct and validate HCL identifiers.

use crate::{Error, InternalString};
use alloc::borrow::{Borrow, Cow};
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::String;
use core::fmt;
use core::ops;
use core::str::FromStr;

/// Represents an HCL identifier.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Ident(InternalString);

impl Ident {
    /// Create a new `Ident` after validating that it only contains characters that are allowed in
    /// HCL identifiers.
    ///
    /// See [`Ident::try_new`] for a fallible alternative to this function.
    ///
    /// # Example
    ///
    /// ```
    /// # use hcl_primitives::Ident;
    /// assert_eq!(Ident::new("some_ident").as_str(), "some_ident");
    /// ```
    ///
    /// # Panics
    ///
    /// This function panics if `ident` contains characters that are not allowed in HCL identifiers
    /// or if it is empty.
    pub fn new<T>(ident: T) -> Ident
    where
        T: Into<InternalString>,
    {
        let ident = ident.into();

        assert!(is_ident(&ident), "invalid identifier `{ident}`");

        Ident(ident)
    }

    /// Create a new `Ident` after validating that it only contains characters that are allowed in
    /// HCL identifiers.
    ///
    /// In contrast to [`Ident::new`], this function returns an error instead of panicking when an
    /// invalid identifier is encountered.
    ///
    /// See [`Ident::new_sanitized`] for an infallible alternative to this function.
    ///
    /// # Example
    ///
    /// ```
    /// # use hcl_primitives::Ident;
    /// assert!(Ident::try_new("some_ident").is_ok());
    /// assert!(Ident::try_new("").is_err());
    /// assert!(Ident::try_new("1two3").is_err());
    /// assert!(Ident::try_new("with whitespace").is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// If `ident` contains characters that are not allowed in HCL identifiers or if it is empty an
    /// error will be returned.
    pub fn try_new<T>(ident: T) -> Result<Ident, Error>
    where
        T: Into<InternalString>,
    {
        let ident = ident.into();

        if !is_ident(&ident) {
            return Err(Error::new(format!("invalid identifier `{ident}`")));
        }

        Ok(Ident(ident))
    }

    /// Create a new `Ident` after sanitizing the input if necessary.
    ///
    /// If `ident` contains characters that are not allowed in HCL identifiers will be sanitized
    /// according to the following rules:
    ///
    /// - An empty `ident` results in an identifier containing a single underscore.
    /// - Invalid characters in `ident` will be replaced with underscores.
    /// - If `ident` starts with a character that is invalid in the first position but would be
    ///   valid in the rest of an HCL identifier it is prefixed with an underscore.
    ///
    /// See [`Ident::try_new`] for a fallible alternative to this function if you prefer rejecting
    /// invalid identifiers instead of sanitizing them.
    ///
    /// # Example
    ///
    /// ```
    /// # use hcl_primitives::Ident;
    /// assert_eq!(Ident::new_sanitized("some_ident").as_str(), "some_ident");
    /// assert_eq!(Ident::new_sanitized("").as_str(), "_");
    /// assert_eq!(Ident::new_sanitized("1two3").as_str(), "_1two3");
    /// assert_eq!(Ident::new_sanitized("with whitespace").as_str(), "with_whitespace");
    /// ```
    pub fn new_sanitized<T>(ident: T) -> Self
    where
        T: AsRef<str>,
    {
        let input = ident.as_ref();

        if input.is_empty() {
            return Ident(InternalString::from("_"));
        }

        let mut ident = String::with_capacity(input.len());

        for (i, ch) in input.chars().enumerate() {
            if i == 0 && is_id_start(ch) {
                ident.push(ch);
            } else if is_id_continue(ch) {
                if i == 0 {
                    ident.push('_');
                }
                ident.push(ch);
            } else {
                ident.push('_');
            }
        }

        Ident(InternalString::from(ident))
    }

    /// Create a new `Ident` without checking if it is valid.
    ///
    /// It is the caller's responsibility to ensure that the identifier is valid.
    ///
    /// For most use cases [`Ident::new`], [`Ident::try_new`] or [`Ident::new_sanitized`] should be
    /// preferred.
    ///
    /// This function is not marked as unsafe because it does not cause undefined behaviour.
    /// However, attempting to serialize an invalid identifier to HCL will produce invalid output.
    #[inline]
    pub fn new_unchecked<T>(ident: T) -> Self
    where
        T: Into<InternalString>,
    {
        Ident(ident.into())
    }

    /// Converts the `Ident` to a mutable string type.
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.0.into_string()
    }

    /// Return a reference to the wrapped `str`.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl TryFrom<InternalString> for Ident {
    type Error = Error;

    #[inline]
    fn try_from(s: InternalString) -> Result<Self, Self::Error> {
        Ident::try_new(s)
    }
}

impl TryFrom<String> for Ident {
    type Error = Error;

    #[inline]
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Ident::try_new(s)
    }
}

impl TryFrom<&str> for Ident {
    type Error = Error;

    #[inline]
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Ident::try_new(s)
    }
}

impl<'a> TryFrom<Cow<'a, str>> for Ident {
    type Error = Error;

    #[inline]
    fn try_from(s: Cow<'a, str>) -> Result<Self, Self::Error> {
        Ident::try_new(s)
    }
}

impl FromStr for Ident {
    type Err = Error;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ident::try_new(s)
    }
}

impl From<Ident> for InternalString {
    #[inline]
    fn from(ident: Ident) -> Self {
        ident.0
    }
}

impl From<Ident> for String {
    #[inline]
    fn from(ident: Ident) -> Self {
        ident.into_string()
    }
}

impl fmt::Debug for Ident {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Ident({self})")
    }
}

impl fmt::Display for Ident {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl ops::Deref for Ident {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl AsRef<str> for Ident {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Ident {
    #[inline]
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Ident {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ident {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let string = InternalString::deserialize(deserializer)?;
        Ident::try_new(string).map_err(serde::de::Error::custom)
    }
}

/// Determines if `ch` is a valid HCL identifier start character.
///
/// # Example
///
/// ```
/// # use hcl_primitives::ident::is_id_start;
/// assert!(is_id_start('_'));
/// assert!(is_id_start('a'));
/// assert!(!is_id_start('-'));
/// assert!(!is_id_start('1'));
/// assert!(!is_id_start(' '));
/// ```
#[inline]
pub fn is_id_start(ch: char) -> bool {
    unicode_ident::is_xid_start(ch) || ch == '_'
}

/// Determines if `ch` is a valid HCL identifier continue character.
///
/// # Example
///
/// ```
/// # use hcl_primitives::ident::is_id_continue;
/// assert!(is_id_continue('-'));
/// assert!(is_id_continue('_'));
/// assert!(is_id_continue('a'));
/// assert!(is_id_continue('1'));
/// assert!(!is_id_continue(' '));
/// ```
#[inline]
pub fn is_id_continue(ch: char) -> bool {
    unicode_ident::is_xid_continue(ch) || ch == '-'
}

/// Determines if `s` represents a valid HCL identifier.
///
/// A string is a valid HCL identifier if:
///
/// - [`is_id_start`] returns `true` for the first character, and
/// - [`is_id_continue`] returns `true` for all remaining chacters
///
/// # Example
///
/// ```
/// # use hcl_primitives::ident::is_ident;
/// assert!(!is_ident(""));
/// assert!(!is_ident("-foo"));
/// assert!(!is_ident("123foo"));
/// assert!(!is_ident("foo bar"));
/// assert!(is_ident("fööbär"));
/// assert!(is_ident("foobar123"));
/// assert!(is_ident("FOO-bar123"));
/// assert!(is_ident("foo_BAR123"));
/// assert!(is_ident("_foo"));
/// assert!(is_ident("_123"));
/// assert!(is_ident("foo_"));
/// assert!(is_ident("foo-"));
/// ```
#[inline]
pub fn is_ident(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    let mut chars = s.chars();
    let first = chars.next().unwrap();

    is_id_start(first) && chars.all(is_id_continue)
}