match-domain 0.1.3

Rapid checker for the prefix and suffix matching of domain names
Documentation
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! # match-domain: Rapid checker for prefix and suffix matching of domain names
//!
//! This crate provides a high-performance domain name matching library using double-array trie
//! data structures. It enables you to efficiently check if a given domain name matches against
//! a collection of prefix or suffix patterns.
//!
//! ## Key Features
//!
//! - **Fast matching**: Uses double-array trie (Cedar) for O(m) lookup performance, where m is the length of the given domain to be matched,
//!   independent of the number of patterns
//! - **Flexible patterns**: Supports both prefix (`www.example.*`) and suffix (`*.example.com`) matching
//! - **Multiple match types**: Simple boolean matching, all matches, and longest match queries
//! - **Memory efficient**: Compact representation using trie data structures
//! - **Thread safe**: All operations are read-only after initialization
//!
//! ## Supported Pattern Types
//!
//! - **Exact domain**: `example.com` matches exactly `example.com`
//! - **Suffix wildcard**: `*.example.com` matches `api.example.com`, `www.example.com`, etc.
//! - **Prefix wildcard**: `www.example.*` matches `www.example.com`, `www.example.org`, etc.
//!
//! ## Quick Start
//!
//! ```rust
//! use match_domain::DomainMatchingRule;
//!
//! // Create a domain matching rule from a list of patterns
//! let rule = DomainMatchingRule::try_from(vec![
//!     "*.google.com",      // Suffix pattern
//!     "www.example.*",     // Prefix pattern
//!     "exact.domain.net",  // Exact match
//! ]).unwrap();
//!
//! // Check if a domain matches any pattern
//! assert!(rule.is_matched("api.google.com"));        // Matches *.google.com
//! assert!(rule.is_matched("www.example.org"));       // Matches www.example.*
//! assert!(rule.is_matched("exact.domain.net"));      // Exact match
//! assert!(!rule.is_matched("unmatched.domain.com")); // No match
//! ```
//!
//! ## Advanced Usage
//!
//! ### Finding All Matches
//!
//! ```rust
//! use match_domain::DomainMatchingRule;
//!
//! let rule = DomainMatchingRule::try_from(vec![
//!     "google.com",
//!     "*.google.com",
//!     "com",
//! ]).unwrap();
//!
//! // Get all matching suffixes (returns reversed strings)
//! let matches = rule.find_suffix_match_all("api.google.com");
//! assert_eq!(matches.len(), 2); // Matches both "google.com" and "com"
//! ```
//!
//! ### Finding Longest Match
//!
//! ```rust
//! use match_domain::DomainMatchingRule;
//!
//! let rule = DomainMatchingRule::try_from(vec![
//!     "www.example.*",
//!     "www.*",
//! ]).unwrap();
//!
//! // Get the most specific (longest) matching prefix
//! let longest = rule.find_prefix_match_longest("www.example.com");
//! assert_eq!(longest, Some("www.example".to_string())); // More specific than "www"
//! ```
//!
//! ## Important Notes
//!
//! - Domain names must be provided in lowercase
//! - Domain names should not contain leading dots
//! - Suffix matching returns reversed strings for internal efficiency
//! - The crate is thread-safe after initialization

use cedarwood::Cedar;
use regex::Regex;

/* --------------------------------------------------------------------- */
/// Describes things that can go wrong in the match-domain
#[derive(Debug, thiserror::Error)]
pub enum Error {
  /// Failed to compile a regular expression
  #[error(transparent)]
  RegexError(#[from] regex::Error),
}

/* --------------------------------------------------------------------- */
/// Regular expression for domain or prefix
pub const REGEXP_DOMAIN_OR_PREFIX: &str = r"^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*\.)+([a-zA-Z]{2,}|\*)";

/// Reverse a string
fn reverse_string(text: &str) -> String {
  text.chars().rev().collect::<String>()
}

/* --------------------------------------------------------------------- */
#[derive(Debug, Clone)]
/// A struct representing a prefix-or-suffix matching rule.
/// This struct checks if a domain is contained in a list of prefixes or suffixes with longest match rule.
pub struct DomainMatchingRule {
  /// Prefix Cedar
  prefix_cedar: Cedar,
  /// Suffix Cedar
  suffix_cedar: Cedar,
  /// Prefix dictionary
  prefix_dict: Vec<String>,
  /// Suffix dictionary
  suffix_dict: Vec<String>,
}

/* --------------------------------------------------------------------- */
impl TryFrom<Vec<&str>> for DomainMatchingRule {
  type Error = Error;

