rfc2047_decoder/lexer/
encoded_word.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
use std::fmt::Display;

use super::QUESTION_MARK;

pub const PREFIX: &[u8] = "=?".as_bytes();
pub const SUFFIX: &[u8] = "?=".as_bytes();
pub const MAX_LENGTH: usize = 75;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EncodedWord {
    pub charset: Vec<u8>,
    pub encoding: Vec<u8>,
    pub encoded_text: Vec<u8>,
}

impl EncodedWord {
    pub fn new(charset: Vec<u8>, encoding: Vec<u8>, encoded_text: Vec<u8>) -> Self {
        Self {
            charset,
            encoding,
            encoded_text,
        }
    }

    pub fn from_parser(((charset, encoding), encoded_text): ((Vec<u8>, Vec<u8>), Vec<u8>)) -> Self {
        Self::new(charset, encoding, encoded_text)
    }

    /// Returns the amount of `char`s for this encoded word
    pub fn len(&self) -> usize {
        self.get_bytes(true).len()
    }

    pub fn get_bytes(&self, with_delimiters: bool) -> Vec<u8> {
        let mut bytes = Vec::new();

        if with_delimiters {
            bytes.extend(PREFIX);
            bytes.extend(&self.charset);
            bytes.extend(&[QUESTION_MARK]);
            bytes.extend(&self.encoding);
            bytes.extend(&[QUESTION_MARK]);
            bytes.extend(&self.encoded_text);
            bytes.extend(SUFFIX);
        } else {
            bytes.extend(&self.charset);
            bytes.extend(&self.encoding);
            bytes.extend(&self.encoded_text);
        }

        bytes
    }
}

impl Display for EncodedWord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let charset = String::from_utf8(self.charset.clone()).unwrap();
        let encoding = String::from_utf8(self.encoding.clone()).unwrap();
        let encoded_text = String::from_utf8(self.encoded_text.clone()).unwrap();

        write!(f, "=?{}?{}?{}?=", charset, encoding, encoded_text)
    }
}