Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify RFC 2822 comment parser #737

Merged
merged 3 commits into from Jul 26, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/format/parse.rs
Expand Up @@ -150,11 +150,8 @@ fn parse_rfc2822<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a st
}

// optional comments
s = s.trim_left();
while let Ok((s_out, ())) = scan::comment_2822(s) {
// Trim left after every found comment, as comments are allowed to have whitespace
// between them
s = s_out.trim_left();
s = s_out;
}

Ok((s, ()))
Expand Down
64 changes: 24 additions & 40 deletions src/format/scan.rs
Expand Up @@ -349,49 +349,33 @@ pub(super) fn timezone_name_skip(s: &str) -> ParseResult<(&str, ())> {
Ok((s.trim_left_matches(|c: char| !c.is_whitespace()), ()))
}

/// Tries to consume an RFC2822 comment
pub(super) fn comment_2822(mut s: &str) -> ParseResult<(&str, ())> {
macro_rules! next_char {
() => {{
let c = s.bytes().nth(0).ok_or(TOO_SHORT)?;
s = &s[1..];
c
}};
}

// Make sure the first letter is a `(`
if b'(' != next_char!() {
Err(INVALID)?;
}

let mut depth = 1; // start with 1 as we already encountered a '('
loop {
match next_char!() {
// If we encounter `\`, ignore the next character as it is escaped.
b'\\' => {
next_char!();
}

// If we encounter `(`, open a parantheses context.
b'(' => {
depth += 1;
}

// If we encounter `)`, close a parentheses context.
// If all are closed, we found the end of the comment.
b')' => {
depth -= 1;
if depth == 0 {
break;
}
}

// Ignore all other characters
_ => (),
/// Tries to consume an RFC2822 comment including preceding ` `.
///
/// Returns the remaining string after the closing parenthesis.
pub(super) fn comment_2822(s: &str) -> ParseResult<(&str, ())> {
use CommentState::*;

let mut state = Start;
for (i, c) in s.bytes().enumerate() {
state = match (state, c) {
(Start, b' ') => Start,
djc marked this conversation as resolved.
Show resolved Hide resolved
(Start, b'(') => Next(1),
(Next(1), b')') => return Ok((&s[i + 1..], ())),
(Next(depth), b'\\') => Escape(depth),
(Next(depth), b'(') => Next(depth + 1),
(Next(depth), b')') => Next(depth - 1),
(Next(depth), _) | (Escape(depth), _) => Next(depth),
_ => return Err(INVALID),
};
}

Ok((s, ()))
Err(TOO_SHORT)
}

enum CommentState {
Start,
Next(usize),
Escape(usize),
}

#[cfg(test)]
Expand Down