rfc2047_decoder/
parser.rs

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
use charset::Charset;
use std::{convert::TryFrom, result};

use crate::lexer::{encoded_word, Token, Tokens};

/// All errors which the parser can throw.
#[derive(thiserror::Error, Debug, Clone, PartialEq)]
pub enum Error {
    #[error("cannot parse encoding: encoding is bigger than a char")]
    ParseEncodingTooBigError,
    #[error("cannot parse encoding: encoding is empty")]
    ParseEncodingEmptyError,
    #[error("cannot parse encoding {0}: B or Q is expected")]
    ParseEncodingError(char),
}

type Result<T> = result::Result<T, Error>;

pub type ClearText = Vec<u8>;
pub type ParsedEncodedWords = Vec<ParsedEncodedWord>;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Encoding {
    B,
    Q,
}

impl Encoding {
    pub const B_CHAR: char = 'b';
    pub const Q_CHAR: char = 'q';
    pub const MAX_LENGTH: usize = 1;
}

impl TryFrom<Vec<u8>> for Encoding {
    type Error = Error;

    fn try_from(token: Vec<u8>) -> Result<Self> {
        if token.len() > Self::MAX_LENGTH {
            return Err(Error::ParseEncodingTooBigError);
        }

        let encoding = token.first().ok_or(Error::ParseEncodingEmptyError)?;
        let encoding = *encoding as char;

        match encoding.to_ascii_lowercase() {
            Encoding::Q_CHAR => Ok(Self::Q),
            Encoding::B_CHAR => Ok(Self::B),
            _ => Err(Error::ParseEncodingError(encoding)),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Hash)]
pub enum ParsedEncodedWord {
    ClearText(ClearText),
    EncodedWord {
        charset: Option<Charset>,
        encoding: Encoding,
        encoded_text: Vec<u8>,
    },
}

impl ParsedEncodedWord {
    pub fn convert_encoded_word(encoded_word: encoded_word::EncodedWord) -> Result<Self> {
        let encoding = Encoding::try_from(encoded_word.encoding)?;
        let charset = Charset::for_label(&encoded_word.charset);

        Ok(Self::EncodedWord {
            charset,
            encoding,
            encoded_text: encoded_word.encoded_text,
        })
    }
}

pub fn run(tokens: Tokens) -> Result<ParsedEncodedWords> {
    let parsed_encoded_words = convert_tokens_to_encoded_words(tokens)?;
    Ok(parsed_encoded_words)
}

fn convert_tokens_to_encoded_words(tokens: Tokens) -> Result<ParsedEncodedWords> {
    tokens
        .into_iter()
        .map(|token: Token| match token {
            Token::ClearText(clear_text) => Ok(ParsedEncodedWord::ClearText(clear_text)),
            Token::EncodedWord(encoded_word) => {
                ParsedEncodedWord::convert_encoded_word(encoded_word)
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use charset::Charset;

    use crate::{
        lexer,
        parser::{self, Encoding, ParsedEncodedWord},
        Decoder,
    };

    /// Example taken from:
    /// https://datatracker.ietf.org/doc/html/rfc2047#section-8
    ///
    /// `From` field
    #[test]
    fn test_parse1() {
        let message = "=?US-ASCII?Q?Keith_Moore?=".as_bytes();
        let tokens = lexer::run(&message, Decoder::new()).unwrap();
        let parsed = parser::run(tokens).unwrap();

        let expected = vec![ParsedEncodedWord::EncodedWord {
            charset: Charset::for_label("US-ASCII".as_bytes()),
            encoding: Encoding::Q,
            encoded_text: "Keith_Moore".as_bytes().to_vec(),
        }];

        assert_eq!(parsed, expected);
    }

    /// Example taken from:
    /// https://datatracker.ietf.org/doc/html/rfc2047#section-8
    ///
    /// `To` field
    #[test]
    fn test_parse2() {
        let message = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?=".as_bytes();
        let tokens = lexer::run(&message, Decoder::new()).unwrap();
        let parsed = parser::run(tokens).unwrap();

        let expected = vec![ParsedEncodedWord::EncodedWord {
            charset: Charset::for_label("ISO-8859-1".as_bytes()),
            encoding: Encoding::Q,
            encoded_text: "Keld_J=F8rn_Simonsen".as_bytes().to_vec(),
        }];

        assert_eq!(parsed, expected);
    }

    /// Example taken from:
    /// https://datatracker.ietf.org/doc/html/rfc2047#section-8
    ///
    /// `CC` field
    #[test]
    fn test_parse3() {
        let message = "=?ISO-8859-1?Q?Andr=E9?=".as_bytes();
        let tokens = lexer::run(&message, Decoder::new()).unwrap();
        let parsed = parser::run(tokens).unwrap();

        let expected = vec![ParsedEncodedWord::EncodedWord {
            charset: Charset::for_label("ISO-8859-1".as_bytes()),
            encoding: Encoding::Q,
            encoded_text: "Andr=E9".as_bytes().to_vec(),
        }];

        assert_eq!(parsed, expected);
    }

    /// Example taken from:
    /// https://datatracker.ietf.org/doc/html/rfc2047#section-8
    ///
    /// `Subject` field
    #[test]
    fn test_parse4() {
        let message = "=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".as_bytes();
        let tokens = lexer::run(&message, Decoder::new()).unwrap();
        let parsed = parser::run(tokens).unwrap();

        let expected = vec![ParsedEncodedWord::EncodedWord {
            charset: Charset::for_label("ISO-8859-1".as_bytes()),
            encoding: Encoding::B,
            encoded_text: "SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=".as_bytes().to_vec(),
        }];

        assert_eq!(parsed, expected);
    }
}