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
346
347
348
349
350
351
//! # Just a tag
//!
//! This crate contains the [`Tag`] type, an [RFC 1035](https://datatracker.ietf.org/doc/html/rfc1035)
//! DNS label compatible string, with parsing [`FromStr`] and optional [serde](https://serde.rs/) support.
//!
//! ## Tag examples
//!
//! ```
//! # use just_a_tag::Tag;
//! assert_eq!(Tag::new("some-tag"), "some-tag");
//! assert_eq!(Tag::from_str("some-tag").unwrap(), "some-tag");
//! assert!(Tag::from_str("invalid-").is_err());
//! ```
//!
//! ## Unions of tags
//!
//! A bit untrue to the crate's name, it also provides the [`TagUnion`] type, which represents
//! (unsurprisingly, this time) a union of tags.
//!
//! ```
//! use std::collections::HashSet;
//! use just_a_tag::{MatchesAnyTagUnion, Tag, TagUnion};
//!
//! let union = TagUnion::from_str("foo").unwrap();
//! assert!(union.contains(&Tag::new("foo")));
//! assert_eq!(union.len(), 1);
//!
//! let union = TagUnion::from_str("foo+bar").unwrap();
//! assert!(union.contains(&Tag::new("foo")));
//! assert!(union.contains(&Tag::new("bar")));
//! assert_eq!(union.len(), 2);
//!
//! // TagUnions are particularly interesting when bundled up.
//! let unions = vec![
//!     TagUnion::from_str("bar+baz").unwrap(),
//!     TagUnion::from_str("foo").unwrap()
//! ];
//!
//! // foo matches
//! let set_1 = HashSet::from_iter([Tag::new("foo"), Tag::new("bar")]);
//! assert!(unions.matches_set(&set_1));
//!
//! // bar+baz matches
//! let set_2 = HashSet::from_iter([Tag::new("fubar"), Tag::new("bar"), Tag::new("baz")]);
//! assert!(unions.matches_set(&set_2));
//!
//! // none match
//! let set_3 = HashSet::from_iter([Tag::new("fubar"), Tag::new("bar")]);
//! assert!(!unions.matches_set(&set_3));
//! ```

// SPDX-FileCopyrightText: Copyright 2023 Markus Mayer
// SPDX-License-Identifier: EUPL-1.2
// SPDX-FileType: SOURCE

// Only enable the `doc_cfg` feature when the `docsrs` configuration attribute is defined.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(feature = "unsafe", allow(unsafe_code))]
#![cfg_attr(not(feature = "unsafe"), forbid(unsafe_code))]

mod tag_union;

#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::str::FromStr;

pub use tag_union::{MatchesAnyTagUnion, TagUnion, TagUnionFromStringError};

/// A tag name.
///
/// Tag names [RFC 1035](https://datatracker.ietf.org/doc/html/rfc1035) DNS label compatible,
/// in other words they must
///
/// - not be longer than 63 characters,,
/// - only lowercase alphanumeric characters or '-',
/// - start with an alphabetic character, and
/// - end with an alphanumeric character.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Tag(String);

impl Tag {
    /// An empty tag.
    pub const EMPTY: Tag = Tag(String::new());

    /// The maximum length of a tag.
    pub const MAX_LEN: usize = 63;

    /// Constructs a new tag.
    ///
    /// ## Panics
    ///
    /// This method panics if the input is not a valid tag. If you want to avoid a panic,
    /// use [`Tag::from_str`](Self::from_str) instead.
    ///
    /// ## Example
    ///
    /// ```
    /// use just_a_tag::Tag;
    /// assert_eq!(Tag::new("foo"), "foo");
    /// ```
    pub fn new<V: AsRef<str>>(value: V) -> Self {
        value.as_ref().parse().expect("invalid input")
    }

    /// Constructs a new tag without checking for validity.
    ///
    /// ## Example
    ///
    /// ```
    /// # use just_a_tag::Tag;
    /// /// // Constructs a Tag without verifying the input.
    /// assert_eq!(unsafe { Tag::new_unchecked("foo") }, "foo");
    /// assert_eq!(unsafe { Tag::new_unchecked("@") }, "@"); // NOTE: invalid input
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "unsafe")))]
    #[cfg(feature = "unsafe")]
    pub unsafe fn new_unchecked<V: Into<String>>(value: V) -> Self {
        Self(value.into())
    }

    /// Parses a [`Tag`] from a string-like value.
    ///
    /// ```
    /// # use just_a_tag::Tag;
    /// assert_eq!(Tag::from_str("some-tag").unwrap(), "some-tag");
    /// assert!(Tag::from_str("invalid-").is_err());
    /// ```
    pub fn from_str<S: AsRef<str>>(value: S) -> Result<Self, TagFromStringError> {
        let value = value.as_ref();
        if value.is_empty() {
            return Ok(Tag::EMPTY.clone());
        }

        if value.len() > Tag::MAX_LEN {
            return Err(TagFromStringError::LimitExceeded(value.len()));
        }

        let mut chars = value.chars();
        let first = chars.next().expect("tag is not empty");
        if !first.is_ascii_lowercase() {
            return Err(TagFromStringError::MustStartAlphabetic(first));
        }

        let mut previous = first;
        while let Some(c) = chars.next() {
            if !c.is_ascii_digit() && !c.is_ascii_lowercase() && c != '-' {
                return Err(TagFromStringError::InvalidCharacter(c));
            }

            previous = c;
        }

        if !previous.is_ascii_lowercase() {
            return Err(TagFromStringError::MustEndAlphanumeric(previous));
        }

        Ok(Self(value.into()))
    }
}

