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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use core::fmt;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;

use crate::{Error, Pattern, Patterns, PatternsBuilderConfigured};

/// Compile time configuration for a [`TypedPattern`].
pub trait PatternConfig {
    /// Configures the pattern to match case insensitive.
    const CASE_INSENSITIVE: bool = false;
    /// Configures the maximum allowed complexity of the pattern.
    const MAX_COMPLEXITY: u64 = u64::MAX;
}

/// The default pattern.
///
/// Equivalent to [`Pattern::new`].
pub struct DefaultPatternConfig;

impl PatternConfig for DefaultPatternConfig {}

/// The default pattern but with case insensitive matching.
///
/// See: [`crate::PatternBuilder::case_insensitive`].
pub struct CaseInsensitive;

impl PatternConfig for CaseInsensitive {
    const CASE_INSENSITIVE: bool = true;
}

/// A [`Pattern`] with compile time encoded [`PatternConfig`].
///
/// Encoding the pattern configuration allows context dependent serialization
/// and usage of patterns and ensures a consistent usage of configuration options
/// throught the code.
///
/// Often repeated configuration can be grouped into custom and importable configurations.
///
/// ```
/// struct MetricConfig;
///
/// impl relay_pattern::PatternConfig for MetricConfig {
///     const CASE_INSENSITIVE: bool = false;
///     // More configuration ...
/// }
///
/// type MetricPattern = relay_pattern::TypedPattern<MetricConfig>;
///
/// let pattern = MetricPattern::new("[cd]:foo/bar").unwrap();
/// assert!(pattern.is_match("c:foo/bar"));
/// ```
#[derive(Debug)]
pub struct TypedPattern<C = DefaultPatternConfig> {
    pattern: Pattern,
    _phantom: PhantomData<C>,
}

impl<C: PatternConfig> TypedPattern<C> {
    /// Creates a new [`TypedPattern`] using the provided pattern and config `C`.
    ///
    /// ```
    /// use relay_pattern::{Pattern, TypedPattern, CaseInsensitive};
    ///
    /// let pattern = TypedPattern::<CaseInsensitive>::new("foo*").unwrap();
    /// assert!(pattern.is_match("FOOBAR"));
    ///
    /// // Equivalent to:
    /// let pattern = Pattern::builder("foo*").case_insensitive(true).build().unwrap();
    /// assert!(pattern.is_match("FOOBAR"));
    /// ```
    pub fn new(pattern: &str) -> Result<Self, Error> {
        Pattern::builder(pattern)
            .case_insensitive(C::CASE_INSENSITIVE)
            .max_complexity(C::MAX_COMPLEXITY)
            .build()
            .map(|pattern| Self {
                pattern,
                _phantom: PhantomData,
            })
    }
}

#[cfg(feature = "serde")]
impl<'de, C: PatternConfig> serde::Deserialize<'de> for TypedPattern<C> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let pattern = <std::borrow::Cow<'_, str>>::deserialize(deserializer)?;
        Self::new(&pattern).map_err(serde::de::Error::custom)
    }
}

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

impl<C> From<TypedPattern<C>> for Pattern {
    fn from(value: TypedPattern<C>) -> Self {
        value.pattern
    }
}

impl<C> AsRef<Pattern> for TypedPattern<C> {
    fn as_ref(&self) -> &Pattern {
        &self.pattern
    }
}

impl<C> Deref for TypedPattern<C> {
    type Target = Pattern;

    fn deref(&self) -> &Self::Target {
        &self.pattern
    }
}

/// [`Patterns`] with a compile time configured [`PatternConfig`].
pub struct TypedPatterns<C = DefaultPatternConfig> {
    patterns: Patterns,
    raw: Vec<String>,
    _phantom: PhantomData<C>,
}

impl<C: PatternConfig> TypedPatterns<C> {
    pub fn builder() -> TypedPatternsBuilder<C> {
        let builder = Patterns::builder()
            .case_insensitive(C::CASE_INSENSITIVE)
            .patterns();

        TypedPatternsBuilder {
            builder,
            raw: Vec::new(),
            _phantom: PhantomData,
        }
    }
}