  /// Populate the domain matching rule from a list of domains
  fn try_from(domain_list: Vec<&str>) -> Result<Self, Self::Error> {
    DomainMatchingRule::try_from(domain_list.as_slice())
  }
}

impl TryFrom<Vec<String>> for DomainMatchingRule {
  type Error = Error;

  /// Populate the domain matching rule from a list of domains
  fn try_from(domain_list: Vec<String>) -> Result<Self, Self::Error> {
    let domain_list: Vec<&str> = domain_list.iter().map(AsRef::as_ref).collect();
    DomainMatchingRule::try_from(domain_list)
  }
}

impl TryFrom<&[String]> for DomainMatchingRule {
  type Error = Error;

  /// Populate the domain matching rule from a list of domains
  fn try_from(domain_list: &[String]) -> Result<Self, Self::Error> {
    let domain_list: Vec<&str> = domain_list.iter().map(AsRef::as_ref).collect();
    DomainMatchingRule::try_from(domain_list)
  }
}

impl TryFrom<&[&str]> for DomainMatchingRule {
  type Error = Error;

  /// Populate the domain matching rule from a list of domains
  fn try_from(domain_list: &[&str]) -> Result<Self, Self::Error> {
    let start_with_star = Regex::new(r"^\*\..+")?;
    let end_with_star = Regex::new(r".+\.\*$")?;
    // TODO: currently either one of prefix or suffix match with '*' is supported
    let re = Regex::new(&format!("{}{}{}", r"^", REGEXP_DOMAIN_OR_PREFIX, r"$"))?;
    let dict: Vec<String> = domain_list
      .iter()
      .map(|d| if start_with_star.is_match(d) { &d[2..] } else { d })
      .filter(|x| re.is_match(x) || (x.split('.').count() == 1))
      .map(|y| y.to_ascii_lowercase())
      .collect();
    let prefix_dict: Vec<String> = dict
      .iter()
      .filter(|d| end_with_star.is_match(d))
      .map(|d| d[..d.len() - 2].to_string())
      .collect();
    let suffix_dict: Vec<String> = dict
      .iter()
      .filter(|d| !end_with_star.is_match(d))
      .map(|d| reverse_string(d))
      .collect();

    let prefix_kv: Vec<(&str, i32)> = prefix_dict
      .iter()
      .map(AsRef::as_ref)
      .enumerate()
      .map(|(k, s)| (s, k as i32))
      .collect();
    let mut prefix_cedar = Cedar::new();
    prefix_cedar.build(&prefix_kv);

    let suffix_kv: Vec<(&str, i32)> = suffix_dict
      .iter()
      .map(AsRef::as_ref)
      .enumerate()
      .map(|(k, s)| (s, k as i32))
      .collect();
    let mut suffix_cedar = Cedar::new();
    suffix_cedar.build(&suffix_kv);

    Ok(DomainMatchingRule {
      prefix_cedar,
      suffix_cedar,
      prefix_dict,
      suffix_dict,
    })
  }
}

/* --------------------------------------------------------------------- */
#[inline]
/// Helper function to find the matched items in trie
fn find_match<'a>(name: &'a str, ceder: &'a Cedar, dict: &'a [String]) -> impl Iterator<Item = (String, usize)> + 'a {
  ceder
    .common_prefix_iter(name)
    .map(|(x, matched_prefix_len)| (dict[x as usize].clone(), matched_prefix_len))
}

#[inline]
/// Inner function for finding all matches, name is reversed for suffix matching
fn find_match_all_inner(name: &str, cedar: &Cedar, dict: &[String]) -> Vec<String> {
  let matched_items = find_match(name, &cedar, &dict);
  matched_items
    .filter_map(|(found, _)| {
      if is_matched_as_domain(&found, name) {
        Some(found)
      } else {
        None
      }
    })
    .collect()
}