impl Display for Tag {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Deref for Tag {
    type Target = str;

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

impl PartialEq<str> for Tag {
    #[inline(always)]
    fn eq(&self, other: &str) -> bool {
        self.0.eq(other)
    }
}

impl PartialEq<&str> for Tag {
    #[inline(always)]
    fn eq(&self, other: &&str) -> bool {
        self.0.eq(other)
    }
}

impl FromStr for Tag {
    type Err = TagFromStringError;

    #[inline(always)]
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Tag::from_str(value)
    }
}

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

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl TryFrom<String> for Tag {
    type Error = TagFromStringError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl TryFrom<&String> for Tag {
    type Error = TagFromStringError;

    fn try_from(value: &String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Tag {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let tag = String::deserialize(deserializer)?;
        match Tag::from_str(&tag) {
            Ok(tag) => Ok(tag),
            Err(e) => Err(de::Error::custom(e)),
        }
    }
}

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

#[derive(Debug, Eq, PartialEq)]
pub enum TagFromStringError {
    MustStartAlphabetic(char),
    MustEndAlphanumeric(char),
    InvalidCharacter(char),
    LimitExceeded(usize),
}

impl Display for TagFromStringError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            TagFromStringError::MustStartAlphabetic(c) => write!(
                f,
                "Tag name must begin with a lowercase alphabetic character, got '{c}'"
            ),
            TagFromStringError::MustEndAlphanumeric(c) => write!(
                f,
                "Tag name must end with a lowercase alphanumeric character, got '{c}'"
            ),
            TagFromStringError::InvalidCharacter(c) => write!(
                f,
                "Tag name must only contain lowercase alphanumeric characters or '-', got '{c}'"
            ),
            TagFromStringError::LimitExceeded(len) => write!(
                f,
                "Tag name must be not longer than 63 characters, got '{len}'"
            ),
        }
    }
}

impl Error for TagFromStringError {}

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

    #[test]
    fn test_trivial() {
        assert_eq!(Tag::from_str("test").unwrap(), "test");
        assert_eq!(Tag::from_str("test-case").unwrap(), "test-case");
        assert_eq!(Tag::from_str("test---12e").unwrap(), "test---12e");
        assert!(
            Tag::from_str("a123456789a123456789a123456789a123456789a123456789a12345678901a")
                .is_ok()
        );
    }

    #[test]
    fn test_invalid() {
        assert!(Tag::from_str("1").is_err());
        assert!(Tag::from_str("-").is_err());
        assert!(Tag::from_str("a-").is_err());
        assert!(Tag::from_str("a1").is_err());
        assert!(Tag::from_str("a_b_c").is_err());
        assert!(
            Tag::from_str("a123456789a123456789a123456789a123456789a123456789a123456789012a")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_de_trivial() {
        assert_eq!(serde_json::from_str::<Tag>(r#""test""#).unwrap(), "test");
        assert_eq!(
            serde_json::from_str::<Tag>(r#""test-case""#).unwrap(),
            "test-case"
        );
        assert_eq!(
            serde_json::from_str::<Tag>(r#""test---12e""#).unwrap(),
            "test---12e"
        );
        assert!(serde_json::from_str::<Tag>(
            r#""a123456789a123456789a123456789a123456789a123456789a12345678901a""#
        )
        .is_ok());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_de_invalid() {
        assert!(serde_json::from_str::<Tag>(r#""1""#).is_err());
        assert!(serde_json::from_str::<Tag>(r#""-""#).is_err());
        assert!(serde_json::from_str::<Tag>(r#""a-""#).is_err());
        assert!(serde_json::from_str::<Tag>(r#""a1""#).is_err());
        assert!(serde_json::from_str::<Tag>(r#""a_b_c""#).is_err());
        assert!(serde_json::from_str::<Tag>(
            r#""a123456789a123456789a123456789a123456789a123456789a123456789012a""#
        )
        .is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serde_ser_invalid() {
        let json = serde_json::to_string(&Tag::new("foo")).unwrap();
        assert_eq!(json, r#""foo""#);
    }
}