impl<C: PatternConfig> Default for TypedPatterns<C> {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl<C> PartialEq for TypedPatterns<C> {
    fn eq(&self, other: &Self) -> bool {
        self.raw.eq(&other.raw)
    }
}

impl<C: PatternConfig> From<String> for TypedPatterns<C> {
    fn from(value: String) -> Self {
        [value].into_iter().collect()
    }
}

impl<C: PatternConfig> From<Vec<String>> for TypedPatterns<C> {
    fn from(value: Vec<String>) -> Self {
        value.into_iter().collect()
    }
}

impl<C: PatternConfig, const N: usize> From<[String; N]> for TypedPatterns<C> {
    fn from(value: [String; N]) -> Self {
        value.into_iter().collect()
    }
}

/// Creates [`Patterns`] from an iterator of strings.
///
/// Invalid patterns are ignored.
impl<C: PatternConfig> FromIterator<String> for TypedPatterns<C> {
    fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
        let mut builder = Self::builder();
        for pattern in iter.into_iter() {
            let _err = builder.add(pattern);
            #[cfg(debug_assertions)]
            _err.expect("all patterns should be valid patterns");
        }
        builder.build()
    }
}

impl<C> From<TypedPatterns<C>> for Patterns {
    fn from(value: TypedPatterns<C>) -> Self {
        value.patterns
    }
}

impl<C> AsRef<Patterns> for TypedPatterns<C> {
    fn as_ref(&self) -> &Patterns {
        &self.patterns
    }
}

impl<C> Deref for TypedPatterns<C> {
    type Target = Patterns;

    fn deref(&self) -> &Self::Target {
        &self.patterns
    }
}

impl<C> Clone for TypedPatterns<C> {
    fn clone(&self) -> Self {
        Self {
            patterns: self.patterns.clone(),
            raw: self.raw.clone(),
            _phantom: PhantomData,
        }
    }
}

impl<C> fmt::Debug for TypedPatterns<C> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.raw.fmt(f)
    }
}

/// Deserializes patterns from a sequence of strings.
///
/// Invalid patterns are ignored while deserializing.
#[cfg(feature = "serde")]
impl<'de, C: PatternConfig> serde::Deserialize<'de> for TypedPatterns<C> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor<C>(PhantomData<C>);

        impl<'a, C: PatternConfig> serde::de::Visitor<'a> for Visitor<C> {
            type Value = TypedPatterns<C>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a sequence of patterns")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'a>,
            {
                let mut builder = TypedPatterns::<C>::builder();

                while let Some(item) = seq.next_element()? {
                    // Ignore invalid patterns as documented.
                    let _err = builder.add(item);
                    #[cfg(debug_assertions)]
                    _err.expect("all patterns should be valid patterns");
                }

                Ok(builder.build())
            }
        }

        deserializer.deserialize_seq(Visitor(PhantomData))
    }
}

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

pub struct TypedPatternsBuilder<C> {
    builder: PatternsBuilderConfigured,
    raw: Vec<String>,
    _phantom: PhantomData<C>,
}

impl<C: PatternConfig> TypedPatternsBuilder<C> {
    /// Adds a pattern to the builder.
    pub fn add(&mut self, pattern: String) -> Result<&mut Self, Error> {
        self.builder.add(&pattern)?;
        self.raw.push(pattern);
        Ok(self)
    }

    /// Builds a [`TypedPatterns`] from the contained patterns.
    pub fn build(self) -> TypedPatterns<C> {
        TypedPatterns {
            patterns: self.builder.build(),
            raw: self.raw,
            _phantom: PhantomData,
        }
    }

