Performance tweaks.

This commit is contained in:
Mauro D
2021-10-30 19:01:19 +00:00
parent 337fbb5078
commit 1d3ad277ef
19 changed files with 421 additions and 106 deletions
+2
View File
@@ -1,2 +1,4 @@
/target
/test
perf.*
*.svg
+3
View File
@@ -24,3 +24,6 @@ serde_json = ">=1.0.59"
default = ["multibytedecode", "serialize"]
multibytedecode = ["encoding_rs"]
serialize = ["serde", "serde_bytes"]
[profile.bench]
debug = true
+39 -6
View File
@@ -1,5 +1,5 @@
### Conformed RFCs
## Conformed RFCs
-------------
- [RFC 822 - Standard for ARPA Internet Text Messages](https://datatracker.ietf.org/doc/html/rfc822)
- [RFC 5322 - Internet Message Format](https://datatracker.ietf.org/doc/html/rfc5322)
@@ -16,17 +16,50 @@
- [RFC 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
- [RFC 8621 - The JSON Meta Application Protocol (JMAP) for Mail (Section 4.1.4)](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4)
### Supported Character Sets
## Supported Character Sets
-------------
- UTF-8
- UTF-16, UTF-16BE, UTF-16LE
- UTF-7
- US-ASCII
- ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, ISO-8859-16
- CP1250, CP1251, CP1252, CP1253, CP1254, CP1255, CP1256, CP1257, CP1258
- KOI8-R, KOI8_U
- ISO-8859-1
- ISO-8859-2
- ISO-8859-3
- ISO-8859-4
- ISO-8859-5
- ISO-8859-6
- ISO-8859-7
- ISO-8859-8
- ISO-8859-9
- ISO-8859-10
- ISO-8859-13
- ISO-8859-14
- ISO-8859-15
- ISO-8859-16
- CP1250
- CP1251
- CP1252
- CP1253
- CP1254
- CP1255
- CP1256
- CP1257
- CP1258
- KOI8-R
- KOI8_U
- MACINTOSH
- IBM850
- TIS-620
- SHIFT_JIS, BIG5, EUC-JP, EUC-KR, GB18030, GBK, ISO-2022-JP, WINDOWS-874, IBM-866 (supported via the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs))
Supported character sets via the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs):
- SHIFT_JIS
- BIG5
- EUC-JP
- EUC-KR
- GB18030
- GBK
- ISO-2022-JP
- WINDOWS-874
- IBM-866
+113
View File
@@ -0,0 +1,113 @@
#![feature(test)]
extern crate test;
use std::{fs, path::PathBuf};
use test::Bencher;
fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
println!("Benchmarking {}...\n", name);
let mut test_data = Vec::new();
for test_suite in ["rfc", "legacy", "thirdparty", "malformed"] {
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_dir.push("tests");
test_dir.push(test_suite);
let mut bench_count = 0;
for file_name in fs::read_dir(&test_dir).unwrap() {
let file_name = file_name.as_ref().unwrap().path();
if file_name.extension().map_or(false, |e| e == "txt") {
let input = fs::read(&file_name).unwrap();
let mut pos = 0;
for sep_pos in 0..input.len() {
if input[sep_pos..sep_pos + SEPARATOR.len()].eq(SEPARATOR) {
pos = sep_pos;
break;
}
}
assert!(
pos > 0,
"Failed to find separator in test file '{}'.",
file_name.display()
);
test_data.push(Vec::from(&input[0..pos]));
bench_count += 1;
}
}
assert!(
bench_count > 0,
"Did not find any benchmarks to run in folder {}.",
test_dir.display()
);
}
b.iter(|| {
for test_msg in &test_data {
let input_str = String::from_utf8_lossy(&test_msg);
let mut input_bytes = test_msg.clone();
fnc(&mut input_bytes[..], &input_str);
}
});
}
#[bench]
fn bench_stalwart(b: &mut Bencher) {
bench_all_samples(b, "stalwart_mail_parser", |bytes, _str| {
mail_parser::Message::parse(bytes);
});
}
/*
// These libraries do not support all RFCs and might be faster
// on the benchmarks as they skip certain encoded parts or fail
// while trying to parse the messages.
// Also no body conversion between HTML/text is done by these.
// email = "0.0.21"
// email-format = "0.8"
// email-parser = "0.5.0"
// mailparse = "0.13"
#[bench]
fn bench_mailparse(b: &mut Bencher) {
bench_all_samples(b, "mailparse", |bytes, _str| {
mailparse::parse_mail(bytes).unwrap();
});
}
#[bench]
fn bench_email_parser(b: &mut Bencher) {
bench_all_samples(b, "email_parser", |bytes, _str| {
email_parser::prelude::parse_message(bytes).unwrap();
});
}
#[bench]
fn benchmark_email(b: &mut Bencher) {
bench_all_samples(b, "email", |_bytes, str| {
email::rfc5322::Rfc5322Parser::new(str).consume_message();
});
}
#[bench]
fn bench_email_format(b: &mut Bencher) {
use email_format::rfc5322::Parsable;
bench_all_samples(b, "email_format", |bytes, _str| {
email_format::Email::parse(bytes).unwrap();
});
}
*/
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
perf record -F max --call-graph dwarf target/release/mail-parser
perf script | inferno-collapse-perf | inferno-flamegraph > flamegraph.svg
+2 -2
View File
@@ -49,8 +49,8 @@ impl<'x> Base64Decoder<'x> for MessageStream<'x> {
while read_pos < data_len {
let ch = (*data).get_unchecked(read_pos);
read_pos += 1;
if match_count < boundary.len() {
if !success {
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
+6 -1
View File
@@ -11,7 +11,12 @@
use std::borrow::Cow;
use super::{DecoderFnc, multi_byte::*, single_byte::*, utf::{decoder_utf16, decoder_utf16_be, decoder_utf16_le, decoder_utf7, decoder_utf8}};
use super::{
multi_byte::*,
single_byte::*,
utf::{decoder_utf16, decoder_utf16_be, decoder_utf16_le, decoder_utf7, decoder_utf8},
DecoderFnc,
};
pub fn get_charset_decoder<'x>(charset: &[u8]) -> Option<DecoderFnc<'x>> {
if (2..=45).contains(&charset.len()) {
+2 -2
View File
@@ -31,7 +31,7 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
let mut hash = entity.len() as u32;
/* Safe because ENTITY_HASH's size is 260 (u8::MAX + 5)
and ENTITY_MAP's size is 18016 (18079 - 64 + 1) */
and ENTITY_MAP's size is 18016 (18079 - 64 + 1) */
debug_assert_eq!(ENTITY_HASH.len(), u8::MAX as usize + 5);
debug_assert_eq!(ENTITY_MAP.len(), 18079 - 64 + 1);
@@ -70,7 +70,7 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
}
// Safe because the input string is tokenized by ASCII chars, therefore the resulting
// u8 array is UTF-8 safe.
// u8 array is UTF-8 safe.
result.push_str(unsafe { std::str::from_utf8_unchecked(token) });
}
+1 -1
View File
@@ -13,5 +13,5 @@ pub mod base64;
pub mod charsets;
pub mod encoded_word;
pub mod hex;
pub mod quoted_printable;
pub mod html;
pub mod quoted_printable;
+1 -1
View File
@@ -60,7 +60,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
let ch = *(*data).get_unchecked(read_pos);
read_pos += 1;
if match_count < boundary.len() {
if !success {
if ch == *boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
+200
View File
@@ -250,3 +250,203 @@ pub struct DateTime {
tz_hour: u32,
tz_minute: u32,
}
pub trait MimeFieldGet<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>>;
fn get_content_disposition(&self) -> Option<&ContentType<'x>>;
fn get_content_id(&self) -> Option<&Cow<'x, str>>;
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>>;
fn get_content_type(&self) -> Option<&ContentType<'x>>;
}
impl<'x> Message<'x> {
pub fn get_bcc(&self) -> &Address<'x> {
&self.header.bcc
}
pub fn get_cc(&self) -> &Address<'x> {
&self.header.cc
}
pub fn get_comments(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.comments.as_ref()
}
pub fn get_date(&self) -> Option<&DateTime> {
self.header.date.as_ref()
}
pub fn get_from(&self) -> &Address<'x> {
&self.header.from
}
pub fn get_in_reply_to(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.in_reply_to.as_ref()
}
pub fn get_keywords(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.keywords.as_ref()
}
pub fn get_list_archive(&self) -> &Address<'x> {
&self.header.list_archive
}
pub fn get_list_help(&self) -> &Address<'x> {
&self.header.list_help
}
pub fn get_list_id(&self) -> &Address<'x> {
&self.header.list_id
}
pub fn get_list_owner(&self) -> &Address<'x> {
&self.header.list_owner
}
pub fn get_list_post(&self) -> &Address<'x> {
&self.header.list_post
}
pub fn get_list_subscribe(&self) -> &Address<'x> {
&self.header.list_subscribe
}
pub fn get_list_unsubscribe(&self) -> &Address<'x> {
&self.header.list_unsubscribe
}
pub fn get_message_id(&self) -> Option<&Cow<'x, str>> {
self.header.message_id.as_ref()
}
pub fn get_mime_version(&self) -> Option<&Cow<'x, str>> {
self.header.mime_version.as_ref()
}
pub fn get_received(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.received.as_ref()
}
pub fn get_references(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.references.as_ref()
}
pub fn get_reply_to(&self) -> &Address<'x> {
&self.header.reply_to
}
pub fn get_resent_bcc(&self) -> &Address<'x> {
&self.header.bcc
}
pub fn get_resent_cc(&self) -> &Address<'x> {
&self.header.resent_to
}
pub fn get_resent_date(&self) -> Option<&Vec<DateTime>> {
self.header.resent_date.as_ref()
}
pub fn get_resent_from(&self) -> &Address<'x> {
&self.header.resent_from
}
pub fn get_resent_message_id(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.resent_message_id.as_ref()
}
pub fn get_resent_sender(&self) -> &Address<'x> {
&self.header.resent_sender
}
pub fn get_resent_to(&self) -> &Address<'x> {
&self.header.resent_to
}
pub fn get_return_path(&self) -> Option<&Vec<Cow<'x, str>>> {
self.header.return_path.as_ref()
}
pub fn get_sender(&self) -> &Address<'x> {
&self.header.sender
}
pub fn get_subject(&self) -> Option<&Cow<'x, str>> {
self.header.subject.as_ref()
}
pub fn get_to(&self) -> &Address<'x> {
&self.header.to
}
pub fn get_header(&self, name: &str) -> Option<&Vec<Cow<'x, str>>> {
self.header.others.get(name)
}
}
impl<'x> MimeFieldGet<'x> for Message<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.header.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.header.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.header.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.header.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.header.content_type.as_ref()
}
}
impl<'x> MimeFieldGet<'x> for MimeHeader<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.content_type.as_ref()
}
}
impl<'x> MimeFieldGet<'x> for MessageHeader<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.content_type.as_ref()
}
}
+4 -1
View File
@@ -11,7 +11,10 @@
use std::borrow::Cow;
use crate::{Addr, Address, Group, decoders::encoded_word::parse_encoded_word, parsers::message_stream::MessageStream};
use crate::{
decoders::encoded_word::parse_encoded_word, parsers::message_stream::MessageStream, Addr,
Address, Group,
};
impl<'x> Default for Address<'x> {
fn default() -> Self {
+1 -1
View File
@@ -11,7 +11,7 @@
use std::fmt;
use crate::{DateTime, parsers::message_stream::MessageStream};
use crate::{parsers::message_stream::MessageStream, DateTime};
impl DateTime {
pub fn to_iso8601(&self) -> String {
+2 -11
View File
@@ -148,12 +148,7 @@ mod tests {
),
(
"=?iso-8859-1?q?this is some text?=, in, a, list, \n",
vec![
"this is some text",
"in",
"a",
"list",
],
vec!["this is some text", "in", "a", "list"],
),
(
concat!(
@@ -177,11 +172,7 @@ mod tests {
),
(
"ハロー・ワールド, and also, ascii terms\n",
vec![
"ハロー・ワールド",
"and also",
"ascii terms",
],
vec!["ハロー・ワールド", "and also", "ascii terms"],
),
];
+15 -53
View File
@@ -11,14 +11,18 @@
use std::borrow::Cow;
use crate::{Address, ContentType, DateTime, MessageHeader, MimeHeader};
use crate::{Address, DateTime, MessageHeader, MimeFieldGet, MimeHeader};
use self::{address::parse_address, id::parse_id, list::parse_comma_separared, raw::{parse_and_ignore, parse_raw}, unstructured::parse_unstructured};
use super::{
message_stream::MessageStream,
use self::{
address::parse_address,
id::parse_id,
list::parse_comma_separared,
raw::{parse_and_ignore, parse_raw},
unstructured::parse_unstructured,
};
use super::message_stream::MessageStream;
pub mod address;
pub mod content_type;
pub mod date;
@@ -27,7 +31,10 @@ pub mod list;
pub mod raw;
pub mod unstructured;
pub trait MessageField<'x> {
pub trait MessageField<'x>: FieldSet<'x> + MimeFieldGet<'x> {}
impl<'x, T: FieldSet<'x> + MimeFieldGet<'x>> MessageField<'x> for T {}
pub trait FieldSet<'x> {
fn set_date(&mut self, stream: &MessageStream<'x>);
fn set_sender(&mut self, stream: &MessageStream<'x>);
fn set_received(&mut self, stream: &MessageStream<'x>);
@@ -64,14 +71,9 @@ pub trait MessageField<'x> {
fn set_list_unsubscribe(&mut self, stream: &MessageStream<'x>);
fn set_mime_version(&mut self, stream: &MessageStream<'x>);
fn set_unsupported(&mut self, stream: &MessageStream<'x>, name: &'x [u8]);
fn get_content_description(&self) -> Option<&Cow<'x, str>>;
fn get_content_disposition(&self) -> Option<&ContentType<'x>>;
fn get_content_id(&self) -> Option<&Cow<'x, str>>;
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>>;
fn get_content_type(&self) -> Option<&ContentType<'x>>;
}
impl<'x> MessageField<'x> for MessageHeader<'x> {
impl<'x> FieldSet<'x> for MessageHeader<'x> {
fn set_date(&mut self, stream: &MessageStream<'x>) {
self.date = self::date::parse_date(stream, false);
}
@@ -223,29 +225,9 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
fn set_content_disposition(&mut self, stream: &MessageStream<'x>) {
self.content_disposition = self::content_type::parse_content_type(stream);
}
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.content_type.as_ref()
}
}
impl<'x> MessageField<'x> for MimeHeader<'x> {
impl<'x> FieldSet<'x> for MimeHeader<'x> {
fn set_date(&mut self, stream: &MessageStream<'x>) {
parse_and_ignore(stream);
}
@@ -389,26 +371,6 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
fn set_content_disposition(&mut self, stream: &MessageStream<'x>) {
self.content_disposition = self::content_type::parse_content_type(stream);
}
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.content_type.as_ref()
}
}
pub fn parse_date<'x>(header: &mut dyn MessageField<'x>, stream: &MessageStream<'x>) {
+2 -4
View File
@@ -9,11 +9,9 @@
* except according to those terms.
*/
use crate::{MessageHeader, MimeHeader, parsers::message_stream::MessageStream};
use crate::{parsers::message_stream::MessageStream, MessageHeader, MimeHeader};
use super::fields::{
parse_unsupported, MessageField,
};
use super::fields::{parse_unsupported, MessageField};
impl<'x> MessageHeader<'x> {
pub fn new() -> MessageHeader<'x> {
+12 -12
View File
@@ -9,21 +9,21 @@
* except according to those terms.
*/
use std::borrow::{Cow};
use std::borrow::Cow;
use crate::{AttachmentPart, BinaryPart, BodyPart, ContentType, Message, MessageHeader, MimeHeader, TextPart, decoders::{
base64::Base64Decoder,
charsets::map::{decoder_default, get_charset_decoder},
html::{html_to_text, text_to_html},
quoted_printable::QuotedPrintableDecoder,
}};
use super::{
fields::{MessageField},
header::{parse_headers},
message_stream::MessageStream,
use crate::{
decoders::{
base64::Base64Decoder,
charsets::map::{decoder_default, get_charset_decoder},
html::{html_to_text, text_to_html},
quoted_printable::QuotedPrintableDecoder,
},
AttachmentPart, BinaryPart, BodyPart, ContentType, Message, MessageHeader, MimeHeader,
TextPart,
};
use super::{fields::MessageField, header::parse_headers, message_stream::MessageStream};
#[derive(Debug, PartialEq)]
enum MimeType {
MultipartMixed,
+6 -8
View File
@@ -145,7 +145,7 @@ impl<'x> MessageStream<'x> {
if match_count == boundary.len() {
let is_boundary_end = self.is_boundary_end(pos);
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
if is_boundary_end {
let match_pos = pos - match_count;
*stream_pos = pos;
@@ -221,12 +221,10 @@ impl<'x> MessageStream<'x> {
#[inline(always)]
pub fn is_boundary_end(&self, pos: usize) -> bool {
matches!(unsafe { (*self.data.get()).get(pos..) }, Some([b'\n', ..])
| Some([b'-', b'-', ..])
| Some([b'\r', b'\n', ..])
| Some([b' ' | b'\t', ..])
| Some([])
| None)
matches!(
unsafe { (*self.data.get()).get(pos..) },
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
)
}
pub fn skip_multipart_end(&self) -> bool {
@@ -239,7 +237,7 @@ impl<'x> MessageStream<'x> {
if !(*byte).is_ascii_whitespace() {
return false;
}
}
}
*pos += 2;
true
}
+6 -3
View File
@@ -1,8 +1,11 @@
use mail_parser::Message;
use mail_parser::{Message, MimeFieldGet};
#[test]
fn test_mail_parser() {
let mut input = "pepe".to_string();
let result = Message::parse(unsafe{input.as_bytes_mut()});
let mut input = "test".to_string();
let message = Message::parse(unsafe{input.as_bytes_mut()});
message.get_content_id();
message.get_subject();
}