#[inline]
/// Inner function for finding match, name is reversed for suffix matching
fn find_match_inner(name: &str, cedar: &Cedar, dict: &[String]) -> bool {
  let mut matched_items = find_match(name, &cedar, &dict);
  matched_items.any(|(found, _)| is_matched_as_domain(&found, name))
}

#[inline]
/// Inner function for finding match with longest match, name is reversed for suffix matching
fn find_match_longest_inner(name: &str, cedar: &Cedar, dict: &[String]) -> Option<String> {
  let matched_items = find_match(name, &cedar, &dict);
  let longest_matched_as_domain = matched_items
    .filter(|(found, _)| is_matched_as_domain(found, name))
    .max_by_key(|(_, len)| *len);
  longest_matched_as_domain.map(|(found, _)| found)
}

#[inline]
/// Check if the matched is a domain name
fn is_matched_as_domain(matched: &str, domain_name: &str) -> bool {
  if matched.len() == domain_name.len() {
    true
  } else if let Some(nth) = domain_name.chars().nth(matched.chars().count()) {
    nth.to_string() == "."
  } else {
    false
  }
}

/* --------------------------------------------------------------------- */
impl DomainMatchingRule {
  /// Find a domain contained in the list of suffixes.
  /// Returns true if found If not found, return false.
  /// Short-circuit evaluation, it immediately stops when the first match is found.
  pub fn find_suffix_match(&self, domain_name: &str) -> bool {
    let reverse_domain_name = reverse_string(domain_name);
    find_match_inner(&reverse_domain_name, &self.suffix_cedar, &self.suffix_dict)
  }

  /// Find a domain contained in the list of suffixes.
  /// Returns list of all matched suffixes.
  pub fn find_suffix_match_all(&self, domain_name: &str) -> Vec<String> {
    let reverse_domain_name = reverse_string(domain_name);
    find_match_all_inner(&reverse_domain_name, &self.suffix_cedar, &self.suffix_dict)
  }

  /// Find a domain contained in the list of suffixes.
  /// Returns the longest match. If not found, return None.
  pub fn find_suffix_match_longest(&self, domain_name: &str) -> Option<String> {
    let reverse_domain_name = reverse_string(domain_name);
    find_match_longest_inner(&reverse_domain_name, &self.suffix_cedar, &self.suffix_dict)
  }

  /// Find a domain contained in the list of prefixes.
  /// Returns true if found If not found, return false.
  /// Short-circuit evaluation, it immediately stops when the first match is found.
  pub fn find_prefix_match(&self, domain_name: &str) -> bool {
    find_match_inner(domain_name, &self.prefix_cedar, &self.prefix_dict)
  }

  /// Find a domain contained in the list of prefixes.
  /// Returns list of all matched prefixes.
  pub fn find_prefix_match_all(&self, domain_name: &str) -> Vec<String> {
    find_match_all_inner(domain_name, &self.prefix_cedar, &self.prefix_dict)
  }

  /// Find a domain contained in the list of prefixes.
  /// Returns the longest match. If not found, return None.
  pub fn find_prefix_match_longest(&self, domain_name: &str) -> Option<String> {
    find_match_longest_inner(domain_name, &self.prefix_cedar, &self.prefix_dict)
  }

  /// Check if a domain is contained in the list of prefixes or suffixes
  /// We should note that
  /// - the argument `domain_name` should be in lowercase
  /// - the argument `domain_name` should not contain a leading dot
  pub fn is_matched(&self, domain_name: &str) -> bool {
    if self.find_suffix_match(domain_name) {
      return true;
    }

    if self.find_prefix_match(domain_name) {
      return true;
    }

    // TODO: other matching patterns

    false
  }
}

