structured-email-address 0.0.10

RFC 5321/5322/6531 email address parser, validator, and normalizer. Subaddress extraction, provider-aware normalization, PSL domain validation, anti-homoglyph protection.
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! # structured-email-address
//!
//! RFC 5321/5322/6531 conformant email address parser, validator, and normalizer.
//!
//! Unlike existing Rust crates that stop at RFC validation, this crate provides:
//! - **Subaddress extraction**: `user+tag@domain` → separate `user`, `tag`, `domain`
//! - **Provider-aware normalization**: Gmail dot-stripping, configurable case folding
//! - **PSL domain validation**: verify domain against the Public Suffix List
//! - **Anti-homoglyph protection**: detect Cyrillic/Latin lookalikes via Unicode skeleton
//! - **Configurable strictness**: Strict (5321), Standard (5322), Lax (obs-* allowed)
//! - **Zero-copy parsing**: internal spans into the input string
//!
//! # Quick Start
//!
//! ```
//! use structured_email_address::{EmailAddress, Config};
//!
//! // Simple: parse with defaults
//! let email: EmailAddress = "user+tag@example.com".parse().unwrap();
//! assert_eq!(email.local_part(), "user+tag");
//! assert_eq!(email.tag(), Some("tag"));
//! assert_eq!(email.domain(), "example.com");
//!
//! // Configured: Gmail normalization pipeline
//! let config = Config::builder()
//!     .strip_subaddress()
//!     .dots_gmail_only()
//!     .lowercase_all()
//!     .build();
//!
//! let email = EmailAddress::parse_with("A.L.I.C.E+promo@Gmail.COM", &config).unwrap();
//! assert_eq!(email.canonical(), "alice@gmail.com");
//! assert_eq!(email.tag(), Some("promo"));
//! ```

#![cfg_attr(
    not(test),
    deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)
)]

mod config;
mod error;
mod normalize;
mod parser;
mod provider;
mod validate;

pub use config::{
    CasePolicy, Config, ConfigBuilder, DomainCheck, DotPolicy, Strictness, SubaddressPolicy,
};
pub use error::{Error, ErrorKind};
pub use normalize::confusable_skeleton;
pub use provider::{ProviderRegistry, ProviderRule};

/// A parsed, validated, and normalized email address.
///
/// Immutable after construction. All accessors return borrowed data.
#[derive(Debug, Clone)]
pub struct EmailAddress {
    /// Original input, exactly as supplied to the parser.
    original: String,
    /// Canonical local part (after normalization).
    local_part: String,
    /// Extracted subaddress tag, if any.
    tag: Option<String>,
    /// Canonical domain (IDNA-encoded, lowercased).
    domain: String,
    /// Unicode form of the domain (only when domain has punycode labels).
    domain_unicode: Option<String>,
    /// Display name, if parsed from `name-addr` format.
    display_name: Option<String>,
    /// Confusable skeleton, if config enabled it.
    skeleton: Option<String>,
    /// Whether the domain is a known freemail provider (from the registry).
    freemail: bool,
}

impl EmailAddress {
    /// Parse and validate with the given configuration.
    pub fn parse_with(input: &str, config: &Config) -> Result<Self, Error> {
        let parsed = parser::parse(
            input,
            config.strictness,
            config.allow_display_name,
            config.allow_domain_literal,
        )?;

        let normalized = normalize::normalize(&parsed, config)?;
        validate::validate(&parsed, &normalized, config)?;

        // Freemail status comes from the provider registry (built-ins + any
        // custom rules), independent of provider-aware normalization.
        let freemail = config
            .providers
            .lookup(&normalized.domain)
            .is_some_and(|p| p.is_freemail());

        Ok(Self {
            original: parsed.input.to_string(),
            local_part: normalized.local_part,
            tag: normalized.tag,
            domain: normalized.domain,
            domain_unicode: normalized.domain_unicode,
            display_name: normalized.display_name,
            skeleton: normalized.skeleton,
            freemail,
        })
    }

    /// The canonical local part (after normalization).
    ///
    /// If subaddress stripping is enabled, this excludes the `+tag`.
    /// If dot stripping is enabled, dots are removed.
    pub fn local_part(&self) -> &str {
        &self.local_part
    }