    /// Builds a [`TypedPatterns`] from the contained patterns and clears the builder.
    pub fn take(&mut self) -> TypedPatterns<C> {
        TypedPatterns {
            patterns: self.builder.take(),
            raw: std::mem::take(&mut self.raw),
            _phantom: PhantomData,
        }
    }
}

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

    #[test]
    fn test_default() {
        let pattern: TypedPattern = TypedPattern::new("*[rt]x").unwrap();
        assert!(pattern.is_match("f/o_rx"));
        assert!(pattern.is_match("f/o_tx"));
        assert!(pattern.is_match("F/o_tx"));
        // case sensitive
        assert!(!pattern.is_match("f/o_Tx"));
        assert!(!pattern.is_match("f/o_rX"));
    }

    #[test]
    fn test_case_insensitive() {
        let pattern: TypedPattern<CaseInsensitive> = TypedPattern::new("*[rt]x").unwrap();
        // case insensitive
        assert!(pattern.is_match("f/o_Tx"));
        assert!(pattern.is_match("f/o_rX"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_deserialize() {
        let pattern: TypedPattern<CaseInsensitive> = serde_json::from_str(r#""*[rt]x""#).unwrap();
        assert!(pattern.is_match("foobar_rx"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_deserialize_err() {
        let r: Result<TypedPattern<CaseInsensitive>, _> = serde_json::from_str(r#""[invalid""#);
        assert!(r.is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_deserialize_complexity() {
        struct Test;
        impl PatternConfig for Test {
            const MAX_COMPLEXITY: u64 = 2;
        }
        let r: Result<TypedPattern<Test>, _> = serde_json::from_str(r#""{foo,bar}""#);
        assert!(r.is_ok());
        let r: Result<TypedPattern<Test>, _> = serde_json::from_str(r#""{foo,bar,baz}""#);
        assert!(r.is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_serialize() {
        let pattern: TypedPattern = TypedPattern::new("*[rt]x").unwrap();
        assert_eq!(serde_json::to_string(&pattern).unwrap(), r#""*[rt]x""#);
        let pattern: TypedPattern<CaseInsensitive> = TypedPattern::new("*[rt]x").unwrap();
        assert_eq!(serde_json::to_string(&pattern).unwrap(), r#""*[rt]x""#);
    }

    #[test]
    fn test_patterns_default() {
        let patterns: TypedPatterns = TypedPatterns::builder()
            .add("*[rt]x".to_owned())
            .unwrap()
            .add("foobar".to_owned())
            .unwrap()
            .take();
        assert!(patterns.is_match("f/o_rx"));
        assert!(patterns.is_match("foobar"));
        assert!(!patterns.is_match("Foobar"));
    }

    #[test]
    fn test_patterns_case_insensitive() {
        let patterns: TypedPatterns<CaseInsensitive> = TypedPatterns::builder()
            .add("*[rt]x".to_owned())
            .unwrap()
            .add("foobar".to_owned())
            .unwrap()
            .take();
        assert!(patterns.is_match("f/o_rx"));
        assert!(patterns.is_match("f/o_Rx"));
        assert!(patterns.is_match("foobar"));
        assert!(patterns.is_match("Foobar"));
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_patterns_deserialize() {
        let pattern: TypedPatterns<CaseInsensitive> =
            serde_json::from_str(r#"["*[rt]x","foobar"]"#).unwrap();
        assert!(pattern.is_match("foobar_rx"));
        assert!(pattern.is_match("FOOBAR"));
    }

    #[test]
    #[cfg(all(feature = "serde", not(debug_assertions)))]
    fn test_patterns_deserialize_err() {
        let r: TypedPatterns<CaseInsensitive> =
            serde_json::from_str(r#"["[invalid","foobar"]"#).unwrap();
        assert!(r.is_match("foobar"));
        assert!(r.is_match("FOOBAR"));

        // The invalid element is dropped.
        assert_eq!(serde_json::to_string(&r).unwrap(), r#"["foobar"]"#);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn test_patterns_serialize() {
        let pattern: TypedPatterns = TypedPatterns::builder()
            .add("*[rt]x".to_owned())
            .unwrap()
            .add("foobar".to_owned())
            .unwrap()
            .take();
        assert_eq!(
            serde_json::to_string(&pattern).unwrap(),
            r#"["*[rt]x","foobar"]"#
        );

        let pattern: TypedPatterns<CaseInsensitive> = TypedPatterns::builder()
            .add("*[rt]x".to_owned())
            .unwrap()
            .add("foobar".to_owned())
            .unwrap()
            .take();
        assert_eq!(
            serde_json::to_string(&pattern).unwrap(),
            r#"["*[rt]x","foobar"]"#
        );
    }
}