Hashing with hashify + cosmetic fixes

This commit is contained in:
mdecimus
2025-01-25 17:45:23 +01:00
parent bc6a5b1e94
commit 8b2ad20bf3
21 changed files with 407 additions and 1947 deletions
+13
View File
@@ -1,3 +1,16 @@
mail-parser 0.10.0
================================
- Perfect hashing using `hashify` crate rather than static `gperf` generated code.
- Added `DkimSignature`, `ArcAuthenticationResults`, `ArcMessageSignature` and `ArcSeal` headers.
- `HeaderName` is non-exhaustive.
- Parse obsolete timezones (#95).
- Fix: Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96).
- Fix: Multiline quoted continuations (closes #92).
- Fix: Deserialize (#93).
- Retain mbox IO errors (#91).
- Hide concrete type behind impl type (#94).
- Removed `ludicrous` feature, the Rust compiler is smart enough to optimize array lookups.
mail-parser 0.9.4
================================
- Flexible parsing of charset names (#85).
+5 -2
View File
@@ -1,7 +1,7 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
version = "0.9.4"
version = "0.10.0"
edition = "2021"
authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT"
@@ -13,6 +13,7 @@ readme = "README.md"
resolver = "2"
[dependencies]
hashify = { path = "../hashify" }
encoding_rs = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
@@ -27,7 +28,9 @@ chrono = "0.4"
default = ["full_encoding"]
full_encoding = ["encoding_rs"]
serde_support = ["serde"]
ludicrous_mode = []
[profile.bench]
debug = true
[lib]
doctest = false
View File
+1 -1
View File
@@ -277,4 +277,4 @@ at your option.
## Copyright
Copyright (C) 2020-2022, Stalwart Labs Ltd.
Copyright (C) 2020, Stalwart Labs LLC
+3 -3
View File
@@ -73,7 +73,7 @@ impl<'x> Address<'x> {
}
/// Returns an iterator over the addresses in the list, or the addresses in the groups.
pub fn iter(&self) -> Box<dyn DoubleEndedIterator<Item = &Addr<'x>> + '_> {
pub fn iter(&self) -> Box<dyn DoubleEndedIterator<Item = &Addr<'x>> + '_ + Sync + Send> {
match self {
Address::List(list) => Box::new(list.iter()),
Address::Group(group) => {
@@ -88,13 +88,13 @@ impl<'x> Address<'x> {
Address::List(list) => list.iter().any(|a| {
a.address
.as_ref()
.map_or(false, |a| a.eq_ignore_ascii_case(addr))
.is_some_and(|a| a.eq_ignore_ascii_case(addr))
}),
Address::Group(group) => group.iter().any(|group| {
group.addresses.iter().any(|a| {
a.address
.as_ref()
.map_or(false, |a| a.eq_ignore_ascii_case(addr))
.is_some_and(|a| a.eq_ignore_ascii_case(addr))
})
}),
}
+28 -4
View File
@@ -156,10 +156,10 @@ impl<'x> HeaderValue<'x> {
}
}
pub fn as_text_list(&self) -> Option<Vec<&str>> {
pub fn as_text_list(&self) -> Option<&[Cow<'x, str>]> {
match *self {
HeaderValue::Text(ref s) => Some(vec![s.as_ref()]),
HeaderValue::TextList(ref l) => Some(l.iter().map(|l| l.as_ref()).collect()),
HeaderValue::Text(ref s) => Some(std::slice::from_ref(s)),
HeaderValue::TextList(ref l) => Some(l.as_slice()),
_ => None,
}
}
@@ -321,6 +321,10 @@ impl HeaderName<'_> {
HeaderName::ListPost => HeaderName::ListPost,
HeaderName::ListSubscribe => HeaderName::ListSubscribe,
HeaderName::ListUnsubscribe => HeaderName::ListUnsubscribe,
HeaderName::ArcAuthenticationResults => HeaderName::ArcAuthenticationResults,
HeaderName::ArcMessageSignature => HeaderName::ArcMessageSignature,
HeaderName::ArcSeal => HeaderName::ArcSeal,
HeaderName::DkimSignature => HeaderName::DkimSignature,
}
}
@@ -364,6 +368,10 @@ impl HeaderName<'_> {
HeaderName::ListPost => HeaderName::ListPost,
HeaderName::ListSubscribe => HeaderName::ListSubscribe,
HeaderName::ListUnsubscribe => HeaderName::ListUnsubscribe,
HeaderName::ArcAuthenticationResults => HeaderName::ArcAuthenticationResults,
HeaderName::ArcMessageSignature => HeaderName::ArcMessageSignature,
HeaderName::ArcSeal => HeaderName::ArcSeal,
HeaderName::DkimSignature => HeaderName::DkimSignature,
}
}
@@ -420,6 +428,10 @@ impl HeaderName<'_> {
HeaderName::ListPost => "List-Post",
HeaderName::ListSubscribe => "List-Subscribe",
HeaderName::ListUnsubscribe => "List-Unsubscribe",
HeaderName::ArcAuthenticationResults => "ARC-Authentication-Results",
HeaderName::ArcMessageSignature => "ARC-Message-Signature",
HeaderName::ArcSeal => "ARC-Seal",
HeaderName::DkimSignature => "DKIM-Signature",
HeaderName::Other(_) => "",
}
}
@@ -463,6 +475,10 @@ impl HeaderName<'_> {
HeaderName::ListPost => "List-Post".len(),
HeaderName::ListSubscribe => "List-Subscribe".len(),
HeaderName::ListUnsubscribe => "List-Unsubscribe".len(),
HeaderName::ArcAuthenticationResults => "ARC-Authentication-Results".len(),
HeaderName::ArcMessageSignature => "ARC-Message-Signature".len(),
HeaderName::ArcSeal => "ARC-Seal".len(),
HeaderName::DkimSignature => "DKIM-Signature".len(),
HeaderName::Other(other) => other.len(),
}
}
@@ -530,6 +546,10 @@ impl HeaderName<'_> {
HeaderName::ListSubscribe => 35,
HeaderName::ListUnsubscribe => 36,
HeaderName::Other(_) => 37,
HeaderName::ArcAuthenticationResults => 38,
HeaderName::ArcMessageSignature => 39,
HeaderName::ArcSeal => 40,
HeaderName::DkimSignature => 41,
}
}
}
@@ -804,7 +824,7 @@ impl<'x> ContentType<'x> {
pub fn has_attribute(&self, name: &str) -> bool {
self.attributes
.as_ref()
.map_or(false, |attr| attr.iter().any(|(key, _)| key == name))
.is_some_and(|attr| attr.iter().any(|(key, _)| key == name))
}
/// Returns ```true``` if the Content-Disposition type is "attachment"
@@ -1007,6 +1027,10 @@ impl From<u8> for HeaderName<'_> {
34 => HeaderName::ListPost,
35 => HeaderName::ListSubscribe,
36 => HeaderName::ListUnsubscribe,
38 => HeaderName::ArcAuthenticationResults,
39 => HeaderName::ArcMessageSignature,
40 => HeaderName::ArcSeal,
41 => HeaderName::DkimSignature,
_ => HeaderName::Other("".into()),
}
}
+5 -5
View File
@@ -93,7 +93,7 @@ impl<'x> Message<'x> {
pub fn header_values(
&self,
name: impl Into<HeaderName<'x>>,
) -> impl Iterator<Item = &HeaderValue<'x>> {
) -> impl Iterator<Item = &HeaderValue<'x>> + Sync + Send {
let name = name.into();
self.parts[0].headers.iter().filter_map(move |header| {
if header.name == name {
@@ -105,7 +105,7 @@ impl<'x> Message<'x> {
}
/// Returns all headers in raw format
pub fn headers_raw(&self) -> impl Iterator<Item = (&str, &str)> {
pub fn headers_raw(&self) -> impl Iterator<Item = (&str, &str)> + Sync + Send {
self.parts[0].headers.iter().filter_map(move |header| {
Some((
header.name.as_str(),
@@ -449,17 +449,17 @@ impl<'x> Message<'x> {
}
/// Returns an Interator over the text body parts
pub fn text_bodies(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> {
pub fn text_bodies(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> + Sync + Send {
BodyPartIterator::new(self, &self.text_body)
}
/// Returns an Interator over the HTML body parts
pub fn html_bodies(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> {
pub fn html_bodies(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> + Sync + Send {
BodyPartIterator::new(self, &self.html_body)
}
/// Returns an Interator over the attachments
pub fn attachments(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> {
pub fn attachments(&self) -> impl Iterator<Item = &'_ MessagePart<'_>> + Sync + Send {
AttachmentIterator::new(self)
}
-66
View File
@@ -29,13 +29,6 @@ pub fn base64_decode_stream<'x>(
let mut buf = Vec::with_capacity(stream_len / 4 * 3);
for &ch in stream {
#[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 {
@@ -47,11 +40,6 @@ pub fn base64_decode_stream<'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]);
}
}
@@ -59,20 +47,10 @@ pub fn base64_decode_stream<'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;
}
@@ -103,13 +81,6 @@ impl<'x> MessageStream<'x> {
self.checkpoint();
while let Some(&ch) = self.next() {
#[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 {
@@ -121,11 +92,6 @@ impl<'x> MessageStream<'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]);
}
}
@@ -133,20 +99,10 @@ impl<'x> MessageStream<'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;
}
@@ -215,20 +171,10 @@ impl<'x> MessageStream<'x> {
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;
}
@@ -253,13 +199,6 @@ impl<'x> MessageStream<'x> {
}
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 {
@@ -271,11 +210,6 @@ impl<'x> MessageStream<'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]);
}
}
+162 -1187
View File
File diff suppressed because it is too large Load Diff
+18 -9
View File
@@ -24,7 +24,8 @@ fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> String {
result
}
pub fn decoder_shift_jis(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_shift_jis(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(SHIFT_JIS.new_decoder(), bytes)
@@ -36,7 +37,8 @@ pub fn decoder_shift_jis(bytes: &[u8]) -> String {
}
}
pub fn decoder_big5(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_big5(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(BIG5.new_decoder(), bytes)
@@ -48,7 +50,8 @@ pub fn decoder_big5(bytes: &[u8]) -> String {
}
}
pub fn decoder_euc_jp(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_euc_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_JP.new_decoder(), bytes)
@@ -60,7 +63,8 @@ pub fn decoder_euc_jp(bytes: &[u8]) -> String {
}
}
pub fn decoder_euc_kr(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_euc_kr(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_KR.new_decoder(), bytes)
@@ -72,7 +76,8 @@ pub fn decoder_euc_kr(bytes: &[u8]) -> String {
}
}
pub fn decoder_gb18030(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_gb18030(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GB18030.new_decoder(), bytes)
@@ -84,7 +89,8 @@ pub fn decoder_gb18030(bytes: &[u8]) -> String {
}
}
pub fn decoder_gbk(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_gbk(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GBK.new_decoder(), bytes)
@@ -96,7 +102,8 @@ pub fn decoder_gbk(bytes: &[u8]) -> String {
}
}
pub fn decoder_iso2022_jp(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso2022_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(ISO_2022_JP.new_decoder(), bytes)
@@ -108,7 +115,8 @@ pub fn decoder_iso2022_jp(bytes: &[u8]) -> String {
}
}
pub fn decoder_windows874(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_windows874(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(WINDOWS_874.new_decoder(), bytes)
@@ -120,7 +128,8 @@ pub fn decoder_windows874(bytes: &[u8]) -> String {
}
}
pub fn decoder_ibm866(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_ibm866(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(IBM866.new_decoder(), bytes)
+56 -33
View File
@@ -13,11 +13,6 @@ fn single_byte_decoder(table: &[char], bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len() * 2);
for byte in bytes {
#[cfg(feature = "ludicrous_mode")]
unsafe {
result.push(*table.get_unchecked(*byte as usize));
}
#[cfg(not(feature = "ludicrous_mode"))]
result.push(table[*byte as usize]);
}
@@ -25,115 +20,143 @@ fn single_byte_decoder(table: &[char], bytes: &[u8]) -> String {
result
}
pub fn decoder_iso_8859_1(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_1(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_1, bytes)
}
pub fn decoder_iso_8859_2(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_2(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_2, bytes)
}
pub fn decoder_iso_8859_3(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_3(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_3, bytes)
}
pub fn decoder_iso_8859_4(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_4(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_4, bytes)
}
pub fn decoder_iso_8859_5(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_5(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_5, bytes)
}
pub fn decoder_iso_8859_6(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_6(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_6, bytes)
}
pub fn decoder_iso_8859_7(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_7(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_7, bytes)
}
pub fn decoder_iso_8859_8(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_8(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_8, bytes)
}
pub fn decoder_iso_8859_9(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_9(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_9, bytes)
}
pub fn decoder_iso_8859_10(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_10(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_10, bytes)
}
pub fn decoder_iso_8859_13(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_13(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_13, bytes)
}
pub fn decoder_iso_8859_14(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_14(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_14, bytes)
}
pub fn decoder_iso_8859_15(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_15(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_15, bytes)
}
pub fn decoder_iso_8859_16(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_iso_8859_16(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_16, bytes)
}
pub fn decoder_cp1250(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1250(bytes: &[u8]) -> String {
single_byte_decoder(CP1250, bytes)
}
pub fn decoder_cp1251(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1251(bytes: &[u8]) -> String {
single_byte_decoder(CP1251, bytes)
}
pub fn decoder_cp1252(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1252(bytes: &[u8]) -> String {
single_byte_decoder(CP1252, bytes)
}
pub fn decoder_cp1253(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1253(bytes: &[u8]) -> String {
single_byte_decoder(CP1253, bytes)
}
pub fn decoder_cp1254(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1254(bytes: &[u8]) -> String {
single_byte_decoder(CP1254, bytes)
}
pub fn decoder_cp1255(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1255(bytes: &[u8]) -> String {
single_byte_decoder(CP1255, bytes)
}
pub fn decoder_cp1256(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1256(bytes: &[u8]) -> String {
single_byte_decoder(CP1256, bytes)
}
pub fn decoder_cp1257(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1257(bytes: &[u8]) -> String {
single_byte_decoder(CP1257, bytes)
}
pub fn decoder_cp1258(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_cp1258(bytes: &[u8]) -> String {
single_byte_decoder(CP1258, bytes)
}
pub fn decoder_koi8_r(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_koi8_r(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_R, bytes)
}
pub fn decoder_koi8_u(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_koi8_u(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_U, bytes)
}
pub fn decoder_macintosh(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_macintosh(bytes: &[u8]) -> String {
single_byte_decoder(MACINTOSH, bytes)
}
pub fn decoder_ibm_850(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_ibm_850(bytes: &[u8]) -> String {
single_byte_decoder(IBM850, bytes)
}
pub fn decoder_tis_620(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_tis_620(bytes: &[u8]) -> String {
single_byte_decoder(TIS_620, bytes)
}
+6 -9
View File
@@ -34,7 +34,7 @@ fn add_utf16_bytes(state: &mut Utf7DecoderState, n_bytes: usize) {
}
}
pub fn decoder_utf7(bytes: &[u8]) -> String {
pub(crate) fn decoder_utf7(bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len());
let mut byte_count: u8 = 0;
let mut in_b64 = false;
@@ -111,16 +111,18 @@ fn decoder_utf16_(bytes: &[u8], fnc: fn([u8; 2]) -> u16) -> String {
}
}
pub fn decoder_utf16_le(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_utf16_le(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_le_bytes)
}
pub fn decoder_utf16_be(bytes: &[u8]) -> String {
#[inline(always)]
pub(crate) fn decoder_utf16_be(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_be_bytes)
}
#[allow(clippy::type_complexity)]
pub fn decoder_utf16(bytes: &[u8]) -> String {
pub(crate) fn decoder_utf16(bytes: &[u8]) -> String {
// Read BOM
let (bytes, fnc): (&[u8], fn([u8; 2]) -> u16) = match bytes.get(0..2) {
Some([0xfe, 0xff]) => (bytes.get(2..).unwrap_or(&[]), u16::from_be_bytes),
@@ -131,11 +133,6 @@ pub fn decoder_utf16(bytes: &[u8]) -> String {
decoder_utf16_(bytes, fnc)
}
// Not currently used at the moment
pub fn decoder_utf8(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
#[cfg(test)]
mod tests {
use crate::decoders::charsets::utf::decoder_utf7;
+6 -48
View File
@@ -36,68 +36,26 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
for (pos, &ch) in entity.iter().enumerate() {
match pos {
0 | 5 | 6 | 9 | 11 => {
hash += {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*ENTITY_HASH.get_unchecked(ch as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
ENTITY_HASH[ch as usize]
};
hash += ENTITY_HASH[ch as usize];
}
1 => {
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]
};
hash += ENTITY_HASH[ch as usize + 4];
}
2 | 4 => {
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]
};
hash += ENTITY_HASH[ch as usize + 1];
}
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]
};
hash += ENTITY_HASH[ch as usize + 3];
}
_ => (),
}
if pos == entity.len() - 1 {
hash += {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*ENTITY_HASH.get_unchecked(ch as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
ENTITY_HASH[ch as usize]
};
hash += ENTITY_HASH[ch as usize];
}
}
if (64..=18079).contains(&hash) {
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]
};
entity_code = ENTITY_MAP[(hash - 64) as usize];
}
}
+7 -54
View File
@@ -61,14 +61,7 @@ pub fn quoted_printable_decode(bytes: &[u8]) -> Option<Vec<u8>> {
buf.push(ch);
}
QuotedPrintableState::Eq => {
hex1 = {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*HEX_MAP.get_unchecked(ch as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
HEX_MAP[ch as usize]
};
hex1 = HEX_MAP[ch as usize];
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
@@ -77,9 +70,6 @@ pub fn quoted_printable_decode(bytes: &[u8]) -> Option<Vec<u8>> {
}
}
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;
@@ -99,26 +89,10 @@ pub fn quoted_printable_decode(bytes: &[u8]) -> Option<Vec<u8>> {
#[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
}
}
let hex1 = HEX_MAP[hex1 as usize];
let hex2 = HEX_MAP[hex2 as usize];
(hex1 != -1 && hex2 != -1).then_some(((hex1 as u8) << 4) | hex2 as u8)
}
impl<'x> MessageStream<'x> {
@@ -184,14 +158,7 @@ impl<'x> MessageStream<'x> {
buf.push(ch);
}
QuotedPrintableState::Eq => {
hex1 = {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*HEX_MAP.get_unchecked(ch as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
HEX_MAP[ch as usize]
};
hex1 = HEX_MAP[ch as usize];
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else if !ch.is_ascii_whitespace() {
@@ -200,9 +167,6 @@ impl<'x> MessageStream<'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;
@@ -276,14 +240,7 @@ impl<'x> MessageStream<'x> {
buf.push(ch);
}
QuotedPrintableState::Eq => {
hex1 = {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*HEX_MAP.get_unchecked(ch as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
HEX_MAP[ch as usize]
};
hex1 = HEX_MAP[ch as usize];
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
@@ -292,11 +249,7 @@ impl<'x> MessageStream<'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;
if hex2 != -1 {
buf.push(((hex1 as u8) << 4) | hex2 as u8);
+10 -242
View File
@@ -1,4 +1,3 @@
#![deny(rust_2018_idioms)]
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
@@ -9,245 +8,9 @@
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
//! # mail-parser
//!
//! _mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the
//! Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as many other [internet messaging RFCs](#conformed-rfcs).
//!
//! It also supports decoding messages in [41 different character sets](#supported-character-sets) including obsolete formats such as UTF-7.
//! All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese
//! and Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
//!
//! In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which
//! states that an implementation must be conservative in its sending behavior and liberal in its receiving behavior. This means that
//! _mail-parser_ will make a best effort to parse non-conformant e-mail messages as long as these do not deviate too much from the standard.
//!
//! Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library
//! conforms to [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4) and provides a more human-friendly
//! representation of the message contents consisting of just text body parts, html body parts and attachments. Additionally, conversion to/from
//! HTML and plain text inline body parts is done automatically when the _alternative_ version is missing.
//!
//! Performance and memory safety were two important factors while designing _mail-parser_:
//!
//! - **Zero-copy**: Practically all strings returned by this library are `Cow<str>` references to the input raw message.
//! - **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)).
//! - **Fast parsing** of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function).
//! - Written in **100% safe** Rust with no external dependencies.
//! - Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and thoroughly [tested with MIRI](#testing-fuzzing--benchmarking).
//! - **Battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
//! - Used in production environments worldwide by [Stalwart Mail Server](https://github.com/stalwartlabs/mail-server).
//!
//! Jump to the [example](#usage-example).
//!
//! ## 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)
//! - [RFC 2045 - Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies](https://datatracker.ietf.org/doc/html/rfc2045)
//! - [RFC 2046 - Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types](https://datatracker.ietf.org/doc/html/rfc2046)
//! - [RFC 2047 - MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text](https://datatracker.ietf.org/doc/html/rfc2047)
//! - [RFC 2048 - Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures](https://datatracker.ietf.org/doc/html/rfc2048)
//! - [RFC 2049 - Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples](https://datatracker.ietf.org/doc/html/rfc2049)
//! - [RFC 2231 - MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations](https://datatracker.ietf.org/doc/html/rfc2231)
//! - [RFC 2557 - MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)](https://datatracker.ietf.org/doc/html/rfc2557)
//! - [RFC 2183 - Communicating Presentation Information in Internet Messages: The Content-Disposition Header Field](https://datatracker.ietf.org/doc/html/rfc2183)
//! - [RFC 2392 - Content-ID and Message-ID Uniform Resource Locators](https://datatracker.ietf.org/doc/html/rfc2392)
//! - [RFC 3282 - Content Language Headers](https://datatracker.ietf.org/doc/html/rfc3282)
//! - [RFC 6532 - Internationalized Email Headers](https://datatracker.ietf.org/doc/html/rfc6532)
//! - [RFC 2152 - UTF-7 - A Mail-Safe Transformation Format of Unicode](https://datatracker.ietf.org/doc/html/rfc2152)
//! - [RFC 2369 - The Use of URLs as Meta-Syntax for Core Mail List Commands and their Transport through Message Header Fields](https://datatracker.ietf.org/doc/html/rfc2369)
//! - [RFC 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
//! - [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
//! - [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)
//! - [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1)
//!
//! ## 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
//! - MACINTOSH
//! - IBM850
//! - TIS-620
//!
//! 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
//!
//! ## Usage Example
//!
//! ```
//! use mail_parser::*;
//!
//! let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
//!To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends:
//! jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;
//!Date: Sat, 20 Nov 2021 14:22:01 -0800
//!Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?=
//!Content-Type: multipart/mixed; boundary="festivus";
//!
//!--festivus
//!Content-Type: text/html; charset="us-ascii"
//!Content-Transfer-Encoding: base64
//!
//!PGh0bWw+PHA+SSB3YXMgdGhpbmtpbmcgYWJvdXQgcXVpdHRpbmcgdGhlICZsZHF1bztle
//!HBvcnRpbmcmcmRxdW87IHRvIGZvY3VzIGp1c3Qgb24gdGhlICZsZHF1bztpbXBvcnRpbm
//!cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8
//!gJiN4MjYzQTs8L3A+PC9odG1sPg==
//!--festivus
//!Content-Type: message/rfc822
//!
//!From: "Cosmo Kramer" <kramer@kramerica.com>
//!Subject: Exporting my book about coffee tables
//!Content-Type: multipart/mixed; boundary="giddyup";
//!
//!--giddyup
//!Content-Type: text/plain; charset="utf-16"
//!Content-Transfer-Encoding: quoted-printable
//!
//!=FF=FE=0C!5=D8"=DD5=D8)=DD5=D8-=DD =005=D8*=DD5=D8"=DD =005=D8"=
//!=DD5=D85=DD5=D8-=DD5=D8,=DD5=D8/=DD5=D81=DD =005=D8*=DD5=D86=DD =
//!=005=D8=1F=DD5=D8,=DD5=D8,=DD5=D8(=DD =005=D8-=DD5=D8)=DD5=D8"=
//!=DD5=D8=1E=DD5=D80=DD5=D8"=DD!=00
//!--giddyup
//!Content-Type: image/gif; name*1="about "; name*0="Book ";
//! name*2*=utf-8''%e2%98%95 tables.gif
//!Content-Transfer-Encoding: Base64
//!Content-Disposition: attachment
//!
//!R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
//!--giddyup--
//!--festivus--
//!"#;
//!
//! let message = MessageParser::default().parse(input).unwrap();
//!
//! // Parses addresses (including comments), lists and groups
//! assert_eq!(
//! message.from().unwrap().first().unwrap(),
//! &Addr::new(
//! "Art Vandelay (Vandelay Industries)".into(),
//! "art@vandelay.com"
//! )
//! );
//!
//! assert_eq!(
//! message.to().unwrap().as_group().unwrap(),
//! &[
//! Group::new(
//! "Colleagues",
//! vec![Addr::new("James Smythe".into(), "james@vandelay.com")]
//! ),
//! Group::new(
//! "Friends",
//! vec![
//! Addr::new(None, "jane@example.com"),
//! Addr::new("John Smîth".into(), "john@example.com"),
//! ]
//! )
//! ]
//! );
//!
//! assert_eq!(
//! message.date().unwrap().to_rfc3339(),
//! "2021-11-20T14:22:01-08:00"
//! );
//!
//! // RFC2047 support for encoded text in message readers
//! assert_eq!(
//! 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.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,",
//! " why not do both? &#x263A;</p></html>"
//! )
//! );
//!
//! // HTML parts are converted to plain text (and viceversa) when missing
//! assert_eq!(
//! 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"
//! )
//! );
//!
//! // Supports nested messages as well as multipart/digest
//! let nested_message = message
//! .attachment(0)
//! .unwrap()
//! .message()
//! .unwrap();
//!
//! assert_eq!(
//! nested_message.subject().unwrap(),
//! "Exporting my book about coffee tables"
//! );
//!
//! // Handles UTF-* as well as many legacy encodings
//! assert_eq!(
//! nested_message.body_text(0).unwrap(),
//! "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
//! );
//! assert_eq!(
//! nested_message.body_html(0).unwrap(),
//! "<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
//! );
//!
//! 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.attachment_name().unwrap(),
//! "Book about ☕ tables.gif"
//! );
//!
//! // Integrates with Serde
//! println!("{}", serde_json::to_string_pretty(&message).unwrap());
//!```
#![doc = include_str!("../README.md")]
#![deny(rust_2018_idioms)]
#[forbid(unsafe_code)]
pub mod core;
pub mod decoders;
pub mod mailbox;
@@ -402,7 +165,11 @@ pub struct Header<'x> {
#[derive(Debug, Clone, PartialOrd, Ord)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde_support", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum HeaderName<'x> {
ArcAuthenticationResults,
ArcMessageSignature,
ArcSeal,
Subject,
From,
To,
@@ -426,6 +193,7 @@ pub enum HeaderName<'x> {
ContentTransferEncoding,
ContentType,
ContentDisposition,
DkimSignature,
ResentTo,
ResentFrom,
ResentBcc,
@@ -635,12 +403,12 @@ pub trait MimeHeaders<'x> {
}
// Returns true is the content type matches
fn is_content_type(&self, type_: &str, subtype: &str) -> bool {
self.content_type().map_or(false, |ct| {
self.content_type().is_some_and(|ct| {
ct.c_type.eq_ignore_ascii_case(type_)
&& ct
.c_subtype
.as_ref()
.map_or(false, |st| st.eq_ignore_ascii_case(subtype))
.is_some_and(|st| st.eq_ignore_ascii_case(subtype))
})
}
}
+11 -10
View File
@@ -453,17 +453,18 @@ impl<'x> MessageStream<'x> {
break;
}
}
match buf.as_ref() {
b"EDT" => -4,
b"EST" => -5,
b"CDT" => -5,
b"CST" => -6,
b"MDT" => -6,
b"MST" => -7,
b"PDT" => -7,
b"PST" => -8,
_ => 0,
hashify::map! { buf.as_ref(),
"EDT" => -4,
"EST" => -5,
"CDT" => -5,
"CST" => -6,
"MDT" => -6,
"MST" => -7,
"PDT" => -7,
"PST" => -8,
}
.unwrap_or(0)
}
}
-21
View File
@@ -566,22 +566,6 @@ impl<'x> Iterator for Tokenizer<'x, '_> {
let text = std::str::from_utf8(self.stream.bytes(start_pos..self.stream.offset() - 1))
.unwrap_or_default();
/*println!(
"({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, 0x{:x}) => Token::{},",
n_alpha,
n_digit,
n_hex,
n_dot,
n_at,
n_other,
n_colon,
n_plus,
n_minus,
n_utf,
hash,
text
);*/
let token = match (
n_alpha, n_digit, n_hex, n_dot, n_at, n_other, n_colon, n_plus, n_minus, n_utf, hash,
) {
@@ -760,11 +744,6 @@ impl<'x> Iterator for Tokenizer<'x, '_> {
}
};
/*println!("{:?} => {}", token, text);
if let Some(token) = &self.next_token {
println!("{:?}", token.token);
}*/
TokenData {
text,
token,
+13 -15
View File
@@ -9,12 +9,13 @@
* except according to those terms.
*/
static RE_PREFIXES: &[&str] = &[
"re", "res", "sv", "antw", "ref", "aw", "απ", "השב", "vá", "r", "rif", "bls", "odp", "ynt",
"atb", "رد", "回复", "转发",
];
fn is_re_prefix(prefix: &str) -> bool {
hashify::set! {prefix.as_bytes(), "re", "res", "sv", "antw", "ref", "aw", "απ", "השב", "vá", "r", "rif", "bls", "odp", "ynt",
"atb", "رد", "回复", "转发",}
}
static FWD_PREFIXES: &[&str] = &[
fn is_fwd_prefix(prefix: &str) -> bool {
hashify::set! {prefix.as_bytes(),
"fwd",
"fw",
"rv",
@@ -37,7 +38,8 @@ static FWD_PREFIXES: &[&str] = &[
"إعادة توجيه",
"回覆",
"轉寄",
];
}
}
pub fn thread_name(text: &str) -> &str {
let mut token_start = 0;
@@ -63,9 +65,7 @@ pub fn thread_name(text: &str) -> &str {
token_end = pos;
}
let prefix = text[token_start..token_end].to_lowercase();
if RE_PREFIXES.contains(&prefix.as_ref())
|| FWD_PREFIXES.contains(&prefix.as_ref())
{
if is_re_prefix(prefix.as_ref()) || is_fwd_prefix(prefix.as_ref()) {
seen_header = true;
} else {
break;
@@ -98,9 +98,7 @@ pub fn thread_name(text: &str) -> &str {
token_end = pos;
}
let prefix = text[token_start..token_end].to_lowercase();
if !RE_PREFIXES.contains(&prefix.as_ref())
&& !FWD_PREFIXES.contains(&prefix.as_ref())
{
if !is_re_prefix(prefix.as_ref()) && !is_fwd_prefix(prefix.as_ref()) {
break;
}
} else {
@@ -115,10 +113,10 @@ pub fn thread_name(text: &str) -> &str {
}
let prefix = text[token_start..token_end].to_lowercase();
if FWD_PREFIXES.contains(&prefix.as_ref()) {
if is_fwd_prefix(prefix.as_ref()) {
token_found = false;
seen_blob_header = true;
} else if seen_blob_header && RE_PREFIXES.contains(&prefix.as_ref()) {
} else if seen_blob_header && is_re_prefix(prefix.as_ref()) {
token_found = false;
} else {
in_blob_ignore = true;
@@ -175,7 +173,7 @@ pub fn trim_trailing_fwd(text: &str) -> &str {
if in_parentheses {
in_parentheses = false;
if fwd_end - pos > 2
&& FWD_PREFIXES.contains(&text[pos + 1..fwd_end].to_lowercase().as_ref())
&& is_fwd_prefix(text[pos + 1..fwd_end].to_lowercase().as_ref())
{
text_end = pos;
trim_end = true;
+61 -236
View File
@@ -78,7 +78,7 @@ impl<'x> MessageStream<'x> {
HeaderName::ContentType | HeaderName::ContentDisposition => {
self.parse_content_type()
}
HeaderName::Other(_) => self.parse_raw(),
_ => self.parse_raw(),
}
} else {
(conf
@@ -104,8 +104,8 @@ impl<'x> MessageStream<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut token_len: usize = 0;
let mut token_hash: usize = 0;
let mut last_ch: u8 = 0;
let mut header = [0u8; 30];
while let Some(&ch) = self.next() {
match ch {
@@ -124,19 +124,10 @@ impl<'x> MessageStream<'x> {
token_end = token_start;
} else {
token_end = self.offset();
last_ch = ch;
}
if let 0 | 9 = token_len {
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;
if let Some(header) = header.get_mut(token_len) {
*header = ch.to_ascii_lowercase();
}
token_len += 1;
}
@@ -145,28 +136,13 @@ impl<'x> MessageStream<'x> {
}
if token_start != 0 {
let field = self.bytes(token_start - 1..token_end);
if (2..=25).contains(&token_len) {
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;
if field.eq_ignore_ascii_case(HDR_NAMES[token_hash]) {
return Some(HDR_MAP[token_hash].clone());
}
}
}
Some(HeaderName::Other(String::from_utf8_lossy(field)))
header_map(&header[..token_len])
.unwrap_or_else(|| {
HeaderName::Other(String::from_utf8_lossy(
self.bytes(token_start - 1..token_end),
))
})
.into()
} else {
None
}
@@ -176,215 +152,64 @@ impl<'x> MessageStream<'x> {
impl<'x> HeaderName<'x> {
/// Parse a header name
pub fn parse(data: impl Into<Cow<'x, str>>) -> Option<HeaderName<'x>> {
let mut token_hash: usize = 0;
let mut last_ch: u8 = 0;
let data = data.into();
let data_ = data.as_bytes();
for (pos, &ch) in data_.iter().enumerate() {
if ch.is_ascii_alphanumeric() || [b'_', b'-'].contains(&ch) {
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;
} else {
return None;
}
}
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].clone().into();
}
}
}
if !data.is_empty() {
HeaderName::Other(data).into()
let data_lc = data.to_ascii_lowercase();
header_map(data_lc.as_bytes())
.unwrap_or(HeaderName::Other(data))
.into()
} else {
None
}
}
}
static HDR_HASH: &[u8] = &[
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 0, 20, 5, 0, 0, 25, 0, 5, 20, 73, 25, 25, 30, 10, 10, 5, 73, 0, 0, 15, 73, 73, 73, 73, 20,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73,
];
static HDR_MAP: &[HeaderName<'_>] = &[
HeaderName::Date,
HeaderName::MimeVersion, // Invalid
HeaderName::Sender,
HeaderName::MimeVersion, // Invalid
HeaderName::Received,
HeaderName::MimeVersion, // Invalid
HeaderName::References,
HeaderName::MimeVersion, // Invalid
HeaderName::Cc,
HeaderName::Comments,
HeaderName::ResentCc,
HeaderName::ContentId,
HeaderName::MimeVersion, // Invalid
HeaderName::ResentMessageId,
HeaderName::ReplyTo,
HeaderName::ResentTo,
HeaderName::ResentBcc,
HeaderName::ContentLanguage,
HeaderName::Subject,
HeaderName::ResentSender,
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::ResentDate,
HeaderName::To,
HeaderName::Bcc,
HeaderName::MimeVersion, // Invalid
HeaderName::ContentTransferEncoding,
HeaderName::ReturnPath,
HeaderName::ListId,
HeaderName::Keywords,
HeaderName::ContentDescription,
HeaderName::ListOwner,
HeaderName::MimeVersion, // Invalid
HeaderName::ContentType,
HeaderName::MimeVersion, // Invalid
HeaderName::ListHelp,
HeaderName::MessageId,
HeaderName::ContentLocation,
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::ListSubscribe,
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::ListPost,
HeaderName::MimeVersion, // Invalid
HeaderName::ResentFrom,
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::ContentDisposition,
HeaderName::MimeVersion, // Invalid
HeaderName::InReplyTo,
HeaderName::ListArchive,
HeaderName::MimeVersion, // Invalid
HeaderName::From,
HeaderName::MimeVersion, // Invalid
HeaderName::ListUnsubscribe,
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion, // Invalid
HeaderName::MimeVersion,
];
static HDR_NAMES: &[&[u8]] = &[
b"date",
b"",
b"sender",
b"",
b"received",
b"",
b"references",
b"",
b"cc",
b"comments",
b"resent-cc",
b"content-id",
b"",
b"resent-message-id",
b"reply-to",
b"resent-to",
b"resent-bcc",
b"content-language",
b"subject",
b"resent-sender",
b"",
b"",
b"resent-date",
b"to",
b"bcc",
b"",
b"content-transfer-encoding",
b"return-path",
b"list-id",
b"keywords",
b"content-description",
b"list-owner",
b"",
b"content-type",
b"",
b"list-help",
b"message-id",
b"content-location",
b"",
b"",
b"list-subscribe",
b"",
b"",
b"",
b"",
b"list-post",
b"",
b"resent-from",
b"",
b"",
b"content-disposition",
b"",
b"in-reply-to",
b"list-archive",
b"",
b"from",
b"",
b"list-unsubscribe",
b"",
b"",
b"",
b"",
b"",
b"",
b"",
b"",
b"",
b"",
b"mime-version",
];
fn header_map(name: &[u8]) -> Option<HeaderName<'static>> {
hashify::map! {name,
"arc-authentication-results" => HeaderName::ArcAuthenticationResults,
"arc-seal" => HeaderName::ArcSeal,
"arc-message-signature" => HeaderName::ArcMessageSignature,
"bcc" => HeaderName::Bcc,
"cc" => HeaderName::Cc,
"comments" => HeaderName::Comments,
"content-description" => HeaderName::ContentDescription,
"content-disposition" => HeaderName::ContentDisposition,
"content-id" => HeaderName::ContentId,
"content-language" => HeaderName::ContentLanguage,
"content-location" => HeaderName::ContentLocation,
"content-transfer-encoding" => HeaderName::ContentTransferEncoding,
"content-type" => HeaderName::ContentType,
"date" => HeaderName::Date,
"dkim-signature" => HeaderName::DkimSignature,
"from" => HeaderName::From,
"in-reply-to" => HeaderName::InReplyTo,
"keywords" => HeaderName::Keywords,
"list-archive" => HeaderName::ListArchive,
"list-help" => HeaderName::ListHelp,
"list-id" => HeaderName::ListId,
"list-owner" => HeaderName::ListOwner,
"list-post" => HeaderName::ListPost,
"list-subscribe" => HeaderName::ListSubscribe,
"list-unsubscribe" => HeaderName::ListUnsubscribe,
"message-id" => HeaderName::MessageId,
"mime-version" => HeaderName::MimeVersion,
"received" => HeaderName::Received,
"references" => HeaderName::References,
"reply-to" => HeaderName::ReplyTo,
"resent-bcc" => HeaderName::ResentBcc,
"resent-cc" => HeaderName::ResentCc,
"resent-date" => HeaderName::ResentDate,
"resent-from" => HeaderName::ResentFrom,
"resent-message-id" => HeaderName::ResentMessageId,
"resent-sender" => HeaderName::ResentSender,
"resent-to" => HeaderName::ResentTo,
"return-path" => HeaderName::ReturnPath,
"sender" => HeaderName::Sender,
"subject" => HeaderName::Subject,
"to" => HeaderName::To,
}
}
#[cfg(test)]
mod tests {
+2 -2
View File
@@ -273,7 +273,7 @@ impl MessageParser {
&& part_headers
.header_value(&HeaderName::ContentDisposition)
.map_or(true, |d| {
!d.as_content_type().map_or(false, |ct| ct.is_attachment())
!d.as_content_type().is_some_and( |ct| ct.is_attachment())
})
&& (state.parts == 1
|| state.mime_type != MimeType::MultipartRelated
@@ -606,7 +606,7 @@ mod tests {
for file_name in fs::read_dir(&test_dir).unwrap() {
let mut file_name = file_name.unwrap().path();
if file_name.extension().map_or(false, |e| e == "eml") {
if file_name.extension().is_some_and( |e| e == "eml") {
let raw_original = fs::read(&file_name).unwrap();
tests_run += 1;