    /// The extracted subaddress tag, if present.
    ///
    /// For `user+promo@example.com`, returns `Some("promo")`.
    /// Always extracted regardless of [`SubaddressPolicy`] — the policy only
    /// affects whether it appears in [`canonical()`](Self::canonical).
    pub fn tag(&self) -> Option<&str> {
        self.tag.as_deref()
    }

    /// The canonical domain (IDNA-encoded, lowercased).
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// The canonical domain in Unicode form.
    ///
    /// For internationalized domains (`münchen.de` → `xn--mnchen-3ya.de`),
    /// returns the Unicode form of the canonical domain. For ASCII-only
    /// domains, returns the same value as [`domain()`](Self::domain).
    ///
    /// # Security
    ///
    /// The Unicode form is intended for **display only**. It may reintroduce
    /// [IDN homograph attacks](https://en.wikipedia.org/wiki/IDN_homograph_attack)
    /// where visually similar characters from different scripts produce
    /// different domain names (e.g. Cyrillic `а` vs Latin `a`).
    ///
    /// For security-sensitive comparisons (allow-lists, deduplication, access
    /// control), always use [`domain()`](Self::domain) which returns the
    /// ACE/Punycode form. If you must compare Unicode domains, apply your own
    /// confusable-detection logic (see [`confusable_skeleton()`]).
    ///
    /// ```
    /// use structured_email_address::EmailAddress;
    ///
    /// let email: EmailAddress = "user@münchen.de".parse().unwrap();
    /// assert_eq!(email.domain(), "xn--mnchen-3ya.de");
    /// assert_eq!(email.domain_unicode(), "münchen.de");
    ///
    /// let ascii: EmailAddress = "user@example.com".parse().unwrap();
    /// assert_eq!(ascii.domain_unicode(), "example.com");
    /// ```
    pub fn domain_unicode(&self) -> &str {
        self.domain_unicode.as_deref().unwrap_or(&self.domain)
    }

    /// The display name, if parsed from `"Name" <addr>` or `Name <addr>` format.
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// The full canonical address: `local_part@domain`.
    ///
    /// If the local part contains characters that require quoting (spaces,
    /// special chars), it is wrapped in quotes for RFC compliance.
    pub fn canonical(&self) -> String {
        if needs_quoting(&self.local_part) {
            let escaped = escape_local_part(&self.local_part);
            format!("\"{}\"@{}", escaped, self.domain)
        } else {
            format!("{}@{}", self.local_part, self.domain)
        }
    }

    /// The original input, exactly as supplied to the parser (not trimmed).
    pub fn original(&self) -> &str {
        &self.original
    }

    /// The confusable skeleton of the local part (if config enabled it).
    ///
    /// Two addresses with the same skeleton + domain are visually confusable.
    pub fn skeleton(&self) -> Option<&str> {
        self.skeleton.as_deref()
    }

    /// Check if the domain is a known freemail provider.
    ///
    /// Determined from the [`ProviderRegistry`] in the [`Config`] used to parse
    /// (built-in providers plus any registered via
    /// [`ConfigBuilder::add_provider`]).
    pub fn is_freemail(&self) -> bool {
        self.freemail
    }

    /// Parse a batch of email addresses with the given configuration.
    ///
    /// Returns one `Result` per input, in the same order. The config is
    /// shared across all inputs, amortizing setup cost.
    ///
    /// # Example
    ///
    /// ```
    /// use structured_email_address::{EmailAddress, Config};
    ///
    /// let config = Config::default();
    /// let results = EmailAddress::parse_batch(
    ///     &["alice@example.com", "invalid", "bob@example.org"],
    ///     &config,
    /// );
    /// assert!(results[0].is_ok());
    /// assert!(results[1].is_err());
    /// assert!(results[2].is_ok());
    /// ```
    pub fn parse_batch(inputs: &[&str], config: &Config) -> Vec<Result<Self, Error>> {
        inputs
            .iter()
            .map(|input| Self::parse_with(input, config))
            .collect()
    }

    /// Parse a batch of email addresses in parallel using rayon.
    ///
    /// Same semantics as [`parse_batch`](Self::parse_batch), but distributes
    /// work across rayon's thread pool. Useful for bulk import/validation of
    /// large lists (10K+ addresses).
    ///
    /// Requires the `rayon` feature.
    ///
    /// # Example
    ///
    /// ```
    /// use structured_email_address::{EmailAddress, Config};
    ///
    /// let config = Config::default();
    /// let results = EmailAddress::parse_batch_par(
    ///     &["alice@example.com", "bob@example.org"],
    ///     &config,
    /// );
    /// assert!(results.iter().all(|r| r.is_ok()));
    /// ```
    #[cfg(feature = "rayon")]
    pub fn parse_batch_par(inputs: &[&str], config: &Config) -> Vec<Result<Self, Error>> {
        use rayon::prelude::*;

        inputs
            .par_iter()
            .map(|input| Self::parse_with(input, config))
            .collect()
    }
}

