Compare commits

...
5 Commits
Author SHA1 Message Date
Mauro D bb0e42e13b Minor fixes. 2022-11-30 18:31:07 +00:00
Mauro D 8ff26db481 Renamed body_html and body_text functions. 2022-11-28 13:03:29 +00:00
Mauro D f4424eeefc Removed get_() prefixes (#31) 2022-11-28 12:37:33 +00:00
Rudi HornandRudi Horn c542f8a0db Use modified time instead of created time (#32)
Co-authored-by: Rudi Horn <dyn-git@rudi-horn.de>
2022-11-20 21:08:44 +01:00
Mauro D 26bca49aac base64_decode_stream and quoted_printable_decode_char 2022-11-03 17:24:57 +00:00
24 changed files with 329 additions and 338 deletions
+5
View File
@@ -1,3 +1,8 @@
mail-parser 0.8.0
================================
- Removed get_() prefixes (#31).
- Maildir import: Use modified time instead of created time (#32)
mail-parser 0.7.0
================================
- Base64/QuotedPrintable decoding optimizations.
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
version = "0.7.0"
version = "0.8.0"
edition = "2018"
authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT"
+13 -13
View File
@@ -79,7 +79,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// Parses addresses (including comments), lists and groups
assert_eq!(
message.get_from(),
message.from(),
&HeaderValue::Address(Addr::new(
"Art Vandelay (Vandelay Industries)".into(),
"art@vandelay.com"
@@ -87,7 +87,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_to(),
message.to(),
&HeaderValue::GroupList(vec![
Group::new(
"Colleagues",
@@ -104,19 +104,19 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_date().unwrap().to_rfc3339(),
message.date().unwrap().to_rfc3339(),
"2021-11-20T14:22:01-08:00"
);
// RFC2047 support for encoded text in message readers
assert_eq!(
message.get_subject().unwrap(),
message.subject().unwrap(),
"Why not both importing AND exporting? ☺"
);
// HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
assert_eq!(
message.get_html_body(0).unwrap(),
message.body_html(0).unwrap(),
concat!(
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ",
"focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,",
@@ -126,7 +126,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// HTML parts are converted to plain text (and viceversa) when missing
assert_eq!(
message.get_text_body(0).unwrap(),
message.body_text(0).unwrap(),
concat!(
"I was thinking about quitting the “exporting” to focus just on the",
" “importing”,\nbut then I thought, why not do both? ☺\n"
@@ -135,33 +135,33 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// Supports nested messages as well as multipart/digest
let nested_message = message
.get_attachment(0)
.attachment(0)
.unwrap()
.get_message();
.message();
.unwrap();
assert_eq!(
nested_message.get_subject().unwrap(),
nested_message.subject().unwrap(),
"Exporting my book about coffee tables"
);
// Handles UTF-* as well as many legacy encodings
assert_eq!(
nested_message.get_text_body(0).unwrap(),
nested_message.body_text(0).unwrap(),
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
assert_eq!(
nested_message.get_html_body(0).unwrap(),
nested_message.body_html(0).unwrap(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = nested_message.get_attachment(0).unwrap();
let nested_attachment = nested_message.attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment.get_attachment_name().unwrap(),
nested_attachment.attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
+12 -12
View File
@@ -57,7 +57,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// Parses addresses (including comments), lists and groups
assert_eq!(
message.get_from(),
message.from(),
&HeaderValue::Address(Addr::new(
"Art Vandelay (Vandelay Industries)".into(),
"art@vandelay.com"
@@ -65,7 +65,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_to(),
message.to(),
&HeaderValue::GroupList(vec![
Group::new(
"Colleagues",
@@ -82,19 +82,19 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_date().unwrap().to_rfc3339(),
message.date().unwrap().to_rfc3339(),
"2021-11-20T14:22:01-08:00"
);
// RFC2047 support for encoded text in message readers
assert_eq!(
message.get_subject().unwrap(),
message.subject().unwrap(),
"Why not both importing AND exporting? ☺"
);
// HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
assert_eq!(
message.get_html_body(0).unwrap(),
message.body_html(0).unwrap(),
concat!(
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ",
"focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,",
@@ -104,7 +104,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// HTML parts are converted to plain text (and viceversa) when missing
assert_eq!(
message.get_text_body(0).unwrap(),
message.body_text(0).unwrap(),
concat!(
"I was thinking about quitting the “exporting” to focus just on the",
" “importing”,\nbut then I thought, why not do both? ☺\n"
@@ -112,30 +112,30 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
// Supports nested messages as well as multipart/digest
let nested_message = message.get_attachment(0).unwrap().get_message().unwrap();
let nested_message = message.attachment(0).unwrap().message().unwrap();
assert_eq!(
nested_message.get_subject().unwrap(),
nested_message.subject().unwrap(),
"Exporting my book about coffee tables"
);
// Handles UTF-* as well as many legacy encodings
assert_eq!(
nested_message.get_text_body(0).unwrap(),
nested_message.body_text(0).unwrap(),
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
assert_eq!(
nested_message.get_html_body(0).unwrap(),
nested_message.body_html(0).unwrap(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = nested_message.get_attachment(0).unwrap();
let nested_attachment = nested_message.attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment.get_attachment_name().unwrap(),
nested_attachment.attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
+4 -4
View File
@@ -59,15 +59,15 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
}
fn write_attachments(message: &Message) {
for attachment in message.get_attachments() {
for attachment in message.attachments() {
if !attachment.is_message() {
std::fs::write(
attachment.get_attachment_name().unwrap_or("Untitled"),
attachment.get_contents(),
attachment.attachment_name().unwrap_or("Untitled"),
attachment.contents(),
)
.unwrap();
} else {
write_attachments(attachment.get_message().unwrap());
write_attachments(attachment.message().unwrap());
}
}
}
+1 -57
View File
@@ -42,10 +42,9 @@ dependencies = [
[[package]]
name = "mail-parser"
version = "0.7.0"
version = "0.8.0"
dependencies = [
"encoding_rs",
"serde",
]
[[package]]
@@ -61,58 +60,3 @@ name = "once_cell"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
[[package]]
name = "proc-macro2"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
+7 -7
View File
@@ -3,15 +3,15 @@ use libfuzzer_sys::fuzz_target;
use mail_parser::{
decoders::{
base64::decode_base64,
base64::base64_decode,
charsets::{
map::get_charset_decoder,
map::charset_decoder,
single_byte::decoder_iso_8859_1,
utf::{decoder_utf16, decoder_utf16_be, decoder_utf16_le, decoder_utf7},
},
hex::decode_hex,
html::{add_html_token, html_to_text, text_to_html},
quoted_printable::decode_quoted_printable,
quoted_printable::quoted_printable_decode,
},
parsers::{
fields::thread::{thread_name, trim_trailing_fwd},
@@ -43,15 +43,15 @@ fuzz_target!(|data: &[u8]| {
MessageStream::new(data).decode_rfc2047();
MessageStream::new(data).seek_next_part(b"\n");
MessageStream::new(data).get_mime_part(b"\n");
MessageStream::new(data).mime_part(b"\n");
MessageStream::new(data).seek_part_end(b"\n"[..].into());
MessageStream::new(data).skip_crlf();
MessageStream::new(data).is_multipart_end();
decode_base64(data);
base64_decode(data);
MessageStream::new(data).decode_base64_word();
MessageStream::new(data).decode_base64_mime(b"\n");
decode_quoted_printable(data);
quoted_printable_decode(data);
MessageStream::new(data).decode_quoted_printable_word();
MessageStream::new(data).decode_quoted_printable_mime(b"\n");
@@ -66,7 +66,7 @@ fuzz_target!(|data: &[u8]| {
// Fuzz decoding functions
decode_hex(data);
get_charset_decoder(data);
charset_decoder(data);
for decoder in &[
decoder_utf7,
+39 -28
View File
@@ -13,13 +13,22 @@ use std::borrow::Cow;
use crate::parsers::MessageStream;
pub fn decode_base64(bytes: &[u8]) -> Option<Vec<u8>> {
#[inline(always)]
pub fn base64_decode(bytes: &[u8]) -> Option<Vec<u8>> {
base64_decode_stream(bytes.iter(), bytes.len(), u8::MAX)
}
pub fn base64_decode_stream<'x>(
stream: impl Iterator<Item = &'x u8>,
stream_len: usize,
stop_char: u8,
) -> Option<Vec<u8>> {
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut buf = Vec::with_capacity(bytes.len() / 4 * 3);
let mut buf = Vec::with_capacity(stream_len / 4 * 3);
for &ch in bytes {
for &ch in stream {
#[cfg(feature = "ludicrous_mode")]
let val = unsafe {
*BASE64_MAP
@@ -46,33 +55,35 @@ pub fn decode_base64(bytes: &[u8]) -> Option<Vec<u8>> {
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
} else if ch == b'=' {
match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
} else {
match ch {
b'=' => match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
return None;
}
0 => (),
_ => {
return None;
}
},
b' ' | b'\t' | b'\r' | b'\n' => (),
_ => return if ch == stop_char { buf.into() } else { None },
}
} else if !ch.is_ascii_whitespace() {
return None;
}
}
@@ -312,7 +323,7 @@ mod tests {
("w6HDqcOtw7PDug==", "áéíóú"),
] {
assert_eq!(
super::decode_base64(encoded_str.as_bytes()).unwrap_or_default(),
super::base64_decode(encoded_str.as_bytes()).unwrap_or_default(),
expected_result.as_bytes(),
"Failed for {:?}",
encoded_str
+4 -4
View File
@@ -16,7 +16,7 @@ use super::{
DecoderFnc,
};
pub fn get_charset_decoder(charset: &[u8]) -> Option<DecoderFnc> {
pub fn charset_decoder(charset: &[u8]) -> Option<DecoderFnc> {
if (2..=45).contains(&charset.len()) {
let mut l_charset = [0u8; 45];
let mut hash: u32 = charset.len() as u32;
@@ -83,10 +83,10 @@ pub fn no_op(_bytes: &[u8]) -> String {
#[cfg(test)]
mod tests {
use super::get_charset_decoder;
use super::charset_decoder;
#[test]
fn get_decoder_charset() {
fn decoder_charset() {
let inputs = [
"l8",
//"utf-8",
@@ -99,7 +99,7 @@ mod tests {
for input in inputs {
assert!(
get_charset_decoder(input.as_bytes()).is_some(),
charset_decoder(input.as_bytes()).is_some(),
"Failed for '{}'",
input
);
+2 -2
View File
@@ -18,7 +18,7 @@ pub type DecoderFnc = fn(&[u8]) -> String;
#[cfg(test)]
mod tests {
use super::map::get_charset_decoder;
use super::map::charset_decoder;
#[test]
fn decode_charset() {
@@ -65,7 +65,7 @@ mod tests {
];
for input in inputs {
let decoder = get_charset_decoder(input.0.as_bytes())
let decoder = charset_decoder(input.0.as_bytes())
.expect(&("Failed to find decoder for ".to_owned() + input.0));
assert_eq!(decoder(&input.1), input.2);
+2 -2
View File
@@ -9,7 +9,7 @@
* except according to those terms.
*/
use crate::{decoders::charsets::map::get_charset_decoder, parsers::MessageStream};
use crate::{decoders::charsets::map::charset_decoder, parsers::MessageStream};
use super::DecodeWordFnc;
@@ -81,7 +81,7 @@ impl<'x> MessageStream<'x> {
}
if let Some(bytes) = decode_fnc.and_then(|fnc| fnc(self)) {
if let Some(decoder) = get_charset_decoder(self.get_bytes(charset_start..charset_end)) {
if let Some(decoder) = charset_decoder(self.bytes(charset_start..charset_end)) {
decoder(&bytes).into()
} else {
String::from_utf8(bytes)
+26 -2
View File
@@ -20,7 +20,7 @@ enum QuotedPrintableState {
Hex1,
}
pub fn decode_quoted_printable(bytes: &[u8]) -> Option<Vec<u8>> {
pub fn quoted_printable_decode(bytes: &[u8]) -> Option<Vec<u8>> {
let mut buf = Vec::with_capacity(bytes.len());
let mut state = QuotedPrintableState::None;
@@ -83,6 +83,30 @@ pub fn decode_quoted_printable(bytes: &[u8]) -> Option<Vec<u8>> {
buf.into()
}
#[inline(always)]
pub fn quoted_printable_decode_char(hex1: u8, hex2: u8) -> Option<u8> {
#[cfg(feature = "ludicrous_mode")]
{
let hex1 = unsafe { *HEX_MAP.get_unchecked(hex1 as usize) };
let hex2 = unsafe { *HEX_MAP.get_unchecked(hex2 as usize) };
if hex1 != -1 && hex2 != -1 {
(((hex1 as u8) << 4) | hex2 as u8).into()
} else {
None
}
}
#[cfg(not(feature = "ludicrous_mode"))]
{
let hex1 = HEX_MAP[hex1 as usize];
let hex2 = HEX_MAP[hex2 as usize];
if hex1 != -1 && hex2 != -1 {
(((hex1 as u8) << 4) | hex2 as u8).into()
} else {
None
}
}
}
impl<'x> MessageStream<'x> {
pub fn decode_quoted_printable_mime(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
let mut buf = Vec::with_capacity(128);
@@ -305,7 +329,7 @@ mod tests {
("\n\n", "\n\n"),
] {
assert_eq!(
super::decode_quoted_printable(encoded_str.as_bytes()).unwrap_or_default(),
super::quoted_printable_decode(encoded_str.as_bytes()).unwrap_or_default(),
expected_result.as_bytes(),
"Failed for {:?}",
encoded_str
+169 -162
View File
@@ -158,7 +158,7 @@
//!
//! // Parses addresses (including comments), lists and groups
//! assert_eq!(
//! message.get_from(),
//! message.from(),
//! &HeaderValue::Address(Addr::new(
//! "Art Vandelay (Vandelay Industries)".into(),
//! "art@vandelay.com"
@@ -166,7 +166,7 @@
//! );
//!
//! assert_eq!(
//! message.get_to(),
//! message.to(),
//! &HeaderValue::GroupList(vec![
//! Group::new(
//! "Colleagues",
@@ -183,19 +183,19 @@
//! );
//!
//! assert_eq!(
//! message.get_date().unwrap().to_rfc3339(),
//! message.date().unwrap().to_rfc3339(),
//! "2021-11-20T14:22:01-08:00"
//! );
//!
//! // RFC2047 support for encoded text in message readers
//! assert_eq!(
//! message.get_subject().unwrap(),
//! message.subject().unwrap(),
//! "Why not both importing AND exporting? ☺"
//! );
//!
//! // HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
//! assert_eq!(
//! message.get_html_body(0).unwrap(),
//! message.body_html(0).unwrap(),
//! concat!(
//! "<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ",
//! "focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,",
@@ -205,7 +205,7 @@
//!
//! // HTML parts are converted to plain text (and viceversa) when missing
//! assert_eq!(
//! message.get_text_body(0).unwrap(),
//! message.body_text(0).unwrap(),
//! concat!(
//! "I was thinking about quitting the “exporting” to focus just on the",
//! " “importing”,\nbut then I thought, why not do both? ☺\n"
@@ -214,33 +214,33 @@
//!
//! // Supports nested messages as well as multipart/digest
//! let nested_message = message
//! .get_attachment(0)
//! .attachment(0)
//! .unwrap()
//! .get_message()
//! .message()
//! .unwrap();
//!
//! assert_eq!(
//! nested_message.get_subject().unwrap(),
//! nested_message.subject().unwrap(),
//! "Exporting my book about coffee tables"
//! );
//!
//! // Handles UTF-* as well as many legacy encodings
//! assert_eq!(
//! nested_message.get_text_body(0).unwrap(),
//! nested_message.body_text(0).unwrap(),
//! "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
//! );
//! assert_eq!(
//! nested_message.get_html_body(0).unwrap(),
//! nested_message.body_html(0).unwrap(),
//! "<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
//! );
//!
//! let nested_attachment = nested_message.get_attachment(0).unwrap();
//! let nested_attachment = nested_message.attachment(0).unwrap();
//!
//! assert_eq!(nested_attachment.len(), 42);
//!
//! // Full RFC2231 support for continuations and character sets
//! assert_eq!(
//! nested_attachment.get_attachment_name().unwrap(),
//! nested_attachment.attachment_name().unwrap(),
//! "Book about ☕ tables.gif"
//! );
//!
@@ -792,11 +792,11 @@ impl<'x> HeaderValue<'x> {
}
}
pub fn get_content_type(&self) -> &ContentType<'x> {
pub fn content_type(&self) -> &ContentType<'x> {
match *self {
HeaderValue::ContentType(ref ct) => ct,
_ => panic!(
"HeaderValue::get_content_type called on non-ContentType: {:?}",
"HeaderValue::content_type called on non-ContentType: {:?}",
self
),
}
@@ -918,13 +918,13 @@ pub struct DateTime {
impl<'x> Message<'x> {
/// Returns the root message part
pub fn get_root_part(&self) -> &MessagePart<'x> {
pub fn root_part(&self) -> &MessagePart<'x> {
&self.parts[0]
}
/// Returns a parsed header.
pub fn get_header(&self, header: &str) -> Option<&HeaderValue> {
self.parts[0].headers.get_header(header).map(|h| &h.value)
pub fn header(&self, header: &str) -> Option<&HeaderValue> {
self.parts[0].headers.header(header).map(|h| &h.value)
}
/// Removed a parsed header and returns its value.
@@ -946,20 +946,20 @@ impl<'x> Message<'x> {
}
/// Returns the raw header.
pub fn get_header_raw(&self, header: &str) -> Option<&str> {
pub fn header_raw(&self, header: &str) -> Option<&str> {
self.parts[0]
.headers
.get_header(header)
.header(header)
.and_then(|h| std::str::from_utf8(&self.raw_message[h.offset_start..h.offset_end]).ok())
}
/// Returns an iterator over the RFC headers of this message.
pub fn get_headers(&self) -> &[Header] {
pub fn headers(&self) -> &[Header] {
&self.parts[0].headers
}
/// Returns an iterator over the matching RFC headers of this message.
pub fn get_header_values<'y: 'x>(
pub fn header_values<'y: 'x>(
&'y self,
name: RfcHeader,
) -> impl Iterator<Item = &HeaderValue<'x>> {
@@ -973,7 +973,7 @@ impl<'x> Message<'x> {
}
/// Returns all headers in raw format
pub fn get_headers_raw(&self) -> impl Iterator<Item = (&str, &str)> {
pub fn headers_raw(&self) -> impl Iterator<Item = (&str, &str)> {
self.parts[0].headers.iter().filter_map(move |header| {
Some((
header.name.as_str(),
@@ -984,228 +984,228 @@ impl<'x> Message<'x> {
}
/// Returns the BCC header field
pub fn get_bcc(&self) -> &HeaderValue {
pub fn bcc(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Bcc)
.rfc(&RfcHeader::Bcc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the CC header field
pub fn get_cc(&self) -> &HeaderValue {
pub fn cc(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Cc)
.rfc(&RfcHeader::Cc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Comments header fields
pub fn get_comments(&self) -> &HeaderValue {
pub fn comments(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Comments)
.rfc(&RfcHeader::Comments)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Date header field
pub fn get_date(&self) -> Option<&DateTime> {
pub fn date(&self) -> Option<&DateTime> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Date)
.rfc(&RfcHeader::Date)
.and_then(|header| header.as_datetime_ref())
}
/// Returns the From header field
pub fn get_from(&self) -> &HeaderValue {
pub fn from(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::From)
.rfc(&RfcHeader::From)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all In-Reply-To header fields
pub fn get_in_reply_to(&self) -> &HeaderValue {
pub fn in_reply_to(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::InReplyTo)
.rfc(&RfcHeader::InReplyTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Keywords header fields
pub fn get_keywords(&self) -> &HeaderValue {
pub fn keywords(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Keywords)
.rfc(&RfcHeader::Keywords)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Archive header field
pub fn get_list_archive(&self) -> &HeaderValue {
pub fn list_archive(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListArchive)
.rfc(&RfcHeader::ListArchive)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Help header field
pub fn get_list_help(&self) -> &HeaderValue {
pub fn list_help(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListHelp)
.rfc(&RfcHeader::ListHelp)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-ID header field
pub fn get_list_id(&self) -> &HeaderValue {
pub fn list_id(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListId)
.rfc(&RfcHeader::ListId)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Owner header field
pub fn get_list_owner(&self) -> &HeaderValue {
pub fn list_owner(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListOwner)
.rfc(&RfcHeader::ListOwner)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Post header field
pub fn get_list_post(&self) -> &HeaderValue {
pub fn list_post(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListPost)
.rfc(&RfcHeader::ListPost)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Subscribe header field
pub fn get_list_subscribe(&self) -> &HeaderValue {
pub fn list_subscribe(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListSubscribe)
.rfc(&RfcHeader::ListSubscribe)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Unsubscribe header field
pub fn get_list_unsubscribe(&self) -> &HeaderValue {
pub fn list_unsubscribe(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ListUnsubscribe)
.rfc(&RfcHeader::ListUnsubscribe)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Message-ID header field
pub fn get_message_id(&self) -> Option<&str> {
pub fn message_id(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::MessageId)
.rfc(&RfcHeader::MessageId)
.and_then(|header| header.as_text_ref())
}
/// Returns the MIME-Version header field
pub fn get_mime_version(&self) -> &HeaderValue {
pub fn mime_version(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::MimeVersion)
.rfc(&RfcHeader::MimeVersion)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Received header fields
pub fn get_received(&self) -> &HeaderValue {
pub fn received(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Received)
.rfc(&RfcHeader::Received)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all References header fields
pub fn get_references(&self) -> &HeaderValue {
pub fn references(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::References)
.rfc(&RfcHeader::References)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Reply-To header field
pub fn get_reply_to(&self) -> &HeaderValue {
pub fn reply_to(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ReplyTo)
.rfc(&RfcHeader::ReplyTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-BCC header field
pub fn get_resent_bcc(&self) -> &HeaderValue {
pub fn resent_bcc(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentBcc)
.rfc(&RfcHeader::ResentBcc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-CC header field
pub fn get_resent_cc(&self) -> &HeaderValue {
pub fn resent_cc(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentTo)
.rfc(&RfcHeader::ResentTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Resent-Date header fields
pub fn get_resent_date(&self) -> &HeaderValue {
pub fn resent_date(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentDate)
.rfc(&RfcHeader::ResentDate)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-From header field
pub fn get_resent_from(&self) -> &HeaderValue {
pub fn resent_from(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentFrom)
.rfc(&RfcHeader::ResentFrom)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Resent-Message-ID header fields
pub fn get_resent_message_id(&self) -> &HeaderValue {
pub fn resent_message_id(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentMessageId)
.rfc(&RfcHeader::ResentMessageId)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Sender header field
pub fn get_resent_sender(&self) -> &HeaderValue {
pub fn resent_sender(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentSender)
.rfc(&RfcHeader::ResentSender)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-To header field
pub fn get_resent_to(&self) -> &HeaderValue {
pub fn resent_to(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ResentTo)
.rfc(&RfcHeader::ResentTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Return-Path header fields
pub fn get_return_path(&self) -> &HeaderValue {
pub fn return_path(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ReturnPath)
.rfc(&RfcHeader::ReturnPath)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the return address from either the Return-Path
/// or From header fields
pub fn get_return_address(&self) -> Option<&str> {
match self.parts[0].headers.get_rfc(&RfcHeader::ReturnPath) {
pub fn return_address(&self) -> Option<&str> {
match self.parts[0].headers.rfc(&RfcHeader::ReturnPath) {
Some(HeaderValue::Text(text)) => Some(text.as_ref()),
Some(HeaderValue::TextList(text_list)) => text_list.last().map(|t| t.as_ref()),
_ => match self.parts[0].headers.get_rfc(&RfcHeader::From) {
_ => match self.parts[0].headers.rfc(&RfcHeader::From) {
Some(HeaderValue::Address(addr)) => addr.address.as_deref(),
Some(HeaderValue::AddressList(addr_list)) => {
addr_list.last().and_then(|a| a.address.as_deref())
@@ -1216,48 +1216,48 @@ impl<'x> Message<'x> {
}
/// Returns the Sender header field
pub fn get_sender(&self) -> &HeaderValue {
pub fn sender(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Sender)
.rfc(&RfcHeader::Sender)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Subject header field
pub fn get_subject(&self) -> Option<&str> {
pub fn subject(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::Subject)
.rfc(&RfcHeader::Subject)
.and_then(|header| header.as_text_ref())
}
/// Returns the message thread name or 'base subject' as defined in
/// [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1)
pub fn get_thread_name(&self) -> Option<&str> {
thread_name(self.get_subject()?).into()
pub fn thread_name(&self) -> Option<&str> {
thread_name(self.subject()?).into()
}
/// Returns the To header field
pub fn get_to(&self) -> &HeaderValue {
pub fn to(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::To)
.rfc(&RfcHeader::To)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns a preview of the message body
pub fn get_body_preview(&self, preview_len: usize) -> Option<Cow<'x, str>> {
pub fn body_preview(&self, preview_len: usize) -> Option<Cow<'x, str>> {
if !self.text_body.is_empty() {
preview_text(self.get_text_body(0)?, preview_len).into()
preview_text(self.body_text(0)?, preview_len).into()
} else if !self.html_body.is_empty() {
preview_html(self.get_html_body(0)?, preview_len).into()
preview_html(self.body_html(0)?, preview_len).into()
} else {
None
}
}
/// Returns the transformed contents an inline HTML body part by position
pub fn get_html_body(&'x self, pos: usize) -> Option<Cow<'x, str>> {
/// Returns a message body part as text/plain
pub fn body_html(&'x self, pos: usize) -> Option<Cow<'x, str>> {
let part = self.parts.get(*self.html_body.get(pos)?)?;
match &part.body {
PartType::Html(html) => Some(html.as_ref().into()),
@@ -1266,9 +1266,9 @@ impl<'x> Message<'x> {
}
}
/// Returns the transformed contents an inline text body part by position
pub fn get_text_body(&'x self, pos: usize) -> Option<Cow<'x, str>> {
let part = self.parts.get(*self.html_body.get(pos)?)?;
/// Returns a message body part as text/plain
pub fn body_text(&'x self, pos: usize) -> Option<Cow<'x, str>> {
let part = self.parts.get(*self.text_body.get(pos)?)?;
match &part.body {
PartType::Text(text) => Some(text.as_ref().into()),
PartType::Html(html) => Some(html_to_text(html.as_ref()).into()),
@@ -1277,52 +1277,52 @@ impl<'x> Message<'x> {
}
/// Returns a message part by position
pub fn get_part(&self, pos: usize) -> Option<&MessagePart> {
pub fn part(&self, pos: usize) -> Option<&MessagePart> {
self.parts.get(pos)
}
/// Returns an inline HTML body part by position
pub fn get_html_part(&self, pos: usize) -> Option<&MessagePart> {
pub fn html_part(&self, pos: usize) -> Option<&MessagePart> {
self.parts.get(*self.html_body.get(pos)?)
}
/// Returns an inline text body part by position
pub fn get_text_part(&self, pos: usize) -> Option<&MessagePart> {
pub fn text_part(&self, pos: usize) -> Option<&MessagePart> {
self.parts.get(*self.text_body.get(pos)?)
}
/// Returns an attacment by position
pub fn get_attachment(&self, pos: usize) -> Option<&MessagePart<'x>> {
pub fn attachment(&self, pos: usize) -> Option<&MessagePart<'x>> {
self.parts.get(*self.attachments.get(pos)?)
}
/// Returns the number of plain text body parts
pub fn get_text_body_count(&self) -> usize {
pub fn text_body_count(&self) -> usize {
self.text_body.len()
}
/// Returns the number of HTML body parts
pub fn get_html_body_count(&self) -> usize {
pub fn html_body_count(&self) -> usize {
self.html_body.len()
}
/// Returns the number of attachments
pub fn get_attachment_count(&self) -> usize {
pub fn attachment_count(&self) -> usize {
self.attachments.len()
}
/// Returns an Interator over the text body parts
pub fn get_text_bodies(&'x self) -> BodyPartIterator<'x> {
pub fn text_bodies(&'x self) -> BodyPartIterator<'x> {
BodyPartIterator::new(self, &self.text_body)
}
/// Returns an Interator over the HTML body parts
pub fn get_html_bodies(&'x self) -> BodyPartIterator<'x> {
pub fn html_bodies(&'x self) -> BodyPartIterator<'x> {
BodyPartIterator::new(self, &self.html_body)
}
/// Returns an Interator over the attachments
pub fn get_attachments(&'x self) -> AttachmentIterator<'x> {
pub fn attachments(&'x self) -> AttachmentIterator<'x> {
AttachmentIterator::new(self)
}
@@ -1341,84 +1341,91 @@ impl<'x> Message<'x> {
/// MIME Header field access trait
pub trait MimeHeaders<'x> {
/// Returns the Content-Description field
fn get_content_description(&self) -> Option<&str>;
fn content_description(&self) -> Option<&str>;
/// Returns the Content-Disposition field
fn get_content_disposition(&self) -> Option<&ContentType>;
fn content_disposition(&self) -> Option<&ContentType>;
/// Returns the Content-ID field
fn get_content_id(&self) -> Option<&str>;
fn content_id(&self) -> Option<&str>;
/// Returns the Content-Encoding field
fn get_content_transfer_encoding(&self) -> Option<&str>;
fn content_transfer_encoding(&self) -> Option<&str>;
/// Returns the Content-Type field
fn get_content_type(&self) -> Option<&ContentType>;
fn content_type(&self) -> Option<&ContentType>;
/// Returns the Content-Language field
fn get_content_language(&self) -> &HeaderValue;
fn content_language(&self) -> &HeaderValue;
/// Returns the Content-Location field
fn get_content_location(&self) -> Option<&str>;
fn content_location(&self) -> Option<&str>;
/// Returns the attachment name, if any.
fn get_attachment_name(&self) -> Option<&str> {
self.get_content_disposition()
.and_then(|cd| cd.get_attribute("filename"))
.or_else(|| {
self.get_content_type()
.and_then(|ct| ct.get_attribute("name"))
})
fn attachment_name(&self) -> Option<&str> {
self.content_disposition()
.and_then(|cd| cd.attribute("filename"))
.or_else(|| self.content_type().and_then(|ct| ct.attribute("name")))
}
// Returns true is the content type matches
fn is_content_type(&self, type_: &str, subtype: &str) -> bool {
self.content_type().map_or(false, |ct| {
ct.c_type.eq_ignore_ascii_case(type_)
&& ct
.c_subtype
.as_ref()
.map_or(false, |st| st.eq_ignore_ascii_case(subtype))
})
}
}
impl<'x> MimeHeaders<'x> for Message<'x> {
fn get_content_description(&self) -> Option<&str> {
fn content_description(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentDescription)
.rfc(&RfcHeader::ContentDescription)
.and_then(|header| header.as_text_ref())
}
fn get_content_disposition(&self) -> Option<&ContentType> {
fn content_disposition(&self) -> Option<&ContentType> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentDisposition)
.rfc(&RfcHeader::ContentDisposition)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_id(&self) -> Option<&str> {
fn content_id(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentId)
.rfc(&RfcHeader::ContentId)
.and_then(|header| header.as_text_ref())
}
fn get_content_transfer_encoding(&self) -> Option<&str> {
fn content_transfer_encoding(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentTransferEncoding)
.rfc(&RfcHeader::ContentTransferEncoding)
.and_then(|header| header.as_text_ref())
}
fn get_content_type(&self) -> Option<&ContentType> {
fn content_type(&self) -> Option<&ContentType> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentType)
.rfc(&RfcHeader::ContentType)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_language(&self) -> &HeaderValue {
fn content_language(&self) -> &HeaderValue {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentLanguage)
.rfc(&RfcHeader::ContentLanguage)
.unwrap_or(&HeaderValue::Empty)
}
fn get_content_location(&self) -> Option<&str> {
fn content_location(&self) -> Option<&str> {
self.parts[0]
.headers
.get_rfc(&RfcHeader::ContentLocation)
.rfc(&RfcHeader::ContentLocation)
.and_then(|header| header.as_text_ref())
}
}
impl<'x> MessagePart<'x> {
/// Returns the body part's contents as a `u8` slice
pub fn get_contents(&'x self) -> &'x [u8] {
pub fn contents(&'x self) -> &'x [u8] {
match &self.body {
PartType::Text(text) | PartType::Html(text) => text.as_bytes(),
PartType::Binary(bin) | PartType::InlineBinary(bin) => bin.as_ref(),
@@ -1428,7 +1435,7 @@ impl<'x> MessagePart<'x> {
}
/// Returns the body part's contents as a `str`
pub fn get_text_contents(&'x self) -> Option<&'x str> {
pub fn text_contents(&'x self) -> Option<&'x str> {
match &self.body {
PartType::Text(text) | PartType::Html(text) => text.as_ref().into(),
PartType::Binary(bin) | PartType::InlineBinary(bin) => {
@@ -1440,7 +1447,7 @@ impl<'x> MessagePart<'x> {
}
/// Returns the nested message
pub fn get_message(&'x self) -> Option<&Message<'x>> {
pub fn message(&'x self) -> Option<&Message<'x>> {
if let PartType::Message(message) = &self.body {
Some(message)
} else {
@@ -1449,7 +1456,7 @@ impl<'x> MessagePart<'x> {
}
/// Returns the sub parts ids of a MIME part
pub fn get_sub_parts(&'x self) -> Option<&[MessagePartId]> {
pub fn sub_parts(&'x self) -> Option<&[MessagePartId]> {
if let PartType::Multipart(parts) = &self.body {
Some(parts.as_ref())
} else {
@@ -1545,68 +1552,68 @@ impl<'x> MessagePart<'x> {
impl<'x> fmt::Display for MessagePart<'x> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(self.get_text_contents().unwrap_or("[no contents]"))
fmt.write_str(self.text_contents().unwrap_or("[no contents]"))
}
}
impl<'x> MimeHeaders<'x> for MessagePart<'x> {
fn get_content_description(&self) -> Option<&str> {
fn content_description(&self) -> Option<&str> {
self.headers
.get_rfc(&RfcHeader::ContentDescription)
.rfc(&RfcHeader::ContentDescription)
.and_then(|header| header.as_text_ref())
}
fn get_content_disposition(&self) -> Option<&ContentType> {
fn content_disposition(&self) -> Option<&ContentType> {
self.headers
.get_rfc(&RfcHeader::ContentDisposition)
.rfc(&RfcHeader::ContentDisposition)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_id(&self) -> Option<&str> {
fn content_id(&self) -> Option<&str> {
self.headers
.get_rfc(&RfcHeader::ContentId)
.rfc(&RfcHeader::ContentId)
.and_then(|header| header.as_text_ref())
}
fn get_content_transfer_encoding(&self) -> Option<&str> {
fn content_transfer_encoding(&self) -> Option<&str> {
self.headers
.get_rfc(&RfcHeader::ContentTransferEncoding)
.rfc(&RfcHeader::ContentTransferEncoding)
.and_then(|header| header.as_text_ref())
}
fn get_content_type(&self) -> Option<&ContentType> {
fn content_type(&self) -> Option<&ContentType> {
self.headers
.get_rfc(&RfcHeader::ContentType)
.rfc(&RfcHeader::ContentType)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_language(&self) -> &HeaderValue {
fn content_language(&self) -> &HeaderValue {
self.headers
.get_rfc(&RfcHeader::ContentLanguage)
.rfc(&RfcHeader::ContentLanguage)
.unwrap_or(&HeaderValue::Empty)
}
fn get_content_location(&self) -> Option<&str> {
fn content_location(&self) -> Option<&str> {
self.headers
.get_rfc(&RfcHeader::ContentLocation)
.rfc(&RfcHeader::ContentLocation)
.and_then(|header| header.as_text_ref())
}
}
pub trait GetHeader {
fn get_rfc(&self, name: &RfcHeader) -> Option<&HeaderValue>;
fn get_header(&self, name: &str) -> Option<&Header>;
fn rfc(&self, name: &RfcHeader) -> Option<&HeaderValue>;
fn header(&self, name: &str) -> Option<&Header>;
}
impl<'x> GetHeader for Vec<Header<'x>> {
fn get_rfc(&self, name: &RfcHeader) -> Option<&HeaderValue<'x>> {
fn rfc(&self, name: &RfcHeader) -> Option<&HeaderValue<'x>> {
self.iter()
.rev()
.find(|header| matches!(&header.name, HeaderName::Rfc(rfc_name) if rfc_name == name))
.map(|header| &header.value)
}
fn get_header(&self, name: &str) -> Option<&Header> {
fn header(&self, name: &str) -> Option<&Header> {
self.iter()
.rev()
.find(|header| header.name.as_str().eq_ignore_ascii_case(name))
@@ -1656,24 +1663,24 @@ impl<'x> Iterator for AttachmentIterator<'x> {
fn next(&mut self) -> Option<Self::Item> {
self.pos += 1;
self.message.get_attachment(self.pos as usize)
self.message.attachment(self.pos as usize)
}
}
/// An RFC2047 Content-Type or RFC2183 Content-Disposition MIME header field.
impl<'x> ContentType<'x> {
/// Returns the type
pub fn get_type(&self) -> &str {
pub fn ctype(&self) -> &str {
&self.c_type
}
/// Returns the sub-type
pub fn get_subtype(&self) -> Option<&str> {
pub fn subtype(&self) -> Option<&str> {
self.c_subtype.as_ref()?.as_ref().into()
}
/// Returns an attribute by name
pub fn get_attribute(&self, name: &str) -> Option<&str> {
pub fn attribute(&self, name: &str) -> Option<&str> {
self.attributes
.as_ref()?
.iter()
@@ -1694,7 +1701,7 @@ impl<'x> ContentType<'x> {
}
/// Returns all attributes
pub fn get_attributes(&self) -> Option<&[(Cow<str>, Cow<str>)]> {
pub fn attributes(&self) -> Option<&[(Cow<str>, Cow<str>)]> {
self.attributes.as_deref()
}
+1 -1
View File
@@ -197,7 +197,7 @@ impl Iterator for MessageIterator {
if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
if !name.starts_with('.') {
let internal_date =
match fs::metadata(&path).and_then(|m| m.created()).and_then(|d| {
match fs::metadata(&path).and_then(|m| m.modified()).and_then(|d| {
d.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|e| {
+3 -3
View File
@@ -12,7 +12,7 @@
use std::borrow::Cow;
use crate::{
decoders::{charsets::map::get_charset_decoder, hex::decode_hex},
decoders::{charsets::map::charset_decoder, hex::decode_hex},
parsers::MessageStream,
ContentType, HeaderValue,
};
@@ -188,7 +188,7 @@ impl<'x> ContentTypeParser<'x> {
value = if let Some(decoder) = self
.attr_charset
.as_ref()
.and_then(|c| get_charset_decoder(c.as_bytes()))
.and_then(|c| charset_decoder(c.as_bytes()))
{
decoder(&decoded_bytes).into()
} else {
@@ -243,7 +243,7 @@ impl<'x> ContentTypeParser<'x> {
for (key, _, value) in continuations.drain(..) {
if let Some((_, old_value)) = self.attributes.iter_mut().find(|(name, _)| name == &key)
{
*old_value = format!("{}{}", old_value.to_owned(), value).into();
*old_value = format!("{}{}", old_value, value).into();
} else {
self.attributes.push((key, value));
}
+3 -3
View File
@@ -20,7 +20,7 @@ pub static MONTH: &[&str] = &[
impl DateTime {
/// Parses an RFC822 date
pub fn parse_rfc822(&self, value: &str) -> Option<Self> {
pub fn parse_rfc822(value: &str) -> Option<Self> {
match MessageStream::new(value.as_bytes()).parse_date() {
HeaderValue::DateTime(dt) => dt.into(),
_ => None,
@@ -198,7 +198,7 @@ impl DateTime {
let month = self.month as u32;
let year_base = 4800; /* Before min year, multiple of 400. */
let m_adj = month.wrapping_sub(3); /* March-based month. */
let carry = if m_adj > month { 1 } else { 0 };
let carry = i64::from(m_adj > month);
let adjust = if carry > 0 { 12 } else { 0 };
let y_adj = self.year as i64 + year_base - carry;
let month_days = ((m_adj.wrapping_add(adjust)) * 62719 + 769) / 2048;
@@ -224,7 +224,7 @@ impl DateTime {
let (h, mn, s) = (seconds / 3600, (seconds / 60) % 60, seconds % 60);
DateTime {
year: (y + (if m <= 2 { 1 } else { 0 })) as u16,
year: (y + i64::from(m <= 2)) as u16,
month: m as u8,
day: d as u8,
hour: h as u8,
+2 -2
View File
@@ -29,7 +29,7 @@ impl<'x> MessageStream<'x> {
0 => {
if token_invalid_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
self.get_bytes(token_invalid_start - 1..token_invalid_end),
self.bytes(token_invalid_start - 1..token_invalid_end),
))
} else {
HeaderValue::Empty
@@ -49,7 +49,7 @@ impl<'x> MessageStream<'x> {
is_id_part = false;
if token_start > 0 {
ids.push(String::from_utf8_lossy(
self.get_bytes(token_start - 1..token_end),
self.bytes(token_start - 1..token_end),
));
token_start = 0;
} else {
+2 -2
View File
@@ -22,7 +22,7 @@ impl<'x> MessageStream<'x> {
if !self.try_next_is_space() {
return if token_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
self.get_bytes(token_start - 1..token_end),
self.bytes(token_start - 1..token_end),
))
} else {
HeaderValue::Empty
@@ -99,7 +99,7 @@ Content-Type: multipart/mixed; boundary="festivus";
Here's a message body.
"#;
let message = Message::parse(input).unwrap();
let mut iter = message.get_headers_raw();
let mut iter = message.headers_raw();
assert_eq!(
iter.next().unwrap(),
("From", " Art Vandelay <art@vandelay.com>\n")
+1 -1
View File
@@ -25,7 +25,7 @@ impl<'x> UnstructuredParser<'x> {
self.tokens.push(" ".into());
}
self.tokens.push(String::from_utf8_lossy(
stream.get_bytes(self.token_start - 1..self.token_end),
stream.bytes(self.token_start - 1..self.token_end),
));
if add_space {
+1 -1
View File
@@ -140,7 +140,7 @@ impl<'x> MessageStream<'x> {
}
if token_start != 0 {
let field = self.get_bytes(token_start - 1..token_end);
let field = self.bytes(token_start - 1..token_end);
if (2..=25).contains(&token_len) {
token_hash += token_len + {
+15 -15
View File
@@ -12,7 +12,7 @@
use std::borrow::Cow;
use crate::{
decoders::{charsets::map::get_charset_decoder, DecodeFnc},
decoders::{charsets::map::charset_decoder, DecodeFnc},
ContentType, Encoding, GetHeader, HeaderValue, Message, MessagePart, MessagePartId, PartType,
RfcHeader,
};
@@ -42,17 +42,17 @@ impl Default for MimeType {
}
#[inline(always)]
fn get_mime_type(
fn mime_type(
content_type: Option<&ContentType>,
parent_content_type: &MimeType,
) -> (bool, bool, bool, MimeType) {
if let Some(content_type) = content_type {
match content_type.get_type() {
match content_type.ctype() {
"multipart" => (
true,
false,
false,
match content_type.get_subtype() {
match content_type.subtype() {
Some("mixed") => MimeType::MultipartMixed,
Some("alternative") => MimeType::MultipartAlernative,
Some("related") => MimeType::MultipartRelated,
@@ -60,13 +60,13 @@ fn get_mime_type(
_ => MimeType::Other,
},
),
"text" => match content_type.get_subtype() {
"text" => match content_type.subtype() {
Some("plain") => (false, true, true, MimeType::TextPlain),
Some("html") => (false, true, true, MimeType::TextHtml),
_ => (false, false, true, MimeType::TextOther),
},
"image" | "audio" | "video" => (false, true, false, MimeType::Inline),
"message" if [Some("rfc822"), Some("global")].contains(&content_type.get_subtype()) => {
"message" if [Some("rfc822"), Some("global")].contains(&content_type.subtype()) => {
(false, false, false, MimeType::Message)
}
_ => (false, false, false, MimeType::Other),
@@ -155,15 +155,15 @@ impl<'x> Message<'x> {
state.sub_part_ids.push(message.parts.len());
let content_type = part_headers
.get_rfc(&RfcHeader::ContentType)
.rfc(&RfcHeader::ContentType)
.and_then(|c| c.as_content_type_ref());
let (is_multipart, mut is_inline, mut is_text, mut mime_type) =
get_mime_type(content_type, &state.mime_type);
mime_type(content_type, &state.mime_type);
if is_multipart {
if let Some(mime_boundary) =
content_type.map_or_else(|| None, |f| f.get_attribute("boundary"))
content_type.map_or_else(|| None, |f| f.attribute("boundary"))
{
if stream.seek_next_part(mime_boundary.as_bytes()) {
let part_id = message.parts.len();
@@ -201,7 +201,7 @@ impl<'x> Message<'x> {
}
let (mut encoding, decode_fnc): (Encoding, DecodeFnc) = match part_headers
.get_rfc(&RfcHeader::ContentTransferEncoding)
.rfc(&RfcHeader::ContentTransferEncoding)
{
Some(HeaderValue::Text(encoding)) if encoding.eq_ignore_ascii_case("base64") => {
(Encoding::Base64, MessageStream::decode_base64_mime)
@@ -214,7 +214,7 @@ impl<'x> Message<'x> {
MessageStream::decode_quoted_printable_mime,
)
}
_ => (Encoding::None, MessageStream::get_mime_part),
_ => (Encoding::None, MessageStream::mime_part),
};
if mime_type == MimeType::Message && encoding == Encoding::None {
@@ -270,8 +270,8 @@ impl<'x> Message<'x> {
let body_part = if mime_type != MimeType::Message {
let is_inline = is_inline
&& part_headers
.get_rfc(&RfcHeader::ContentDisposition)
.map_or_else(|| true, |d| !d.get_content_type().is_attachment())
.rfc(&RfcHeader::ContentDisposition)
.map_or_else(|| true, |d| !d.content_type().is_attachment())
&& (state.parts == 1
|| (state.mime_type != MimeType::MultipartRelated
&& (mime_type == MimeType::Inline
@@ -306,8 +306,8 @@ impl<'x> Message<'x> {
let text = match (
bytes,
content_type.and_then(|ct| {
ct.get_attribute("charset")
.and_then(|c| get_charset_decoder(c.as_bytes()))
ct.attribute("charset")
.and_then(|c| charset_decoder(c.as_bytes()))
}),
) {
(Cow::Owned(vec), Some(charset_decoder)) => charset_decoder(&vec).into(),
+3 -3
View File
@@ -58,7 +58,7 @@ impl<'x> MessageStream<'x> {
None
}
pub fn get_mime_part(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
pub fn mime_part(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
let mut last_ch = b'\n';
let mut before_last_ch = 0;
let start_pos = self.offset();
@@ -81,7 +81,7 @@ impl<'x> MessageStream<'x> {
if before_last_ch != b'\n' {
end_pos = self.offset() - boundary.len() - 2;
}
return (end_pos, self.get_bytes(start_pos..end_pos).into());
return (end_pos, self.bytes(start_pos..end_pos).into());
}
before_last_ch = last_ch;
@@ -95,7 +95,7 @@ impl<'x> MessageStream<'x> {
self.restore();
usize::MAX
},
self.get_bytes(start_pos..self.len()).into(),
self.bytes(start_pos..self.len()).into(),
)
}
+1 -1
View File
@@ -104,7 +104,7 @@ impl<'x> MessageStream<'x> {
}
#[inline(always)]
pub fn get_bytes(&self, range: Range<usize>) -> &'x [u8] {
pub fn bytes(&self, range: Range<usize>) -> &'x [u8] {
&self.data[range]
}
+12 -12
View File
@@ -65,7 +65,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_from(),
message.from(),
&HeaderValue::Address(Addr::new(
"Art Vandelay (Vandelay Industries)".into(),
"art@vandelay.com"
@@ -73,7 +73,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_to(),
message.to(),
&HeaderValue::GroupList(vec![
Group::new(
"Colleagues",
@@ -90,17 +90,17 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_date().unwrap().to_rfc3339(),
message.date().unwrap().to_rfc3339(),
"2021-11-20T14:22:01-08:00"
);
assert_eq!(
message.get_subject().unwrap(),
message.subject().unwrap(),
"Why not both importing AND exporting? ☺"
);
assert_eq!(
message.get_html_body(0).unwrap(),
message.body_html(0).unwrap(),
concat!(
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ",
"focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,",
@@ -109,36 +109,36 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
assert_eq!(
message.get_text_body(0).unwrap(),
message.body_text(0).unwrap(),
concat!(
"I was thinking about quitting the “exporting” to focus just on the",
" “importing”,\nbut then I thought, why not do both? ☺\n"
)
);
let nested_message = message.get_attachment(0).unwrap().get_message().unwrap();
let nested_message = message.attachment(0).unwrap().message().unwrap();
assert_eq!(
nested_message.get_subject().unwrap(),
nested_message.subject().unwrap(),
"Exporting my book about coffee tables"
);
assert_eq!(
nested_message.get_text_body(0).unwrap(),
nested_message.body_text(0).unwrap(),
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
assert_eq!(
nested_message.get_html_body(0).unwrap(),
nested_message.body_html(0).unwrap(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = nested_message.get_attachment(0).unwrap();
let nested_attachment = nested_message.attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
assert_eq!(
nested_attachment.get_attachment_name().unwrap(),
nested_attachment.attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
}