From 439041724739e45b0faabdbd01c0c8189053b3fd Mon Sep 17 00:00:00 2001 From: Mauro D Date: Sat, 8 Oct 2022 17:50:08 +0000 Subject: [PATCH] Added ludicrous mode and header parsing helper functions. --- CHANGELOG.md | 1 + Cargo.toml | 1 + src/decoders/base64.rs | 67 +++++++++++++++++++++++ src/decoders/charsets/map.rs | 36 +++++++++++-- src/decoders/html.rs | 60 +++++++++++++++++---- src/decoders/quoted_printable.rs | 37 +++++++++++-- src/lib.rs | 60 ++++++++++++++++++++- src/parsers/header.rs | 91 +++++++++++++++++++++++++++++--- 8 files changed, 329 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 005272b..345774d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ mail-parser 0.6.2 ================================ - Base64/QuotedPrintable decoding optimizations. +- Added "ludicrous mode" Cargo option to use some unsafe code for additional performance. mail-parser 0.6.1 ================================ diff --git a/Cargo.toml b/Cargo.toml index fb0e3db..8450c2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ chrono = "0.4" default = ["serde_support", "full_encoding"] full_encoding = ["encoding_rs"] serde_support = ["serde"] +ludicrous_mode = [] [profile.bench] debug = true diff --git a/src/decoders/base64.rs b/src/decoders/base64.rs index 490753e..33fc627 100644 --- a/src/decoders/base64.rs +++ b/src/decoders/base64.rs @@ -20,6 +20,13 @@ pub fn decode_base64(bytes: &[u8]) -> Option> { let mut buf = Vec::with_capacity(bytes.len() / 4 * 3); for &ch in bytes { + #[cfg(feature = "ludicrous_mode")] + let val = unsafe { + *BASE64_MAP + .get_unchecked(byte_count as usize) + .get_unchecked(ch as usize) + }; + #[cfg(not(feature = "ludicrous_mode"))] let val = BASE64_MAP[byte_count as usize][ch as usize]; if val < 0x01ffffff { @@ -31,16 +38,31 @@ pub fn decode_base64(bytes: &[u8]) -> Option> { chunk |= val; if byte_count == 0 { + #[cfg(feature = "ludicrous_mode")] + unsafe { + buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3)); + } + #[cfg(not(feature = "ludicrous_mode"))] 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)); + } + #[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)); + } + #[cfg(not(feature = "ludicrous_mode"))] buf.extend_from_slice(&chunk.to_le_bytes()[0..2]); byte_count = 0; } @@ -74,7 +96,15 @@ pub fn decode_base64_mime<'x>( while let Some(&ch) = iter.next() { pos += 1; + #[cfg(feature = "ludicrous_mode")] + let val = unsafe { + *BASE64_MAP + .get_unchecked(byte_count as usize) + .get_unchecked(ch as usize) + }; + #[cfg(not(feature = "ludicrous_mode"))] let val = BASE64_MAP[byte_count as usize][ch as usize]; + if val < 0x01ffffff { byte_count = (byte_count + 1) & 3; @@ -84,6 +114,11 @@ pub fn decode_base64_mime<'x>( chunk |= val; if byte_count == 0 { + #[cfg(feature = "ludicrous_mode")] + unsafe { + buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3)); + } + #[cfg(not(feature = "ludicrous_mode"))] buf.extend_from_slice(&chunk.to_le_bytes()[0..3]); } } @@ -91,10 +126,20 @@ pub fn decode_base64_mime<'x>( 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; } 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; } @@ -160,10 +205,20 @@ pub fn decode_base64_word(bytes: &[u8]) -> (usize, Vec) { 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; } 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; } @@ -190,6 +245,13 @@ pub fn decode_base64_word(bytes: &[u8]) -> (usize, Vec) { } b' ' | b'\t' | b'\r' => (), _ => { + #[cfg(feature = "ludicrous_mode")] + let val = unsafe { + *BASE64_MAP + .get_unchecked(byte_count as usize) + .get_unchecked(ch as usize) + }; + #[cfg(not(feature = "ludicrous_mode"))] let val = BASE64_MAP[byte_count as usize][ch as usize]; if val < 0x01ffffff { @@ -201,6 +263,11 @@ pub fn decode_base64_word(bytes: &[u8]) -> (usize, Vec) { chunk |= val; if byte_count == 0 { + #[cfg(feature = "ludicrous_mode")] + unsafe { + buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3)); + } + #[cfg(not(feature = "ludicrous_mode"))] buf.extend_from_slice(&chunk.to_le_bytes()[0..3]); } } diff --git a/src/decoders/charsets/map.rs b/src/decoders/charsets/map.rs index 360cd33..1d235e8 100644 --- a/src/decoders/charsets/map.rs +++ b/src/decoders/charsets/map.rs @@ -29,19 +29,47 @@ pub fn get_charset_decoder(charset: &[u8]) -> Option { }; l_charset[pos] = ch; if let 0 | 3 | 6 | 7 | 8 | 9 = pos { - hash += CH_HASH[ch as usize]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *CH_HASH.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + CH_HASH[ch as usize] + }; } if pos == charset.len() - 1 { - hash += CH_HASH[ch as usize]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *CH_HASH.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + CH_HASH[ch as usize] + }; } } if (7..=764).contains(&hash) { let hash = (hash - 7) as usize; - let ch_map = CH_MAP[hash]; + let ch_map = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *CH_MAP.get_unchecked(hash) + } + #[cfg(not(feature = "ludicrous_mode"))] + CH_MAP[hash] + }; if l_charset[..charset.len()].eq(ch_map) { - return Some(FNC_MAP[hash]); + return Some({ + #[cfg(feature = "ludicrous_mode")] + unsafe { + *FNC_MAP.get_unchecked(hash) + } + #[cfg(not(feature = "ludicrous_mode"))] + FNC_MAP[hash] + }); } } } diff --git a/src/decoders/html.rs b/src/decoders/html.rs index 289d076..64661c0 100644 --- a/src/decoders/html.rs +++ b/src/decoders/html.rs @@ -33,29 +33,71 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) { debug_assert_eq!(ENTITY_HASH.len(), u8::MAX as usize + 5); debug_assert_eq!(ENTITY_MAP.len(), 18079 - 64 + 1); - for (pos, ch) in entity.iter().enumerate() { + for (pos, &ch) in entity.iter().enumerate() { match pos { 0 | 5 | 6 | 9 | 11 => { - hash += ENTITY_HASH[*ch as usize]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_HASH.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_HASH[ch as usize] + }; } 1 => { - hash += ENTITY_HASH[*ch as usize + 4]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_HASH.get_unchecked(ch as usize + 4) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_HASH[ch as usize + 4] + }; } 2 | 4 => { - hash += ENTITY_HASH[*ch as usize + 1]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_HASH.get_unchecked(ch as usize + 1) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_HASH[ch as usize + 1] + }; } 3 => { - hash += ENTITY_HASH[*ch as usize + 3]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_HASH.get_unchecked(ch as usize + 3) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_HASH[ch as usize + 3] + }; } _ => (), } if pos == entity.len() - 1 { - hash += ENTITY_HASH[*ch as usize]; + hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_HASH.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_HASH[ch as usize] + }; } } if (64..=18079).contains(&hash) { - entity_code = ENTITY_MAP[(hash - 64) as usize]; + entity_code = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *ENTITY_MAP.get_unchecked((hash - 64) as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + ENTITY_MAP[(hash - 64) as usize] + }; } } @@ -221,12 +263,12 @@ pub fn text_to_html(input: &str) -> String { result.extend_from_slice(b""); - for ch in input { + for &ch in input { match ch { b'\n' => result.extend_from_slice(b"
"), b'<' => result.extend_from_slice(b"<"), b'\r' => (), - _ => result.push(*ch), + _ => result.push(ch), } } result.extend_from_slice(b""); diff --git a/src/decoders/quoted_printable.rs b/src/decoders/quoted_printable.rs index 98b69f2..85c4408 100644 --- a/src/decoders/quoted_printable.rs +++ b/src/decoders/quoted_printable.rs @@ -48,7 +48,15 @@ pub fn decode_quoted_printable(bytes: &[u8]) -> Option> { buf.push(ch); } QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; + hex1 = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HEX_MAP.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + HEX_MAP[ch as usize] + }; + if hex1 != -1 { state = QuotedPrintableState::Hex1; } else { @@ -56,6 +64,9 @@ pub fn decode_quoted_printable(bytes: &[u8]) -> Option> { } } QuotedPrintableState::Hex1 => { + #[cfg(feature = "ludicrous_mode")] + let hex2 = unsafe { *HEX_MAP.get_unchecked(ch as usize) }; + #[cfg(not(feature = "ludicrous_mode"))] let hex2 = HEX_MAP[ch as usize]; state = QuotedPrintableState::None; @@ -131,7 +142,14 @@ pub fn decode_quoted_printable_mime<'x>( buf.push(ch); } QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; + hex1 = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HEX_MAP.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + HEX_MAP[ch as usize] + }; if hex1 != -1 { state = QuotedPrintableState::Hex1; } else { @@ -139,6 +157,9 @@ pub fn decode_quoted_printable_mime<'x>( } } QuotedPrintableState::Hex1 => { + #[cfg(feature = "ludicrous_mode")] + let hex2 = unsafe { *HEX_MAP.get_unchecked(ch as usize) }; + #[cfg(not(feature = "ludicrous_mode"))] let hex2 = HEX_MAP[ch as usize]; state = QuotedPrintableState::None; @@ -216,7 +237,14 @@ pub fn decode_quoted_printable_word(bytes: &[u8]) -> (usize, Vec) { buf.push(ch); } QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; + hex1 = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HEX_MAP.get_unchecked(ch as usize) + } + #[cfg(not(feature = "ludicrous_mode"))] + HEX_MAP[ch as usize] + }; if hex1 != -1 { state = QuotedPrintableState::Hex1; } else { @@ -225,6 +253,9 @@ pub fn decode_quoted_printable_word(bytes: &[u8]) -> (usize, Vec) { } } QuotedPrintableState::Hex1 => { + #[cfg(feature = "ludicrous_mode")] + let hex2 = unsafe { *HEX_MAP.get_unchecked(ch as usize) }; + #[cfg(not(feature = "ludicrous_mode"))] let hex2 = HEX_MAP[ch as usize]; state = QuotedPrintableState::None; diff --git a/src/lib.rs b/src/lib.rs index 2051fc9..16f95ec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -248,14 +248,15 @@ //! println!("{}", serde_json::to_string_pretty(&message).unwrap()); //! println!("{}", serde_yaml::to_string(&message).unwrap()); //!``` -#[forbid(unsafe_code)] pub mod decoders; pub mod mailbox; pub mod parsers; use std::{ borrow::Cow, + convert::TryInto, fmt::{self, Display}, + slice::Iter, }; use decoders::html::{html_to_text, text_to_html}; @@ -551,7 +552,7 @@ pub enum RfcHeader { ListPost = 34, ListSubscribe = 35, ListUnsubscribe = 36, -} +} // Note: Do not add new entries without updating HDR* tables impl RfcHeader { pub fn as_str(&self) -> &'static str { @@ -1187,6 +1188,53 @@ impl<'x> Message<'x> { pub fn get_attachments(&'x self) -> AttachmentIterator<'x> { AttachmentIterator::new(self) } + + /// Returns am iterator that yields children message parts recursively + pub fn get_subparts_recursive<'z: 'x>( + &'z self, + from_part_id: MessagePartId, + ) -> Option> { + if let Some(PartType::Multipart(subparts)) = self.parts.get(from_part_id).map(|p| &p.body) { + Some(SubpartIterator::new(self, subparts.iter())) + } else { + None + } + } +} + +pub struct SubpartIterator<'x> { + message: &'x Message<'x>, + iter: Iter<'x, usize>, + iter_stack: Vec>, +} + +impl<'x> SubpartIterator<'x> { + pub(crate) fn new(message: &'x Message<'x>, iter: Iter<'x, usize>) -> Self { + SubpartIterator { + message, + iter, + iter_stack: Vec::new(), + } + } + + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> Option<&MessagePart<'x>> { + loop { + if let Some(part_id) = self.iter.next() { + let subpart = self.message.parts.get(*part_id)?; + if let PartType::Multipart(subparts) = &subpart.body { + self.iter_stack + .push(std::mem::replace(&mut self.iter, subparts.iter())); + } + return Some(subpart); + } + if let Some(prev_iter) = self.iter_stack.pop() { + self.iter = prev_iter; + } else { + return None; + } + } + } } /// MIME Header field access trait @@ -1620,3 +1668,11 @@ impl From for Cow<'_, str> { Cow::Borrowed(header.as_str()) } } + +impl<'x> TryInto> for &'x [u8] { + type Error = (); + + fn try_into(self) -> Result, Self::Error> { + Message::parse(self).ok_or(()) + } +} diff --git a/src/parsers/header.rs b/src/parsers/header.rs index f84d244..fd9535d 100644 --- a/src/parsers/header.rs +++ b/src/parsers/header.rs @@ -41,7 +41,15 @@ pub fn parse_headers<'x>(headers: &mut Vec>, stream: &mut MessageStre match result { HeaderParserResult::Rfc(name) => { - let (_, parser) = HDR_PARSER[name as usize]; + let (_, parser) = { + #[cfg(feature = "ludicrous_mode")] + unsafe { + HDR_PARSER.get_unchecked(name as usize) + } + + #[cfg(not(feature = "ludicrous_mode"))] + HDR_PARSER[name as usize] + }; let from_offset = stream.pos; headers.push(Header { @@ -78,7 +86,7 @@ pub fn parse_header_name(data: &[u8]) -> (usize, HeaderParserResult) { let mut last_ch: u8 = 0; let mut bytes_read: usize = 0; - for ch in data.iter() { + for &ch in data.iter() { bytes_read += 1; match ch { @@ -91,17 +99,25 @@ pub fn parse_header_name(data: &[u8]) -> (usize, HeaderParserResult) { return (bytes_read - 1, HeaderParserResult::Lf); } _ => { - if !(*ch).is_ascii_whitespace() { + if !ch.is_ascii_whitespace() { if token_start == 0 { token_start = bytes_read; token_end = token_start; } else { token_end = bytes_read; - last_ch = *ch; + last_ch = ch; } if let 0 | 9 = token_len { - token_hash += HDR_HASH[(*ch).to_ascii_lowercase() as usize] as usize; + token_hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HDR_HASH.get_unchecked(ch.to_ascii_lowercase() as usize) + } + + #[cfg(not(feature = "ludicrous_mode"))] + HDR_HASH[ch.to_ascii_lowercase() as usize] + } as usize; } token_len += 1; } @@ -113,7 +129,15 @@ pub fn parse_header_name(data: &[u8]) -> (usize, HeaderParserResult) { let field = &data[token_start - 1..token_end]; if (2..=25).contains(&token_len) { - token_hash += token_len + HDR_HASH[last_ch.to_ascii_lowercase() as usize] as usize; + token_hash += token_len + { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize) + } + + #[cfg(not(feature = "ludicrous_mode"))] + HDR_HASH[last_ch.to_ascii_lowercase() as usize] + } as usize; if (4..=72).contains(&token_hash) { let token_hash = token_hash - 4; @@ -132,12 +156,67 @@ pub fn parse_header_name(data: &[u8]) -> (usize, HeaderParserResult) { } } +impl RfcHeader { + pub fn parse(data: &str) -> Option { + let mut token_hash: usize = 0; + let mut last_ch: u8 = 0; + let data_ = data.as_bytes(); + + for (pos, &ch) in data_.iter().enumerate() { + if let 0 | 9 = pos { + token_hash += { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HDR_HASH.get_unchecked(ch.to_ascii_lowercase() as usize) + } + + #[cfg(not(feature = "ludicrous_mode"))] + HDR_HASH[ch.to_ascii_lowercase() as usize] + } as usize; + } + last_ch = ch; + } + + if (2..=25).contains(&data.len()) { + token_hash += data.len() + { + #[cfg(feature = "ludicrous_mode")] + unsafe { + *HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize) + } + + #[cfg(not(feature = "ludicrous_mode"))] + HDR_HASH[last_ch.to_ascii_lowercase() as usize] + } as usize; + + if (4..=72).contains(&token_hash) { + let token_hash = token_hash - 4; + + if data_.eq_ignore_ascii_case(HDR_NAMES[token_hash]) { + return HDR_MAP[token_hash].into(); + } + } + } + + None + } +} + impl From for u8 { fn from(name: RfcHeader) -> Self { name as u8 } } +impl<'x> From> for HeaderName<'x> { + fn from(result: HeaderParserResult<'x>) -> Self { + match result { + HeaderParserResult::Rfc(header) => HeaderName::Rfc(header), + HeaderParserResult::Other(header) => HeaderName::Other(header), + _ => HeaderName::Other("".into()), + } + } +} + #[cfg(test)] mod tests { use crate::{parsers::header::parse_header_name, RfcHeader};