/* --------------------------------------------------------------------- */

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

  #[test]
  fn matching_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "www.google.com".to_string(),
      "*.google.com".to_string(),
      "yahoo.co.*".to_string(),
    ])
    .unwrap();

    assert!(domain_matching_rule.is_matched("wwxx.google.com"));
    assert!(domain_matching_rule.is_matched("yahoo.co.jp"));

    assert!(!domain_matching_rule.is_matched("www.yahoo.com"));
    assert!(!domain_matching_rule.is_matched("www.yahoo.co.jp"));
  }

  #[test]
  fn matching_works_regardless_of_dns0x20() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec!["GOOGLE.com".to_string()]).unwrap();

    assert!(domain_matching_rule.is_matched("www.google.com"));

    // input domain name must be in lowercase
    assert!(domain_matching_rule.is_matched("WWW.gOoGlE.COM".to_ascii_lowercase().as_str()));
  }

  #[test]
  fn find_suffix_match_all_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "google.com".to_string(),
      "*.google.com".to_string(),
      "com".to_string(),
      "example.com".to_string(),
    ])
    .unwrap();

    // Test multiple matches for a subdomain
    let matches = domain_matching_rule.find_suffix_match_all("test.google.com");
    assert!(matches.contains(&"moc.elgoog".to_string())); // reversed "google.com"
    assert!(matches.contains(&"moc".to_string())); // reversed "com"
    assert_eq!(matches.len(), 2);

    // Test single match
    let matches = domain_matching_rule.find_suffix_match_all("example.com");
    assert!(matches.contains(&"moc.elpmaxe".to_string())); // reversed "example.com"
    assert!(matches.contains(&"moc".to_string())); // reversed "com"
    assert_eq!(matches.len(), 2);

    // Test no matches
    let matches = domain_matching_rule.find_suffix_match_all("yahoo.org");
    assert!(matches.is_empty());

    // Test exact match
    let matches = domain_matching_rule.find_suffix_match_all("google.com");
    assert!(matches.contains(&"moc.elgoog".to_string()));
    assert!(matches.contains(&"moc".to_string()));
    assert_eq!(matches.len(), 2);
  }

  #[test]
  fn find_suffix_match_longest_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "google.com".to_string(),
      "*.google.com".to_string(),
      "com".to_string(),
      "example.com".to_string(),
    ])
    .unwrap();

    // Test longest match for subdomain
    let longest = domain_matching_rule.find_suffix_match_longest("test.google.com");
    assert_eq!(longest, Some("moc.elgoog".to_string())); // "google.com" is longer than "com"

    // Test longest match for exact domain
    let longest = domain_matching_rule.find_suffix_match_longest("example.com");
    assert_eq!(longest, Some("moc.elpmaxe".to_string())); // "example.com" is longer than "com"

    // Test no match returns None
    let longest = domain_matching_rule.find_suffix_match_longest("yahoo.org");
    assert_eq!(longest, None);

    // Test single match
    let domain_matching_rule_single = DomainMatchingRule::try_from(vec!["test.org".to_string()]).unwrap();
    let longest = domain_matching_rule_single.find_suffix_match_longest("test.org");
    assert_eq!(longest, Some("gro.tset".to_string()));
  }

  #[test]
  fn find_suffix_match_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "google.com".to_string(),
      "*.google.com".to_string(),
      "example.org".to_string(),
    ])
    .unwrap();

    // Test suffix match
    assert!(domain_matching_rule.find_suffix_match("www.google.com"));
    assert!(domain_matching_rule.find_suffix_match("google.com"));
    assert!(domain_matching_rule.find_suffix_match("example.org"));

    // Test no match
    assert!(!domain_matching_rule.find_suffix_match("yahoo.com"));
    assert!(!domain_matching_rule.find_suffix_match("google.org"));
  }

  #[test]
  fn find_prefix_match_works() {
    let domain_matching_rule =
      DomainMatchingRule::try_from(vec!["www.example.*".to_string(), "blog.test.*".to_string()]).unwrap();

    // Test prefix match
    assert!(domain_matching_rule.find_prefix_match("www.example.com"));
    assert!(domain_matching_rule.find_prefix_match("www.example.org"));
    assert!(domain_matching_rule.find_prefix_match("blog.test.net"));

    // Test no match
    assert!(!domain_matching_rule.find_prefix_match("api.example.com"));
    assert!(!domain_matching_rule.find_prefix_match("www.google.com"));
    assert!(!domain_matching_rule.find_prefix_match("example.com"));
  }

  #[test]
  fn find_prefix_match_all_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "www.example.*".to_string(),
      "www.*".to_string(),
      "blog.test.*".to_string(),
      "example.*".to_string(),
    ])
    .unwrap();

    // Test multiple matches for a domain with overlapping prefixes
    let matches = domain_matching_rule.find_prefix_match_all("www.example.com");
    assert!(matches.contains(&"www.example".to_string()));
    assert!(matches.contains(&"www".to_string()));
    assert_eq!(matches.len(), 2);

    // Test single match
    let matches = domain_matching_rule.find_prefix_match_all("blog.test.net");
    assert!(matches.contains(&"blog.test".to_string()));
    assert_eq!(matches.len(), 1);

    // Test no matches
    let matches = domain_matching_rule.find_prefix_match_all("api.google.com");
    assert!(matches.is_empty());

    // Test exact match case
    let matches = domain_matching_rule.find_prefix_match_all("example.org");
    assert!(matches.contains(&"example".to_string()));
    assert_eq!(matches.len(), 1);

    // Test domain that matches multiple patterns
    let matches = domain_matching_rule.find_prefix_match_all("www.test.co.uk");
    assert!(matches.contains(&"www".to_string()));
    assert_eq!(matches.len(), 1);
  }

  #[test]
  fn find_prefix_match_longest_works() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "www.example.*".to_string(),
      "www.*".to_string(),
      "blog.test.*".to_string(),
      "example.*".to_string(),
    ])
    .unwrap();

    // Test longest match for domain with multiple prefix matches
    let longest = domain_matching_rule.find_prefix_match_longest("www.example.com");
    assert_eq!(longest, Some("www.example".to_string())); // "www.example" is longer than "www"

    // Test longest match for single match
    let longest = domain_matching_rule.find_prefix_match_longest("blog.test.net");
    assert_eq!(longest, Some("blog.test".to_string()));

    // Test no match returns None
    let longest = domain_matching_rule.find_prefix_match_longest("api.google.com");
    assert_eq!(longest, None);

    // Test single match
    let longest = domain_matching_rule.find_prefix_match_longest("example.org");
    assert_eq!(longest, Some("example".to_string()));

    // Test case where shorter prefix matches
    let longest = domain_matching_rule.find_prefix_match_longest("www.test.co.uk");
    assert_eq!(longest, Some("www".to_string()));
  }

  #[test]
  fn edge_cases_work() {
    let domain_matching_rule =
      DomainMatchingRule::try_from(vec!["a.com".to_string(), "*.b.com".to_string(), "c.*".to_string()]).unwrap();

    // Single character domain parts
    assert!(domain_matching_rule.find_suffix_match("a.com"));
    assert!(domain_matching_rule.find_suffix_match("x.b.com"));
    assert!(domain_matching_rule.find_prefix_match("c.org"));

    // Test with very short domains
    let short_domain_rule = DomainMatchingRule::try_from(vec!["co".to_string()]).unwrap();
    assert!(short_domain_rule.find_suffix_match("co"));

    // Test empty result cases
    let empty_matches = domain_matching_rule.find_suffix_match_all("nonexistent.domain");
    assert!(empty_matches.is_empty());

    let no_longest = domain_matching_rule.find_suffix_match_longest("nonexistent.domain");
    assert_eq!(no_longest, None);
  }

  #[test]
  fn mixed_prefix_suffix_patterns_work() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "*.google.com".to_string(),     // suffix pattern
      "www.example.*".to_string(),    // prefix pattern
      "exact.domain.net".to_string(), // exact suffix match
    ])
    .unwrap();

    // Test suffix patterns
    assert!(domain_matching_rule.is_matched("api.google.com"));
    assert!(domain_matching_rule.is_matched("mail.google.com"));
    assert!(domain_matching_rule.is_matched("exact.domain.net"));

    // Test prefix patterns
    assert!(domain_matching_rule.is_matched("www.example.com"));
    assert!(domain_matching_rule.is_matched("www.example.org"));

    // Test non-matches
    // Note: "google.com" should match because it's in the suffix dictionary from "*.google.com"
    assert!(domain_matching_rule.is_matched("google.com")); // This should actually match
    assert!(!domain_matching_rule.is_matched("example.com")); // This should not match without www prefix
    assert!(!domain_matching_rule.is_matched("api.example.com"));
  }

  #[test]
  fn debug_pattern_behavior() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec!["*.google.com".to_string()]).unwrap();

    // The pattern "*.google.com" should match both "subdomain.google.com" and "google.com"
    assert!(domain_matching_rule.is_matched("api.google.com"));
    assert!(domain_matching_rule.is_matched("google.com"));

    let domain_matching_rule2 = DomainMatchingRule::try_from(vec!["www.example.*".to_string()]).unwrap();

    // The pattern "www.example.*" should match "www.example.anything"
    assert!(domain_matching_rule2.is_matched("www.example.com"));
    assert!(!domain_matching_rule2.is_matched("example.com"));
    assert!(!domain_matching_rule2.is_matched("api.example.com"));
  }

  #[test]
  fn test_try_from_implementations() {
    let domains_vec_str = vec!["google.com", "*.example.com"];
    let rule1 = DomainMatchingRule::try_from(domains_vec_str).unwrap();
    assert!(rule1.is_matched("google.com"));
    assert!(rule1.is_matched("test.example.com"));

    let domains_vec_string = vec!["google.com".to_string(), "*.example.com".to_string()];
    let rule2 = DomainMatchingRule::try_from(domains_vec_string).unwrap();
    assert!(rule2.is_matched("google.com"));
    assert!(rule2.is_matched("test.example.com"));

    let domains_slice_string = vec!["google.com".to_string(), "*.example.com".to_string()];
    let rule3 = DomainMatchingRule::try_from(domains_slice_string.as_slice()).unwrap();
    assert!(rule3.is_matched("google.com"));
    assert!(rule3.is_matched("test.example.com"));

    let domains_slice_str: &[&str] = &["google.com", "*.example.com"];
    let rule4 = DomainMatchingRule::try_from(domains_slice_str).unwrap();
    assert!(rule4.is_matched("google.com"));
    assert!(rule4.is_matched("test.example.com"));
  }

  #[test]
  fn test_invalid_regex_patterns() {
    // Test with invalid domain patterns - they should be filtered out
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "valid.com".to_string(),
      "invalid..domain".to_string(), // double dots should be filtered
      "*.valid.org".to_string(),
    ])
    .unwrap();

    assert!(domain_matching_rule.is_matched("valid.com"));
    assert!(domain_matching_rule.is_matched("test.valid.org"));
    // Invalid patterns should be ignored, not cause errors
    assert!(!domain_matching_rule.is_matched("invalid.domain"));
  }

  #[test]
  fn test_empty_input() {
    let empty_rule = DomainMatchingRule::try_from(vec![] as Vec<String>).unwrap();

    // Empty rule should not match anything
    assert!(!empty_rule.is_matched("google.com"));
    assert!(!empty_rule.is_matched("example.org"));

    // Test empty results for all methods
    assert!(empty_rule.find_suffix_match_all("google.com").is_empty());
    assert_eq!(empty_rule.find_suffix_match_longest("google.com"), None);
    assert!(!empty_rule.find_suffix_match("google.com"));
    assert!(!empty_rule.find_prefix_match("google.com"));
  }

  #[test]
  fn test_complex_multilevel_domains() {
    let domain_matching_rule = DomainMatchingRule::try_from(vec![
      "*.api.service.example.com".to_string(),
      "deep.nested.domain.*".to_string(),
      "a.b.c.d.e.f.g.com".to_string(),
    ])
    .unwrap();

    // Test deep suffix matching
    assert!(domain_matching_rule.is_matched("v1.api.service.example.com"));
    assert!(domain_matching_rule.is_matched("api.service.example.com"));

    // Test deep prefix matching
    assert!(domain_matching_rule.is_matched("deep.nested.domain.org"));
    assert!(domain_matching_rule.is_matched("deep.nested.domain.co.uk"));

    // Test exact deep domain matching
    assert!(domain_matching_rule.is_matched("a.b.c.d.e.f.g.com"));

    // Test non-matches
    assert!(!domain_matching_rule.is_matched("service.example.com"));
    assert!(!domain_matching_rule.is_matched("nested.domain.org"));
  }
}