impl std::fmt::Display for EmailAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let local = if needs_quoting(&self.local_part) {
            format!("\"{}\"", escape_local_part(&self.local_part))
        } else {
            self.local_part.clone()
        };
        match &self.display_name {
            Some(name) => write!(
                f,
                "\"{}\" <{}@{}>",
                escape_display_name(name),
                local,
                self.domain
            ),
            None => write!(f, "{}@{}", local, self.domain),
        }
    }
}

/// Check if a local-part needs quoting for RFC 5321/5322 serialization.
/// Returns true if the local part contains characters outside of atext.
fn needs_quoting(local: &str) -> bool {
    if local.is_empty() {
        return true;
    }
    // Dots are only safe in valid dot-atom form (no leading/trailing/consecutive dots).
    if local.starts_with('.') || local.ends_with('.') || local.contains("..") {
        return true;
    }
    local.chars().any(|ch| {
        !ch.is_ascii_alphanumeric()
            && !matches!(
                ch,
                '!' | '#'
                    | '$'
                    | '%'
                    | '&'
                    | '\''
                    | '*'
                    | '+'
                    | '-'
                    | '/'
                    | '='
                    | '?'
                    | '^'
                    | '_'
                    | '`'
                    | '{'
                    | '|'
                    | '}'
                    | '~'
                    | '.'
            )
            && (ch as u32) < 0x80 // non-ASCII doesn't need quoting per RFC 6531
    })
}

/// Escape a local-part for use inside quotes: backslash-escape `"` and `\`,
/// strip CR/LF to prevent header injection (FWS is collapsed during normalization).
fn escape_local_part(local: &str) -> String {
    let mut escaped = String::with_capacity(local.len());
    for ch in local.chars() {
        match ch {
            '"' | '\\' => {
                escaped.push('\\');
                escaped.push(ch);
            }
            '\r' | '\n' => {} // strip CRLF to prevent header injection
            _ => escaped.push(ch),
        }
    }
    escaped
}

/// Backslash-escapes `"` and `\`, and strips bare CR/LF to prevent
/// header injection in serialized output.
fn escape_display_name(name: &str) -> String {
    let mut escaped = String::with_capacity(name.len());
    for ch in name.chars() {
        match ch {
            '"' => {
                escaped.push('\\');
                escaped.push('"');
            }
            '\\' => {
                escaped.push('\\');
                escaped.push('\\');
            }
            '\r' | '\n' => {} // strip CRLF
            _ => escaped.push(ch),
        }
    }
    escaped
}

/// Equality is based on canonical form (`local_part` + `domain`) only.
/// Display name, tag, and skeleton are intentionally excluded —
/// `"John" <user@example.com>` equals `"Jane" <user@example.com>`
/// because they route to the same mailbox.
impl PartialEq for EmailAddress {
    fn eq(&self, other: &Self) -> bool {
        self.local_part == other.local_part && self.domain == other.domain
    }
}

impl Eq for EmailAddress {}

impl std::hash::Hash for EmailAddress {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.local_part.hash(state);
        self.domain.hash(state);
    }
}

