structured_email_address/
error.rs1use core::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct Error {
8 kind: ErrorKind,
9 position: usize,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ErrorKind {
15 Empty,
17 MissingAtSign,
19 EmptyLocalPart,
21 EmptyDomain,
23 LocalPartTooLong { len: usize },
25 AddressTooLong { len: usize },
27 DomainLabelTooLong { label: String, len: usize },
29 InvalidLocalPartChar { ch: char },
31 InvalidDomainChar { ch: char },
33 DomainLabelHyphen,
35 DomainNoDot,
37 UnterminatedQuotedString,
39 InvalidQuotedPair,
41 UnterminatedComment,
43 UnterminatedDomainLiteral,
45 IdnaError(String),
47 UnknownTld(String),
49 Unexpected { ch: char },
51}
52
53impl Error {
54 pub(crate) fn new(kind: ErrorKind, position: usize) -> Self {
56 Self { kind, position }
57 }
58
59 pub fn kind(&self) -> &ErrorKind {
61 &self.kind
62 }
63
64 pub fn position(&self) -> usize {
66 self.position
67 }
68}
69
70impl fmt::Display for Error {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 match &self.kind {
73 ErrorKind::Empty => write!(f, "empty input"),
74 ErrorKind::MissingAtSign => write!(f, "missing '@' separator"),
75 ErrorKind::EmptyLocalPart => write!(f, "empty local part"),
76 ErrorKind::EmptyDomain => write!(f, "empty domain"),
77 ErrorKind::LocalPartTooLong { len } => {
78 write!(f, "local part too long: {len} octets (max 64)")
79 }
80 ErrorKind::AddressTooLong { len } => {
81 write!(f, "address too long: {len} octets (max 254)")
82 }
83 ErrorKind::DomainLabelTooLong { label, len } => {
84 write!(f, "domain label '{label}' too long: {len} octets (max 63)")
85 }
86 ErrorKind::InvalidLocalPartChar { ch } => {
87 write!(f, "invalid character in local part: '{ch}'")
88 }
89 ErrorKind::InvalidDomainChar { ch } => {
90 write!(f, "invalid character in domain: '{ch}'")
91 }
92 ErrorKind::DomainLabelHyphen => {
93 write!(f, "domain label starts or ends with hyphen")
94 }
95 ErrorKind::DomainNoDot => write!(f, "domain has no dot"),
96 ErrorKind::UnterminatedQuotedString => write!(f, "unterminated quoted string"),
97 ErrorKind::InvalidQuotedPair => write!(f, "invalid quoted-pair escape"),
98 ErrorKind::UnterminatedComment => write!(f, "unterminated comment"),
99 ErrorKind::UnterminatedDomainLiteral => write!(f, "unterminated domain literal"),
100 ErrorKind::IdnaError(msg) => write!(f, "IDNA encoding failed: {msg}"),
101 ErrorKind::UnknownTld(tld) => write!(f, "unknown TLD: .{tld}"),
102 ErrorKind::Unexpected { ch } => {
103 write!(
104 f,
105 "unexpected character '{ch}' at position {}",
106 self.position
107 )
108 }
109 }
110 }
111}
112
113impl std::error::Error for Error {}