impl std::str::FromStr for EmailAddress {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_with(s, &Config::default())
    }
}

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

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

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

    // ── FromStr (default config) ──

    #[test]
    fn parse_simple() {
        let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "user");
        assert_eq!(email.domain(), "example.com");
        assert_eq!(email.tag(), None);
        assert_eq!(email.canonical(), "user@example.com");
    }

    #[test]
    fn parse_with_tag() {
        let email: EmailAddress = "user+newsletter@example.com"
            .parse()
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "user+newsletter");
        assert_eq!(email.tag(), Some("newsletter"));
    }

    #[test]
    fn display_format() {
        let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(format!("{email}"), "user@example.com");
    }

    #[test]
    fn display_name_escaping() {
        let config = Config::builder().allow_display_name().build();
        // Display name with quotes should be escaped
        let email = EmailAddress::parse_with("John \"Johnny\" Doe <user@example.com>", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        let formatted = format!("{email}");
        assert!(
            formatted.contains("\\\"Johnny\\\""),
            "Expected escaped quotes in: {formatted}"
        );
    }

    #[test]
    fn equality_by_canonical() {
        let a: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
        let b: EmailAddress = "user@Example.COM".parse().unwrap_or_else(|e| panic!("{e}"));
        // Default config: domain-only lowercase, so local parts same case → equal
        assert_eq!(a, b);
    }

    #[test]
    fn freemail_detection() {
        let email: EmailAddress = "user@gmail.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert!(email.is_freemail());

        let email: EmailAddress = "user@company.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert!(!email.is_freemail());
    }

    #[test]
    fn freemail_via_custom_provider() {
        // A registered custom provider marked freemail is reported by is_freemail().
        use crate::ProviderRule;
        let config = Config::builder()
            .add_provider(ProviderRule::new(["freebie.example"]).freemail(true))
            .build();
        let email = EmailAddress::parse_with("user@freebie.example", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert!(email.is_freemail());
    }

    // ── Provider-aware normalization (#5) ──

    #[test]
    fn provider_aware_gmail_normalizes_by_rule() {
        // provider_aware applies Gmail's rule (strip dots, fold case, '+' tag)
        // without setting any global dot/case policy. strip_subaddress drops the
        // extracted tag from the canonical form.
        let config = Config::builder()
            .provider_aware()
            .strip_subaddress()
            .build();
        let email = EmailAddress::parse_with("A.Li.Ce+promo@Gmail.com", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "alice");
        assert_eq!(email.tag(), Some("promo"));
        assert_eq!(email.domain(), "gmail.com");
    }

    #[test]
    fn provider_aware_gmail_preserves_tag_by_default() {
        // Default subaddress policy keeps the tag in the canonical local part;
        // dots are still stripped and case folded by the Gmail rule.
        let config = Config::builder().provider_aware().build();
        let email = EmailAddress::parse_with("A.Li.Ce+promo@Gmail.com", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "alice+promo");
        assert_eq!(email.tag(), Some("promo"));
    }

    #[test]
    fn provider_aware_leaves_non_provider_domains_to_global_policy() {
        // A non-provider domain is untouched by provider rules: dots preserved,
        // local-part case preserved (global defaults).
        let config = Config::builder().provider_aware().build();
        let email = EmailAddress::parse_with("A.L.I.C.E@example.com", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "A.L.I.C.E");
        assert_eq!(email.domain(), "example.com");
    }

    #[test]
    fn provider_aware_quoted_local_preserves_case() {
        // A quoted local-part is literal: the provider rule's case folding
        // (Gmail) must NOT apply inside it, just as dots and the subaddress
        // separator don't. Without a global lowercase policy, case is preserved.
        let config = Config::builder().provider_aware().build();
        let email = EmailAddress::parse_with("\"A.B\"@gmail.com", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "A.B");

        // A global lowercase policy is not provider-specific, so it still folds
        // a quoted local-part — even when a provider rule matches (the rule's
        // own folding is skipped for quoted, but the global policy still applies).
        let config = Config::builder().provider_aware().lowercase_all().build();
        let email = EmailAddress::parse_with("\"A.B\"@gmail.com", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "a.b");
    }

    #[test]
    fn provider_aware_off_does_not_strip_gmail_dots() {
        // Without provider_aware and without dots_gmail_only, gmail dots stay.
        let email: EmailAddress = "a.b.c@gmail.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "a.b.c");
    }

    #[test]
    fn custom_provider_aware_rule_applies() {
        use crate::ProviderRule;
        // Custom provider: strips dots, '-' separator.
        let config = Config::builder()
            .provider_aware()
            .strip_subaddress()
            .add_provider(
                ProviderRule::new(["corp.example"])
                    .strip_dots(true)
                    .lowercase_local(true)
                    .subaddress_separator(Some('-')),
            )
            .build();
        let email = EmailAddress::parse_with("John.Doe-tag@corp.example", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "johndoe");
        assert_eq!(email.tag(), Some("tag"));
    }

    #[test]
    fn idn_provider_rule_consistent_across_normalization_and_freemail() {
        use crate::ProviderRule;
        // A provider rule registered with the Unicode domain must apply to the
        // IDNA-encoded address for BOTH provider-aware normalization and
        // is_freemail() — the canonical domain is used at both call sites.
        let config = Config::builder()
            .provider_aware()
            .add_provider(
                ProviderRule::new(["münchen.de"])
                    .strip_dots(true)
                    .lowercase_local(true)
                    .freemail(true),
            )
            .build();
        let email =
            EmailAddress::parse_with("A.B@münchen.de", &config).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.domain(), "xn--mnchen-3ya.de");
        assert_eq!(
            email.local_part(),
            "ab",
            "provider rule strips dots + folds case"
        );
        assert!(email.is_freemail(), "same rule drives is_freemail");
    }

    #[test]
    fn dots_gmail_only_ignores_custom_providers() {
        use crate::ProviderRule;
        // GmailOnly is a legacy mode tied to the built-in dot-stripping providers
        // (Gmail/Googlemail). Custom providers affect normalization ONLY under
        // provider_aware(); a custom strip_dots rule must NOT leak into GmailOnly
        // when provider_aware is off.
        let config = Config::builder()
            .dots_gmail_only()
            .add_provider(ProviderRule::new(["corp.example"]).strip_dots(true))
            .build();

        // The custom provider's strip_dots is ignored: dots are preserved.
        let email =
            EmailAddress::parse_with("a.b@corp.example", &config).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "a.b");

        // Built-in Gmail still strips dots under GmailOnly.
        let email =
            EmailAddress::parse_with("a.b.c@gmail.com", &config).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.local_part(), "abc");
    }

    // ── Configured parsing ──

    #[test]
    fn full_normalization_pipeline() {
        let config = Config::builder()
            .strip_subaddress()
            .dots_gmail_only()
            .lowercase_all()
            .check_confusables()
            .build();

        let email = EmailAddress::parse_with("A.L.I.C.E+promo@Gmail.COM", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.canonical(), "alice@gmail.com");
        assert_eq!(email.tag(), Some("promo"));
        assert!(email.skeleton().is_some());
    }

    #[test]
    fn display_name_parsing() {
        let config = Config::builder().allow_display_name().build();

        let email = EmailAddress::parse_with("John Doe <user@example.com>", &config)
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.display_name(), Some("John Doe"));
        assert_eq!(email.local_part(), "user");
        assert_eq!(email.domain(), "example.com");
    }

    #[test]
    fn leading_comment_full_pipeline() {
        // #40: a leading RFC 5322 comment before the local-part must parse
        // end-to-end, with the comment stripped from the canonical address.
        let config = Config::builder()
            .strictness(Strictness::Lax)
            .allow_display_name()
            .allow_domain_literal()
            .allow_single_label_domain()
            .lowercase_all()
            .build();

        for input in [
            "(comment)jane.smith@example.com",
            "jane(comment).smith@example.com",
            "jane.smith(comment)@example.com",
            "jane.smith@example.com",
        ] {
            let email = EmailAddress::parse_with(input, &config)
                .unwrap_or_else(|e| panic!("'{input}' must parse: {e}"));
            assert_eq!(email.canonical(), "jane.smith@example.com");
        }
    }

    #[test]
    fn rejects_newline_in_address() {
        // Header-injection hardening: a trailing newline must not be silently
        // accepted (it previously survived an over-eager input.trim()).
        let config = Config::default();
        assert!("user@example.com\n".parse::<EmailAddress>().is_err());
        assert!(EmailAddress::parse_with("user@example.com\r\n", &config).is_err());
    }

    // ── Serde ──

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip() {
        let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
        let json = serde_json::to_string(&email).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(json, "\"user@example.com\"");

        let back: EmailAddress = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email, back);
    }

    // ── Validation errors ──

    #[test]
    fn rejects_empty() {
        let result: Result<EmailAddress, _> = "".parse();
        assert!(result.is_err());
    }

    #[test]
    fn rejects_no_domain_dot() {
        let result: Result<EmailAddress, _> = "user@localhost".parse();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err().kind(), ErrorKind::DomainNoDot));
    }

    #[test]
    fn allows_single_label_when_configured() {
        let config = Config::builder().allow_single_label_domain().build();
        let email =
            EmailAddress::parse_with("user@localhost", &config).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.domain(), "localhost");
    }

    // ── Batch parsing ──

    #[test]
    fn batch_parse_mixed_results() {
        // Verifies that parse_batch returns Ok for valid and Err for invalid
        // inputs, preserving input order.
        let config = Config::default();
        let results = EmailAddress::parse_batch(
            &["alice@example.com", "invalid", "bob@example.org"],
            &config,
        );
        assert_eq!(results.len(), 3);
        assert!(results[0].is_ok());
        assert!(results[1].is_err());
        assert!(results[2].is_ok());
        assert_eq!(results[0].as_ref().map(|e| e.domain()), Ok("example.com"));
        assert_eq!(results[2].as_ref().map(|e| e.domain()), Ok("example.org"));
    }

    #[test]
    fn batch_parse_empty_input() {
        // Empty slice returns empty vec.
        let config = Config::default();
        let results = EmailAddress::parse_batch(&[], &config);
        assert!(results.is_empty());
    }

    #[test]
    fn batch_parse_all_valid() {
        // Batch of valid addresses all succeed.
        let config = Config::default();
        let inputs = &["a@b.com", "x@y.org", "test+tag@example.com"];
        let results = EmailAddress::parse_batch(inputs, &config);
        assert!(results.iter().all(|r| r.is_ok()));
    }

    #[test]
    fn batch_parse_all_invalid() {
        // Batch of invalid addresses all fail.
        let config = Config::default();
        let results = EmailAddress::parse_batch(&["", "noatsign", "@missing-local.com"], &config);
        assert!(results.iter().all(|r| r.is_err()));
    }

    #[test]
    fn batch_parse_with_config() {
        // Batch parsing respects config (e.g., subaddress stripping).
        let config = Config::builder()
            .strip_subaddress()
            .dots_gmail_only()
            .lowercase_all()
            .build();
        let results =
            EmailAddress::parse_batch(&["A.L.I.C.E+promo@Gmail.COM", "BOB@example.com"], &config);
        assert_eq!(results.len(), 2);
        assert_eq!(
            results[0].as_ref().map(|e| e.canonical()),
            Ok("alice@gmail.com".to_string())
        );
        assert_eq!(
            results[1].as_ref().map(|e| e.canonical()),
            Ok("bob@example.com".to_string())
        );
    }

    // ── domain_unicode() accessor ──

    #[test]
    fn domain_unicode_roundtrip() {
        // IDN domain: input Unicode → domain() punycode → domain_unicode() back to Unicode.
        let email: EmailAddress = "user@münchen.de".parse().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.domain(), "xn--mnchen-3ya.de");
        assert_eq!(email.domain_unicode(), "münchen.de");
    }

    #[test]
    fn domain_unicode_ascii_fallback() {
        // ASCII domain: domain_unicode() returns same as domain().
        let email: EmailAddress = "user@example.com".parse().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.domain_unicode(), "example.com");
        assert_eq!(email.domain_unicode(), email.domain());
    }

    #[test]
    fn domain_unicode_mixed_labels() {
        // Domain with one IDN label and one ASCII label.
        let email: EmailAddress = "user@über.example.com"
            .parse()
            .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(email.domain(), "xn--ber-goa.example.com");
        assert_eq!(email.domain_unicode(), "über.example.com");
    }

    #[test]
    fn domain_unicode_japanese() {
        // Japanese domain roundtrip.
        let email: EmailAddress = "user@例え.jp".parse().unwrap_or_else(|e| panic!("{e}"));
        assert!(email.domain().contains("xn--"));
        assert_eq!(email.domain_unicode(), "例え.jp");
    }

    #[cfg(feature = "rayon")]
    #[test]
    fn batch_par_matches_sequential() {
        // Parallel variant produces identical results to sequential.
        let config = Config::builder().strip_subaddress().lowercase_all().build();
        let inputs = &[
            "alice@example.com",
            "invalid",
            "BOB+tag@Example.ORG",
            "",
            "user@test.com",
        ];
        let seq = EmailAddress::parse_batch(inputs, &config);
        let par = EmailAddress::parse_batch_par(inputs, &config);
        assert_eq!(seq.len(), par.len());
        for (i, (s, p)) in seq.iter().zip(par.iter()).enumerate() {
            match (s, p) {
                (Ok(a), Ok(b)) => assert_eq!(a, b, "result {i} diverges"),
                (Err(a), Err(b)) => assert_eq!(a, b, "error {i} diverges: {a} vs {b}"),
                _ => panic!("result {i}: one Ok, one Err"),
            }
        }
    }
}