Compare commits

..
1 Commits
Author SHA1 Message Date
Mauro D 6f98f52d77 100% safe Rust 2021-11-03 09:08:07 +00:00
28 changed files with 1185 additions and 1494 deletions
Generated
+1 -1
View File
@@ -59,7 +59,7 @@ checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "mail-parser"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"encoding_rs",
"serde",
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
version = "0.1.1"
version = "0.2.0"
edition = "2018"
authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT"
+10 -13
View File
@@ -24,20 +24,18 @@ HTML and plain text inline body parts is done automatically when the _alternativ
Performance and memory safety were two important factors while designing _mail-parser_:
- **Zero-copy parsing** is done in most cases (unless when decoding non-UTF8 text or when RFC2047/RFC2231 encoded parts are present).
Practically all strings and u8 slices returned by this library are `Cow<str>` or `Cow<[u8]>` references to the input raw message.
- Memory allocations are always avoided unless they are really necessary. In fact, all Base64 and Quoted-Printable parts are decoded in
place re-using the input buffer.
- [Perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) is used for fast look-up of message header fields, character
set names and aliases, HTML entities as well as month names while parsing _Date_ fields.
- Although some `unsafe` code was used to obtain performance gains of about 10%, every function in the library has been
[fuzzed](#testing-fuzzing--benchmarking) and also heavily [tested with MIRI](#testing-fuzzing--benchmarking).
- Fully battle-tested with millions of real-world e-mail messages dating from 1995 until today.
- **Zero-copy parsing**: 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
meticulously [tested with MIRI](#testing-fuzzing--benchmarking).
- Thoroughly **battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
## Usage Example
```rust
let mut input = concat!(
let input = concat!(
"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
"To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
" jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
@@ -72,10 +70,9 @@ Performance and memory safety were two important factors while designing _mail-p
"--giddyup--\n",
"--festivus--\n",
)
.as_bytes()
.to_vec();
.as_bytes();
let message = Message::parse(&mut input[..]);
let message = Message::parse(input);
// Parses addresses (including comments), lists and groups
assert_eq!(
+2 -5
View File
@@ -17,7 +17,7 @@ use std::{fs, path::PathBuf};
use test::Bencher;
fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&[u8], &str)) {
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
println!("Benchmarking {}...\n", name);
@@ -63,10 +63,7 @@ fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
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);
fnc(test_msg, String::from_utf8_lossy(&test_msg).as_ref());
}
});
}
+3 -4
View File
@@ -1,7 +1,7 @@
use mail_parser::{Addr, Address, BodyPart, Group, Message, MessagePart, MimeFieldGet};
fn main() {
let mut input = concat!(
let input = concat!(
"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
"To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
" jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
@@ -36,10 +36,9 @@ fn main() {
"--giddyup--\n",
"--festivus--\n",
)
.as_bytes()
.to_vec();
.as_bytes();
let message = Message::parse(&mut input[..]);
let message = Message::parse(input);
// Parses addresses (including comments), lists and groups
assert_eq!(
+1 -1
View File
@@ -42,7 +42,7 @@ dependencies = [
[[package]]
name = "mail-parser"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"encoding_rs",
"serde",
+7 -10
View File
@@ -1,6 +1,5 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use std::borrow::Cow;
use mail_parser::{
decoders::{
@@ -34,8 +33,7 @@ use mail_parser::{
fuzz_target!(|data: &[u8]| {
// Fuzz every parsing function
for n_fuzz in 1..=24 {
let mut data = Vec::from(data);
let stream = MessageStream::new(&mut data);
let stream = MessageStream::new(&data);
match n_fuzz {
1 => {
@@ -116,16 +114,16 @@ fuzz_target!(|data: &[u8]| {
// Fuzz HTML functions
let mut html_str = String::with_capacity(data.len());
add_html_token(&mut html_str, data, false);
let html_str = String::from_utf8_lossy(data);
html_to_text(&html_str);
text_to_html(&html_str);
let str_data = String::from_utf8_lossy(data);
add_html_token(&mut html_str, str_data.as_ref().as_bytes(), false);
html_to_text(&str_data);
text_to_html(&str_data);
// Fuzz decoding functions
decode_hex(data);
get_charset_decoder(data);
let decoders: &[for<'x> fn(&'x [u8]) -> Cow<'x, str>] = &[
let decoders: &[for<'x> fn(&'x [u8]) -> String] = &[
decoder_utf7,
decoder_utf16_le,
decoder_utf16_be,
@@ -138,6 +136,5 @@ fuzz_target!(|data: &[u8]| {
}
// Fuzz the entire library
let mut data = Vec::from(data);
Message::parse(&mut data[..]);
Message::parse(&data[..]);
});
+79 -133
View File
@@ -9,154 +9,100 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::parsers::message_stream::MessageStream;
#[repr(C)]
pub union Base64Chunk {
pub val: u32,
pub bytes: [u8; std::mem::size_of::<u32>()],
}
pub trait Base64Decoder<'x> {
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, bool, Option<&'x [u8]>);
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, Option<Cow<'x, [u8]>>);
}
// Miri does not play well with UnsafeCells, see https://github.com/rust-lang/miri/issues/1665
//
// When testing under Miri,
// (*data)[i] = val;
// is used instead of
// *(*data).get_unchecked_mut(i) = val;
//
impl<'x> Base64Decoder<'x> for MessageStream<'x> {
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let mut success = boundary.is_empty();
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, Option<Cow<'x, [u8]>>) {
let mut success = boundary.is_empty();
let mut chunk = Base64Chunk { val: 0 };
let mut byte_count: u8 = 0;
let mut match_count: usize = 0;
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut match_count: usize = 0;
let data = &mut *self.data.get();
let data_len = (*data).len();
let start_pos = self.pos.get();
let mut read_pos = start_pos;
let stream_pos = &mut *self.pos.get();
let start_pos = *stream_pos;
let mut read_pos = *stream_pos;
let mut write_pos = *stream_pos;
let mut buf = Vec::with_capacity(self.data.len() - read_pos);
while read_pos < data_len {
let ch = (*data).get_unchecked(read_pos);
read_pos += 1;
for ch in self.data[read_pos..].iter() {
read_pos += 1;
if !success {
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
success = true;
break;
} else {
continue;
}
} else if match_count > 0 {
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
let val = BASE64_MAP
.get_unchecked(byte_count as usize)
.get_unchecked(*ch as usize);
if *val >= 0x01ffffff {
if *ch == b'=' {
match byte_count {
1 | 2 => {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) =
*chunk.bytes.get_unchecked(0);
}
write_pos += 1;
byte_count = 0;
}
3 => {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
(*data)[write_pos + 1] = *chunk.bytes.get_unchecked(1);
}
#[cfg(not(miri))]
{
(*data)
.get_unchecked_mut(write_pos..write_pos + 2)
.copy_from_slice(chunk.bytes.get_unchecked(0..2));
}
write_pos += 2;
byte_count = 0;
}
0 => (),
_ => {
success = false;
break;
}
}
} else if !(*ch).is_ascii_whitespace() || is_word {
success = false;
if !success {
if *ch == boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
success = true;
break;
} else {
continue;
}
continue;
}
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk.val = *val;
} else {
chunk.val |= *val;
if byte_count == 0 {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
(*data)[write_pos + 1] = *chunk.bytes.get_unchecked(1);
(*data)[write_pos + 2] = *chunk.bytes.get_unchecked(2);
}
#[cfg(not(miri))]
{
(*data)
.get_unchecked_mut(write_pos..write_pos + 3)
.copy_from_slice(chunk.bytes.get_unchecked(0..3));
}
write_pos += 3;
} else if match_count > 0 {
if *ch == boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
*stream_pos = read_pos;
let val = BASE64_MAP[byte_count as usize][*ch as usize];
(
success,
false,
if write_pos > start_pos {
Some((*data).get_unchecked(start_pos..write_pos))
} else {
None
},
)
if val >= 0x01ffffff {
if *ch == b'=' {
match byte_count {
1 | 2 => {
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
3 => {
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
success = false;
break;
}
}
} else if !ch.is_ascii_whitespace() || is_word {
success = false;
break;
}
continue;
}
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if byte_count == 0 {
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
}
self.pos.set(read_pos);
(
success,
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
} else {
None
},
)
}
}
@@ -220,14 +166,14 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let stream = MessageStream::new(unsafe { str.as_bytes_mut() });
let str = input.0.to_string();
let stream = MessageStream::new(str.as_bytes());
let (success, _, result) = stream.decode_base64(input.2.as_bytes(), input.3);
let (success, result) = stream.decode_base64(input.2.as_bytes(), input.3);
assert_eq!(success, !input.1.is_empty(), "Failed for '{:?}'", input.0);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.unwrap()).unwrap();
let result_str = std::str::from_utf8(result.as_ref().unwrap().as_ref()).unwrap();
//println!("'{}' -> '{}'", input.0.escape_debug(), result_str.escape_debug());
assert_eq!(
result_str,
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -9,14 +9,12 @@
* except according to those terms.
*/
use std::borrow::Cow;
pub mod map;
pub mod multi_byte;
pub mod single_byte;
pub mod utf;
pub type DecoderFnc<'x> = fn(&'x [u8]) -> Cow<'x, str>;
pub type DecoderFnc<'x> = fn(&'x [u8]) -> String;
#[cfg(test)]
mod tests {
+11 -13
View File
@@ -9,8 +9,6 @@
* except according to those terms.
*/
use std::borrow::Cow;
#[cfg(feature = "full_encoding")]
use encoding_rs::*;
@@ -18,7 +16,7 @@ use encoding_rs::*;
use super::map::decoder_default;
#[cfg(feature = "full_encoding")]
fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> Cow<str> {
fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len() * 3);
if let (CoderResult::OutputFull, _, _) = decoder.decode_to_string(bytes, &mut result, true) {
@@ -26,10 +24,10 @@ fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> Cow<str> {
}
result.shrink_to_fit();
result.into()
result
}
pub fn decoder_shift_jis(bytes: &[u8]) -> Cow<str> {
pub fn decoder_shift_jis(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(SHIFT_JIS.new_decoder(), bytes)
@@ -41,7 +39,7 @@ pub fn decoder_shift_jis(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_big5(bytes: &[u8]) -> Cow<str> {
pub fn decoder_big5(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(BIG5.new_decoder(), bytes)
@@ -53,7 +51,7 @@ pub fn decoder_big5(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_euc_jp(bytes: &[u8]) -> Cow<str> {
pub fn decoder_euc_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_JP.new_decoder(), bytes)
@@ -65,7 +63,7 @@ pub fn decoder_euc_jp(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_euc_kr(bytes: &[u8]) -> Cow<str> {
pub fn decoder_euc_kr(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_KR.new_decoder(), bytes)
@@ -77,7 +75,7 @@ pub fn decoder_euc_kr(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_gb18030(bytes: &[u8]) -> Cow<str> {
pub fn decoder_gb18030(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GB18030.new_decoder(), bytes)
@@ -89,7 +87,7 @@ pub fn decoder_gb18030(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_gbk(bytes: &[u8]) -> Cow<str> {
pub fn decoder_gbk(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GBK.new_decoder(), bytes)
@@ -101,7 +99,7 @@ pub fn decoder_gbk(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_iso2022_jp(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso2022_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(ISO_2022_JP.new_decoder(), bytes)
@@ -113,7 +111,7 @@ pub fn decoder_iso2022_jp(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_windows874(bytes: &[u8]) -> Cow<str> {
pub fn decoder_windows874(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(WINDOWS_874.new_decoder(), bytes)
@@ -125,7 +123,7 @@ pub fn decoder_windows874(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_ibm866(bytes: &[u8]) -> Cow<str> {
pub fn decoder_ibm866(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(IBM866.new_decoder(), bytes)
+31 -34
View File
@@ -9,129 +9,126 @@
* except according to those terms.
*/
use std::borrow::Cow;
fn single_byte_decoder<'x>(table: &[char], bytes: &'x [u8]) -> Cow<'x, str> {
fn single_byte_decoder(table: &[char], bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len() * 2);
for byte in bytes {
// SAFE: table's size is always u8::MAX
result.push(unsafe { *table.get_unchecked(*byte as usize) });
result.push(table[*byte as usize]);
}
result.shrink_to_fit();
result.into()
result
}
pub fn decoder_iso_8859_1(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_1(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_1, bytes)
}
pub fn decoder_iso_8859_2(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_2(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_2, bytes)
}
pub fn decoder_iso_8859_3(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_3(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_3, bytes)
}
pub fn decoder_iso_8859_4(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_4(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_4, bytes)
}
pub fn decoder_iso_8859_5(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_5(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_5, bytes)
}
pub fn decoder_iso_8859_6(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_6(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_6, bytes)
}
pub fn decoder_iso_8859_7(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_7(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_7, bytes)
}
pub fn decoder_iso_8859_8(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_8(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_8, bytes)
}
pub fn decoder_iso_8859_9(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_9(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_9, bytes)
}
pub fn decoder_iso_8859_10(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_10(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_10, bytes)
}
pub fn decoder_iso_8859_13(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_13(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_13, bytes)
}
pub fn decoder_iso_8859_14(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_14(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_14, bytes)
}
pub fn decoder_iso_8859_15(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_15(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_15, bytes)
}
pub fn decoder_iso_8859_16(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_16(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_16, bytes)
}
pub fn decoder_cp1250(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1250(bytes: &[u8]) -> String {
single_byte_decoder(CP1250, bytes)
}
pub fn decoder_cp1251(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1251(bytes: &[u8]) -> String {
single_byte_decoder(CP1251, bytes)
}
pub fn decoder_cp1252(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1252(bytes: &[u8]) -> String {
single_byte_decoder(CP1252, bytes)
}
pub fn decoder_cp1253(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1253(bytes: &[u8]) -> String {
single_byte_decoder(CP1253, bytes)
}
pub fn decoder_cp1254(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1254(bytes: &[u8]) -> String {
single_byte_decoder(CP1254, bytes)
}
pub fn decoder_cp1255(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1255(bytes: &[u8]) -> String {
single_byte_decoder(CP1255, bytes)
}
pub fn decoder_cp1256(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1256(bytes: &[u8]) -> String {
single_byte_decoder(CP1256, bytes)
}
pub fn decoder_cp1257(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1257(bytes: &[u8]) -> String {
single_byte_decoder(CP1257, bytes)
}
pub fn decoder_cp1258(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1258(bytes: &[u8]) -> String {
single_byte_decoder(CP1258, bytes)
}
pub fn decoder_koi8_r(bytes: &[u8]) -> Cow<str> {
pub fn decoder_koi8_r(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_R, bytes)
}
pub fn decoder_koi8_u(bytes: &[u8]) -> Cow<str> {
pub fn decoder_koi8_u(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_U, bytes)
}
pub fn decoder_macintosh(bytes: &[u8]) -> Cow<str> {
pub fn decoder_macintosh(bytes: &[u8]) -> String {
single_byte_decoder(MACINTOSH, bytes)
}
pub fn decoder_ibm_850(bytes: &[u8]) -> Cow<str> {
pub fn decoder_ibm_850(bytes: &[u8]) -> String {
single_byte_decoder(IBM850, bytes)
}
pub fn decoder_tis_620(bytes: &[u8]) -> Cow<str> {
pub fn decoder_tis_620(bytes: &[u8]) -> String {
single_byte_decoder(TIS_620, bytes)
}
+26 -40
View File
@@ -9,38 +9,32 @@
* except according to those terms.
*/
use std::{
borrow::Cow,
char::{decode_utf16, REPLACEMENT_CHARACTER},
};
use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use crate::decoders::base64::{Base64Chunk, BASE64_MAP};
use crate::decoders::base64::BASE64_MAP;
struct Utf7DecoderState {
utf16_bytes: Vec<u16>,
pending_byte: Option<u8>,
b64_bytes: Base64Chunk,
b64_bytes: u32,
}
fn add_utf16_bytes(state: &mut Utf7DecoderState, n_bytes: usize) {
debug_assert!(n_bytes < std::mem::size_of::<u32>());
unsafe {
// SAFE: union access of `n_bytes`, which is always lower than size_of::<u32>
for byte in state.b64_bytes.bytes.get_unchecked(0..n_bytes) {
if let Some(pending_byte) = state.pending_byte {
state
.utf16_bytes
.push(u16::from_be_bytes([pending_byte, *byte]));
state.pending_byte = None;
} else {
state.pending_byte = Some(*byte);
}
for byte in state.b64_bytes.to_le_bytes()[0..n_bytes].iter() {
if let Some(pending_byte) = state.pending_byte {
state
.utf16_bytes
.push(u16::from_be_bytes([pending_byte, *byte]));
state.pending_byte = None;
} else {
state.pending_byte = Some(*byte);
}
}
}
pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
pub 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;
@@ -48,28 +42,20 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
let mut state = Utf7DecoderState {
utf16_bytes: Vec::with_capacity(10),
pending_byte: None,
b64_bytes: Base64Chunk { val: 0 },
b64_bytes: 0,
};
for byte in bytes {
if in_b64 {
// SAFE: BASEMAP's size is [4][u8::MAX]
let val = unsafe {
BASE64_MAP
.get_unchecked(byte_count as usize)
.get_unchecked(*byte as usize)
};
let val = BASE64_MAP[byte_count as usize][*byte as usize];
if *val < 0x01ffffff {
if val < 0x01ffffff {
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
state.b64_bytes.val = *val;
state.b64_bytes = val;
} else {
// SAFE: union read/write
unsafe {
state.b64_bytes.val |= *val;
}
state.b64_bytes |= val;
if byte_count == 0 {
add_utf16_bytes(&mut state, 3);
@@ -112,30 +98,29 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
}
result.shrink_to_fit();
result.into()
result
}
fn decoder_utf16_(bytes: &[u8], fnc: fn([u8; 2]) -> u16) -> Cow<str> {
fn decoder_utf16_(bytes: &[u8], fnc: fn([u8; 2]) -> u16) -> String {
if bytes.len() >= 2 {
decode_utf16(bytes.chunks_exact(2).map(|c| fnc([c[0], c[1]])))
.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>()
.into()
} else {
"".into()
"".to_string()
}
}
pub fn decoder_utf16_le(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf16_le(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_le_bytes)
}
pub fn decoder_utf16_be(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf16_be(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_be_bytes)
}
#[allow(clippy::type_complexity)]
pub fn decoder_utf16(bytes: &[u8]) -> Cow<str> {
pub 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),
@@ -146,8 +131,9 @@ pub fn decoder_utf16(bytes: &[u8]) -> Cow<str> {
decoder_utf16_(bytes, fnc)
}
pub fn decoder_utf8(bytes: &[u8]) -> Cow<str> {
String::from_utf8_lossy(bytes)
// Not currently used at the moment
pub fn decoder_utf8(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
#[cfg(test)]
+9 -14
View File
@@ -9,8 +9,6 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::{
decoders::{
base64::Base64Decoder, charsets::map::get_charset_decoder,
@@ -19,9 +17,7 @@ use crate::{
parsers::message_stream::MessageStream,
};
use super::charsets::map::decoder_default;
pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
pub fn parse_encoded_word(stream: &MessageStream) -> Option<String> {
if !stream.skip_byte(&b'?') {
return None;
}
@@ -55,12 +51,12 @@ pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
return None;
}
let (success, is_utf8_safe, bytes) = match stream.next() {
let (success, bytes) = match stream.next() {
Some(b'q') | Some(b'Q') if stream.skip_byte(&b'?') => {
stream.decode_quoted_printable(b"?=", true)
}
Some(b'b') | Some(b'B') if stream.skip_byte(&b'?') => stream.decode_base64(b"?=", true),
_ => (false, false, None),
_ => (false, None),
};
if !success {
@@ -71,12 +67,11 @@ pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
if let Some(decoder) =
get_charset_decoder(stream.get_bytes(charset_start, charset_end).unwrap())
{
decoder(bytes?).into()
} else if is_utf8_safe {
// SAFE: slice checked previously
unsafe { Cow::from(std::str::from_utf8_unchecked(bytes?)).into() }
decoder(bytes?.as_ref()).into()
} else {
decoder_default(bytes?).into()
String::from_utf8(bytes?.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
}
@@ -166,9 +161,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
match parse_encoded_word(&MessageStream::new(unsafe { str.as_bytes_mut() })) {
match parse_encoded_word(&MessageStream::new(str.as_bytes())) {
Some(string) => {
//println!("Decoded '{}'", string);
assert_eq!(string, input.1);
+2 -4
View File
@@ -39,8 +39,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
result.push(*ch);
}
HexState::Percent => {
// SAFE: HEX_MAP's size is u8::MAX
hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
hex1 = HEX_MAP[*ch as usize];
if hex1 != -1 {
state = HexState::Hex1;
} else {
@@ -49,8 +48,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
}
}
HexState::Hex1 => {
// SAFE: HEX_MAP's size is u8::MAX
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
let hex2 = HEX_MAP[*ch as usize];
state = HexState::None;
if hex2 != -1 {
+21 -28
View File
@@ -33,33 +33,29 @@ 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);
/* SAFE: ENTITY_HASH's size is 260 (u8::MAX + 5)
and ENTITY_MAP's size is 18016 (18079 - 64 + 1) */
unsafe {
for (pos, ch) in entity.iter().enumerate() {
match pos {
0 | 5 | 6 | 9 | 11 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize);
}
1 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 4);
}
2 | 4 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 1);
}
3 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 3);
}
_ => (),
for (pos, ch) in entity.iter().enumerate() {
match pos {
0 | 5 | 6 | 9 | 11 => {
hash += ENTITY_HASH[*ch as usize];
}
if pos == entity.len() - 1 {
hash += *ENTITY_HASH.get_unchecked(*ch as usize);
1 => {
hash += ENTITY_HASH[*ch as usize + 4];
}
2 | 4 => {
hash += ENTITY_HASH[*ch as usize + 1];
}
3 => {
hash += ENTITY_HASH[*ch as usize + 3];
}
_ => (),
}
if pos == entity.len() - 1 {
hash += ENTITY_HASH[*ch as usize];
}
}
if (64..=18079).contains(&hash) {
entity_code = *ENTITY_MAP.get_unchecked((hash - 64) as usize);
}
if (64..=18079).contains(&hash) {
entity_code = ENTITY_MAP[(hash - 64) as usize];
}
}
@@ -69,9 +65,7 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
}
}
// SAFE: the input string is tokenized by ASCII chars, therefore the resulting
// u8 array is UTF-8 safe.
result.push_str(unsafe { std::str::from_utf8_unchecked(token) });
result.push_str(std::str::from_utf8(token).unwrap());
}
pub fn html_to_text(input: &str) -> String {
@@ -237,8 +231,7 @@ pub fn text_to_html(input: &str) -> String {
}
result.extend_from_slice(b"</body></html>");
// SAFE: `result` contains a sequence of a valid `input` string tokens and UTF-8 safe slices
unsafe { String::from_utf8_unchecked(result) }
String::from_utf8(result).unwrap()
}
#[cfg(test)]
+122 -208
View File
@@ -9,6 +9,8 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::parsers::message_stream::MessageStream;
#[derive(PartialEq, Debug)]
@@ -23,234 +25,146 @@ pub trait QuotedPrintableDecoder<'x> {
&self,
boundary: &[u8],
is_word: bool,
) -> (bool, bool, Option<&'x [u8]>);
) -> (bool, Option<Cow<'x, [u8]>>);
}
// Miri does not play well with UnsafeCells, see https://github.com/rust-lang/miri/issues/1665
//
// When testing under Miri,
// (*data)[i] = val;
// is used instead of
// *(*data).get_unchecked_mut(i) = val;
//
impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
fn decode_quoted_printable(
&self,
boundary: &[u8],
is_word: bool,
) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let mut success = boundary.is_empty();
let mut is_utf8_safe = true;
) -> (bool, Option<Cow<'x, [u8]>>) {
let mut success = boundary.is_empty();
// SAFE: exclusive access to `self.data`
let mut data = &mut *self.data.get();
let data_len = (*data).len();
let start_pos = self.pos.get();
let mut read_pos = start_pos;
// SAFE: exclusive access to `self.pos`
let stream_pos = &mut *self.pos.get();
let start_pos = *stream_pos;
let mut read_pos = *stream_pos;
let mut write_pos = *stream_pos;
let mut buf = Vec::with_capacity(self.data.len() - read_pos);
let mut state = QuotedPrintableState::None;
let mut match_count = 0;
let mut hex1 = 0;
let mut state = QuotedPrintableState::None;
let mut match_count = 0;
let mut hex1 = 0;
debug_assert!(boundary.is_empty() || boundary.len() >= 2);
debug_assert!(boundary.is_empty() || boundary.len() >= 2);
while read_pos < data_len {
// SAFE: slice bounds checked in while loop
let ch = *(*data).get_unchecked(read_pos);
read_pos += 1;
for ch in self.data[read_pos..].iter() {
read_pos += 1;
// if success is false, a boundary was provided
if !success {
let mut is_boundary_end = true;
// if success is false, a boundary was provided
if !success {
let mut is_boundary_end = true;
// SAFE: bounds are checked after the first match occurs
if ch == *boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
let done = if is_word {
true
} else {
// SAFE: exclusive access to `self.data` is re-obtained after
// is_boundary_end finishes.
is_boundary_end = self.is_boundary_end(read_pos);
is_boundary_end
};
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
if done {
success = true;
break;
}
if *ch == boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
let done = if is_word {
true
} else {
continue;
}
}
is_boundary_end = self.is_boundary_end(read_pos);
is_boundary_end
};
if match_count > 0 {
for ch in boundary[..match_count].iter() {
if *ch != b'\n' || QuotedPrintableState::Eq != state {
#[cfg(miri)]
{
(*data)[write_pos] = *ch;
}
#[cfg(not(miri))]
{
// SAFE: `write_pos` increments in parallel to `read_pos`
// which is bound checked in the while loop
*((*data).get_unchecked_mut(write_pos)) = *ch;
}
write_pos += 1;
if is_utf8_safe && *ch > 0x7f {
is_utf8_safe = false;
}
}
}
state = QuotedPrintableState::None;
// is_boundary_end is always true except in the rare event
// that a boundary was found without a proper MIME ending (-- or \r\n)
if is_boundary_end {
// SAFE: `boundary` is never empty at this point
if ch == *boundary.get_unchecked(0) {
// Char matched beginning of boundary, get next char.
match_count = 1;
continue;
} else {
// Reset match count and decode character
match_count = 0;
}
} else {
// There was a full boundary match but without a proper MIME
// ending, reset match count and continue.
match_count = 0;
continue;
if done {
success = true;
break;
}
} else {
continue;
}
}
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
if match_count > 0 {
for ch in boundary[..match_count].iter() {
if *ch != b'\n' || QuotedPrintableState::Eq != state {
buf.push(*ch);
}
}
state = QuotedPrintableState::None;
// is_boundary_end is always true except in the rare event
// that a boundary was found without a proper MIME ending (-- or \r\n)
if is_boundary_end {
if *ch == boundary[0] {
// Char matched beginning of boundary, get next char.
match_count = 1;
continue;
} else {
success = false;
break;
// Reset match count and decode character
match_count = 0;
}
} else {
// There was a full boundary match but without a proper MIME
// ending, reset match count and continue.
match_count = 0;
continue;
}
b'\n' => {
if is_word {
success = false;
break;
} else if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
#[cfg(miri)]
{
(*data)[write_pos] = b'\n';
}
#[cfg(not(miri))]
{
// SAFE: `write_pos` increments in parallel to `read_pos`
// which is bound checked in the while loop
*((*data).get_unchecked_mut(write_pos)) = b'\n';
}
write_pos += 1;
}
}
b'_' if is_word => {
#[cfg(miri)]
{
(*data)[write_pos] = b' ';
}
#[cfg(not(miri))]
{
// SAFE: `write_pos` increments in parallel to `read_pos`
// which is bound checked in the while loop
*((*data).get_unchecked_mut(write_pos)) = b' ';
}
write_pos += 1;
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
#[cfg(miri)]
{
(*data)[write_pos] = ch;
}
#[cfg(not(miri))]
{
// SAFE: `write_pos` increments in parallel to `read_pos`
// which is bound checked in the while loop
*((*data).get_unchecked_mut(write_pos)) = ch;
}
write_pos += 1;
if is_utf8_safe && ch > 0x7f {
is_utf8_safe = false;
}
}
QuotedPrintableState::Eq => {
// SAFE: HEX_MAP's size is u8::MAX
hex1 = *HEX_MAP.get_unchecked(ch as usize);
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
success = false;
break;
}
}
QuotedPrintableState::Hex1 => {
// SAFE: HEX_MAP's size is u8::MAX
let hex2 = *HEX_MAP.get_unchecked(ch as usize);
state = QuotedPrintableState::None;
if hex2 != -1 {
let ch = ((hex1 as u8) << 4) | hex2 as u8;
#[cfg(miri)]
{
(*data)[write_pos] = ch;
}
#[cfg(not(miri))]
{
// SAFE: `write_pos` increments in parallel to `read_pos`
// which is bound checked in the while loop
*((*data).get_unchecked_mut(write_pos)) = ch;
}
write_pos += 1;
if is_utf8_safe && ch > 0x7f {
is_utf8_safe = false;
}
} else {
success = false;
break;
}
}
},
}
}
*stream_pos = read_pos;
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
success = false;
break;
}
}
b'\n' => {
if is_word {
success = false;
break;
} else if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
buf.push(b'\n');
}
}
b'_' if is_word => {
buf.push(b' ');
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
buf.push(*ch);
}
QuotedPrintableState::Eq => {
hex1 = HEX_MAP[*ch as usize];
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
success = false;
break;
}
}
QuotedPrintableState::Hex1 => {
let hex2 = HEX_MAP[*ch as usize];
(
success,
is_utf8_safe,
if write_pos > start_pos {
// SAFE: bounds are checked
Some((*data).get_unchecked(start_pos..write_pos))
} else {
None
state = QuotedPrintableState::None;
if hex2 != -1 {
let ch = ((hex1 as u8) << 4) | hex2 as u8;
buf.push(ch);
} else {
success = false;
break;
}
}
},
)
}
}
self.pos.set(read_pos);
(
success,
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
} else {
None
},
)
}
}
@@ -331,15 +245,15 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let stream = MessageStream::new(unsafe { str.as_bytes_mut() });
let str = input.0.to_string();
let stream = MessageStream::new(str.as_bytes());
let (success, _, result) = stream.decode_quoted_printable(input.2.as_bytes(), input.3);
let (success, result) = stream.decode_quoted_printable(input.2.as_bytes(), input.3);
assert_eq!(success, !input.1.is_empty(), "Failed for '{:?}'", input.0);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.unwrap()).unwrap();
let result_str = std::str::from_utf8(result.as_ref().unwrap()).unwrap();
/*println!(
"Decoded '{}'\n -> to ->\n'{}'\n{}",
@@ -358,14 +272,14 @@ mod tests {
}
// MIRI overflow tests
for mut input in [b"\x0a\x0a\x00\x0b".to_vec(), b":B\x0a%".to_vec()] {
let stream = MessageStream::new(&mut input[..]);
for input in [b"\x0a\x0a\x00\x0b".to_vec(), b":B\x0a%".to_vec()] {
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(b"\n\n", true);
let stream = MessageStream::new(&mut input[..]);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(b"\n\n", false);
let stream = MessageStream::new(&mut input[..]);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(&[], true);
let stream = MessageStream::new(&mut input[..]);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(&[], false);
}
}
+74 -13
View File
@@ -29,15 +29,13 @@
//!
//! Performance and memory safety were two important factors while designing _mail-parser_:
//!
//! - **Zero-copy parsing** is done in most cases (unless when decoding non-UTF8 text or when RFC2047/RFC2231 encoded parts are present).
//! Practically all strings and u8 slices returned by this library are `Cow<str>` or `Cow<[u8]>` references to the input raw message.
//! - Memory allocations are always avoided unless they are really necessary. In fact, all Base64 and Quoted-Printable parts are decoded in
//! place re-using the input buffer.
//! - [Perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) is used for fast look-up of message header fields, character
//! set names and aliases, HTML entities as well as month names while parsing _Date_ fields.
//! - Although some `unsafe` code was used to obtain performance gains of about 10%, every function in the library has been
//! [fuzzed](#testing-fuzzing--benchmarking) and also heavily [tested with MIRI](#testing-fuzzing--benchmarking).
//! - Fully battle-tested with millions of real-world e-mail messages dating from 1995 until today.
//! - **Zero-copy parsing**: 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
//! meticulously [tested with MIRI](#testing-fuzzing--benchmarking).
//! - Thoroughly **battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
//!
//! Jump to the [example](#usage-example).
//!
@@ -110,7 +108,7 @@
//! ```
//! use mail_parser::*;
//!
//! let mut input = concat!(
//! let input = concat!(
//! "From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
//! "To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
//! " jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
@@ -145,10 +143,9 @@
//! "--giddyup--\n",
//! "--festivus--\n",
//! )
//! .as_bytes()
//! .to_vec();
//! .as_bytes();
//!
//! let message = Message::parse(&mut input[..]);
//! let message = Message::parse(input);
//!
//! // Parses addresses (including comments), lists and groups
//! assert_eq!(
@@ -941,6 +938,70 @@ impl<'x> Message<'x> {
}
}
impl<'x> MessageHeader<'x> {
pub fn is_empty(&self) -> bool {
for addr in [
&self.from,
&self.to,
&self.cc,
&self.bcc,
&self.reply_to,
&self.sender,
&self.resent_to,
&self.resent_from,
&self.resent_bcc,
&self.resent_cc,
&self.resent_sender,
&self.list_archive,
&self.list_help,
&self.list_id,
&self.list_owner,
&self.list_post,
&self.list_subscribe,
&self.list_unsubscribe,
] {
if !addr.is_empty() {
return false;
}
}
for str in [
&self.subject,
&self.message_id,
&self.mime_version,
&self.content_description,
&self.content_id,
&self.content_transfer_encoding,
] {
if str.is_some() {
return false;
}
}
if self.date.is_some() || !self.others.is_empty() {
return false;
}
for vec in [
&self.comments,
&self.in_reply_to,
&self.keywords,
&self.received,
&self.references,
&self.resent_message_id,
&self.return_path,
] {
if vec.is_some() {
return false;
}
}
self.content_disposition.is_none()
&& self.resent_date.is_none()
&& self.content_type.is_none()
}
}
impl<'x> MimeFieldGet<'x> for Message<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.header.content_description.as_ref()
+6 -17
View File
@@ -40,7 +40,6 @@ pub struct AddressParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_email: bool,
is_token_start: bool,
is_escaped: bool,
@@ -65,11 +64,7 @@ pub fn add_token<'x>(
) {
if parser.token_start > 0 {
let token = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap();
let mut add_space = false;
let list = match parser.state {
@@ -100,7 +95,6 @@ pub fn add_token<'x>(
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_email = false;
parser.is_token_start = true;
parser.is_escaped = false;
@@ -238,7 +232,6 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_email: false,
is_token_start: true,
is_escaped: false,
@@ -323,7 +316,7 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
} else {
&mut parser.comment_tokens
})
.push(token);
.push(token.into());
continue;
}
}
@@ -373,12 +366,7 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
add_group(&mut parser);
continue;
}
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_escaped {
@@ -941,8 +929,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let result = parse_address(&MessageStream::new(unsafe { str.as_bytes_mut() }));
println!("Testiong {}", input.0);
let str = input.0.to_string();
let result = parse_address(&MessageStream::new(str.as_bytes()));
let expected: Address = serde_yaml::from_str(input.1).unwrap_or(Address::Empty);
/*if input.0.len() >= 70 {
+20 -46
View File
@@ -16,9 +16,7 @@ use std::{
use crate::{
decoders::{
charsets::map::{decoder_default, get_charset_decoder},
encoded_word::parse_encoded_word,
hex::decode_hex,
charsets::map::get_charset_decoder, encoded_word::parse_encoded_word, hex::decode_hex,
},
parsers::message_stream::MessageStream,
ContentType,
@@ -58,24 +56,18 @@ struct ContentTypeParser<'x> {
is_encoded_attribute: bool,
is_escaped: bool,
is_lower_case: bool,
is_token_safe: bool,
is_token_start: bool,
}
#[inline(always)]
fn reset_parser(parser: &mut ContentTypeParser) {
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
fn add_attribute<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) -> bool {
if parser.token_start > 0 {
let mut attr = stream.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
);
let mut attr = stream.get_string(parser.token_start - 1, parser.token_end);
if !parser.is_lower_case {
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
@@ -99,11 +91,7 @@ fn add_attribute<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<
fn add_attribute_parameter<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) {
if parser.token_start > 0 {
let attr_part = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap();
if parser.attr_charset.is_none() {
@@ -143,7 +131,6 @@ fn add_partial_value<'x>(
} else {
parser.token_end
},
parser.is_token_safe,
)
.unwrap(),
);
@@ -162,11 +149,7 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
let has_values = !parser.values.is_empty();
let value = if parser.token_start > 0 {
stream.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
stream.get_string(parser.token_start - 1, parser.token_end)
} else {
if !has_values {
return;
@@ -200,16 +183,17 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
if parser.is_encoded_attribute {
if let (true, decoded_bytes) = decode_hex(value.as_bytes()) {
value = get_charset_decoder(
parser
.attr_charset
.as_ref()
.unwrap_or(&"utf-8".into())
.as_bytes(),
)
.unwrap_or(decoder_default)(&decoded_bytes)
.into_owned()
.into();
value = if let Some(decoder) = parser
.attr_charset
.as_ref()
.and_then(|c| get_charset_decoder(c.as_bytes()))
{
decoder(&decoded_bytes).into()
} else {
String::from_utf8(decoded_bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
}
parser.is_encoded_attribute = false;
}
@@ -240,11 +224,7 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
fn add_attr_position(parser: &mut ContentTypeParser, stream: &MessageStream) -> bool {
if parser.token_start > 0 {
parser.attr_position = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap()
.parse()
.unwrap_or(0);
@@ -288,7 +268,6 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
is_continuation: false,
is_encoded_attribute: false,
is_lower_case: true,
is_token_safe: true,
is_token_start: true,
is_escaped: false,
@@ -418,7 +397,7 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
{
if let Some(token) = parse_encoded_word(stream) {
add_partial_value(&mut parser, stream, false);
parser.values.push(token);
parser.values.push(token.into());
continue;
}
}
@@ -496,12 +475,7 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
continue;
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_escaped {
@@ -1353,9 +1327,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
let result = parse_content_type(&MessageStream::new(unsafe { str.as_bytes_mut() }));
let result = parse_content_type(&MessageStream::new(str.as_bytes()));
let expected: Option<ContentType> = serde_yaml::from_str(input.1).unwrap_or(None);
/*
+6 -9
View File
@@ -115,11 +115,9 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
b'a'..=b'z' | b'A'..=b'Z' => {
if pos == 1 {
if (1..=2).contains(&month_pos) {
// SAFE: MONTH_HASH's size is u8::MAX
month_hash += unsafe {
*MONTH_HASH
.get_unchecked((if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize)
} as usize;
month_hash += MONTH_HASH
[(if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize]
as usize;
}
month_pos += 1;
}
@@ -158,8 +156,7 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
parts[2]
},
month: if month_pos == 3 && month_hash <= 30 {
// SAFE: MONTH_MAP's size is 31
(unsafe { *MONTH_MAP.get_unchecked(month_hash) }) as u32
MONTH_MAP[month_hash] as u32
} else {
parts[1]
},
@@ -261,8 +258,8 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
match parse_date(&MessageStream::new(unsafe { str.as_bytes_mut() }), false) {
let str = input.0.to_string();
match parse_date(&MessageStream::new(str.as_bytes()), false) {
Some(date) => {
//println!("{} -> {}", input.0.escape_debug(), date.to_iso8601());
assert_eq!(input.1, date.to_iso8601());
+4 -15
View File
@@ -16,7 +16,6 @@ use crate::parsers::message_stream::MessageStream;
pub fn parse_id<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'x, str>>> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_token_safe = true;
let mut is_id_part = false;
let mut ids = Vec::new();
@@ -36,24 +35,14 @@ pub fn parse_id<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'x, str>>> {
b'>' => {
is_id_part = false;
if token_start > 0 {
ids.push(
stream
.get_string(token_start - 1, token_end, is_token_safe)
.unwrap(),
);
is_token_safe = true;
ids.push(stream.get_string(token_start - 1, token_end).unwrap());
token_start = 0;
} else {
continue;
}
}
b' ' | b'\t' | b'\r' => continue,
0..=0x7f => (),
_ => {
if is_token_safe {
is_token_safe = false;
}
}
_ => (),
}
if is_id_part {
if token_start == 0 {
@@ -103,10 +92,10 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
input.1,
parse_id(&MessageStream::new(unsafe { str.as_bytes_mut() })).unwrap(),
parse_id(&MessageStream::new(str.as_bytes())).unwrap(),
"Failed to parse '{:?}'",
input.0
);
+5 -17
View File
@@ -16,7 +16,6 @@ use crate::{decoders::encoded_word::parse_encoded_word, parsers::message_stream:
struct ListParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_start: bool,
tokens: Vec<Cow<'x, str>>,
list: Vec<Cow<'x, str>>,
@@ -29,11 +28,7 @@ fn add_token<'x>(parser: &mut ListParser<'x>, stream: &MessageStream<'x>, add_sp
}
parser.tokens.push(
stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap(),
);
@@ -42,7 +37,6 @@ fn add_token<'x>(parser: &mut ListParser<'x>, stream: &MessageStream<'x>, add_sp
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
}
@@ -63,7 +57,6 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
let mut parser = ListParser {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_start: true,
tokens: Vec::new(),
list: Vec::new(),
@@ -101,7 +94,7 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
b'=' if parser.is_token_start => {
if let Some(token) = parse_encoded_word(stream) {
add_token(&mut parser, stream, true);
parser.tokens.push(token);
parser.tokens.push(token.into());
continue;
}
}
@@ -111,12 +104,7 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
continue;
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_token_start {
@@ -177,9 +165,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_comma_separared(&MessageStream::new(unsafe { str.as_bytes_mut() }),).unwrap(),
parse_comma_separared(&MessageStream::new(str.as_bytes()),).unwrap(),
input.1
);
}
+4 -10
View File
@@ -16,7 +16,6 @@ use crate::parsers::message_stream::MessageStream;
pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_token_safe = true;
while let Some(ch) = stream.next() {
match ch {
@@ -28,7 +27,7 @@ pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
_ => {
return if token_start > 0 {
stream
.get_string(token_start - 1, token_end, is_token_safe)
.get_string(token_start - 1, token_end)
.unwrap()
.into()
} else {
@@ -37,12 +36,7 @@ pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
}
},
b' ' | b'\t' | b'\r' => continue,
0..=0x7f => (),
_ => {
if is_token_safe {
is_token_safe = false;
}
}
_ => (),
}
if token_start == 0 {
@@ -93,9 +87,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_raw(&MessageStream::new(unsafe { str.as_bytes_mut() })).unwrap(),
parse_raw(&MessageStream::new(str.as_bytes())).unwrap(),
input.1,
"Failed for '{:?}'",
input.0
+5 -17
View File
@@ -15,7 +15,6 @@ use crate::{decoders::encoded_word::parse_encoded_word, parsers::message_stream:
struct UnstructuredParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_start: bool,
tokens: Vec<Cow<'x, str>>,
}
@@ -27,11 +26,7 @@ fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &MessageStream<'x>
}
parser.tokens.push(
stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap(),
);
@@ -40,7 +35,6 @@ fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &MessageStream<'x>
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
}
@@ -49,7 +43,6 @@ pub fn parse_unstructured<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
let mut parser = UnstructuredParser {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_start: true,
tokens: Vec::new(),
};
@@ -85,17 +78,12 @@ pub fn parse_unstructured<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
b'=' if parser.is_token_start => {
if let Some(token) = parse_encoded_word(stream) {
add_token(&mut parser, stream, true);
parser.tokens.push(token);
parser.tokens.push(token.into());
continue;
}
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_token_start {
@@ -191,9 +179,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_unstructured(&MessageStream::new(unsafe { str.as_bytes_mut() }),).unwrap(),
parse_unstructured(&MessageStream::new(str.as_bytes()),).unwrap(),
input.1,
"Failed to parse '{:?}'",
input.0
+7 -19
View File
@@ -77,23 +77,14 @@ pub fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'
let field = stream.get_bytes(token_start - 1, token_end).unwrap();
if (2..=25).contains(&token_len) {
// SAFE: HDR_HASH's size is u8::MAX
token_hash += token_len
+ unsafe {
*HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize)
} as usize;
token_hash +=
token_len + HDR_HASH[last_ch.to_ascii_lowercase() as usize] as usize;
if (4..=61).contains(&token_hash) {
let token_hash = token_hash - 4;
// SAFE: HDR_NAME's size is 58
if field.eq_ignore_ascii_case(unsafe {
HDR_NAMES.get_unchecked(token_hash)
}) {
// SAFE: HDR_FNCS's size is 58
return HeaderParserResult::Supported(unsafe {
*HDR_FNCS.get_unchecked(token_hash)
});
if field.eq_ignore_ascii_case(HDR_NAMES[token_hash]) {
return HeaderParserResult::Supported(HDR_FNCS[token_hash]);
}
}
}
@@ -115,10 +106,7 @@ pub fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'
}
if let 0 | 9 = token_len {
// SAFE: HDR_HASH's size is u8::MAX
token_hash +=
unsafe { *HDR_HASH.get_unchecked((*ch).to_ascii_lowercase() as usize) }
as usize;
token_hash += HDR_HASH[(*ch).to_ascii_lowercase() as usize] as usize;
}
token_len += 1;
}
@@ -163,8 +151,8 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
match parse_header_name(&MessageStream::new(unsafe { str.as_bytes_mut() })) {
let str = input.0.to_string();
match parse_header_name(&MessageStream::new(str.as_bytes())) {
HeaderParserResult::Supported(f) => {
if let HeaderParserResult::Supported(val) = input.1 {
if f as usize == val as usize {
+20 -28
View File
@@ -14,7 +14,7 @@ use std::borrow::Cow;
use crate::{
decoders::{
base64::Base64Decoder,
charsets::map::{decoder_default, get_charset_decoder},
charsets::map::get_charset_decoder,
html::{html_to_text, text_to_html},
quoted_printable::QuotedPrintableDecoder,
},
@@ -38,25 +38,18 @@ enum MimeType {
}
#[inline(always)]
fn bytes_to_string<'x>(
bytes: &'x [u8],
content_type: Option<&ContentType>,
is_utf8_safe: bool,
) -> Cow<'x, str> {
fn bytes_to_string<'x>(bytes: Cow<'x, [u8]>, content_type: Option<&ContentType>) -> Cow<'x, str> {
if let Some(content_type) = content_type {
if let Some(charset) = content_type.get_attribute("charset") {
if let Some(decoder_fnc) = get_charset_decoder(charset.as_bytes()) {
return decoder_fnc(bytes);
return decoder_fnc(bytes.as_ref()).into();
}
}
}
if !is_utf8_safe {
decoder_default(bytes)
} else {
// SAFE: `bytes` slice is ASCII and UTF-8 safe
(unsafe { std::str::from_utf8_unchecked(bytes) }).into()
}
String::from_utf8(bytes.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
#[inline(always)]
@@ -130,16 +123,19 @@ impl<'x> Message<'x> {
}
}
/// Returns `false` if at least one header field was successfully parsed.
pub fn is_empty(&self) -> bool {
self.header.is_empty()
}
/// Parses a byte slice containing the RFC5322 raw message and returns a
/// `Message` struct.
///
/// This function never panics, a best-effort is made to parse the message and
/// if no headers are found and empty `Message` struct is returned.
/// To make sure parsing was successfull use `is_empty()`.
///
/// Note: The `parse()` function requires a mutable `[u8]` as input in order
/// to perform BASE64/Quoted-Printable decoding in-place.
///
pub fn parse(bytes: &'x mut [u8]) -> Message<'x> {
pub fn parse(bytes: &'x [u8]) -> Message<'x> {
let stream = MessageStream::new(bytes);
let mut message = Message::new();
@@ -219,9 +215,7 @@ impl<'x> Message<'x> {
stream.skip_crlf();
let (success, mut is_utf8_safe, mut bytes) = match header
.get_content_transfer_encoding()
{
let (success, mut bytes) = match header.get_content_transfer_encoding() {
Some(encoding) if encoding.eq_ignore_ascii_case("base64") => stream.decode_base64(
state
.mime_boundary
@@ -249,7 +243,7 @@ impl<'x> Message<'x> {
if !success {
if !stream.is_eof() {
// Get raw MIME part
let (success, r_is_utf8_safe, r_bytes) = stream.get_bytes_to_boundary(
let (success, r_bytes) = stream.get_bytes_to_boundary(
state
.mime_boundary
.as_ref()
@@ -258,10 +252,8 @@ impl<'x> Message<'x> {
if !success {
// If there is MIME boundary, ignore it and get raw message
if !stream.is_eof() && state.mime_boundary.is_some() {
let (_, r_is_utf8_safe, r_bytes) =
stream.get_bytes_to_boundary(&[][..]);
let (_, r_bytes) = stream.get_bytes_to_boundary(&[][..]);
if r_bytes.is_some() {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
} else {
break;
@@ -270,7 +262,6 @@ impl<'x> Message<'x> {
break;
}
} else {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
}
mime_type = MimeType::TextOther;
@@ -319,9 +310,8 @@ impl<'x> Message<'x> {
if is_text {
let text_part = TextPart {
contents: bytes_to_string(
bytes.map_or_else(|| "\n".as_bytes(), |v| v),
bytes.unwrap_or_else(|| vec![b'\n'].into()),
header.get_content_type(),
is_utf8_safe,
),
header: if !mime_part_header.is_empty() {
Some(std::mem::take(&mut mime_part_header))
@@ -358,7 +348,7 @@ impl<'x> Message<'x> {
} else {
None
},
contents: bytes.map_or_else(|| "?".as_bytes(), |v| v).into(),
contents: bytes.unwrap_or_else(|| Cow::from(vec![b'?'])),
};
if add_to_html {
@@ -512,6 +502,8 @@ mod tests {
let input = input.split_at_mut(pos);
let message = Message::parse(input.0);
assert!(!message.is_empty());
assert_eq!(
message,
serde_json::from_slice::<Message>(&input.1[SEPARATOR.len()..]).unwrap(),
+97 -172
View File
@@ -9,126 +9,86 @@
* except according to those terms.
*/
use std::{borrow::Cow, cell::UnsafeCell};
use std::{borrow::Cow, cell::Cell};
pub struct MessageStream<'x> {
// SAFE: MessageStream is always executed on a single thread and this struct
// is never shared outside the library.
pub data: UnsafeCell<&'x mut [u8]>,
pub pos: UnsafeCell<usize>,
pub data: &'x [u8],
pub pos: Cell<usize>,
}
impl<'x> MessageStream<'x> {
pub fn new(data: &'x mut [u8]) -> MessageStream<'x> {
pub fn new(data: &'x [u8]) -> MessageStream<'x> {
MessageStream {
data: data.into(),
data,
pos: 0.into(),
}
}
#[inline(always)]
pub fn get_bytes(&self, from: usize, to: usize) -> Option<&'x [u8]> {
// SAFE: exclusive access to `data`
unsafe { (*self.data.get()).get(from..to) }
self.data.get(from..to)
}
pub fn get_string(&self, from: usize, to: usize, utf8_valid: bool) -> Option<Cow<'x, str>> {
// SAFE: exclusive access to `data`
unsafe {
if utf8_valid {
// SAFE: slice region is US-ASCII and UTF-8 safe
Cow::from(std::str::from_utf8_unchecked(
(*self.data.get()).get(from..to)?,
))
.into()
} else {
String::from_utf8_lossy((*self.data.get()).get(from..to)?).into()
}
}
pub fn get_string(&self, from: usize, to: usize) -> Option<Cow<'x, str>> {
String::from_utf8_lossy(self.data.get(from..to)?).into()
}
#[inline(always)]
pub fn is_eof(&self) -> bool {
// SAFE: exclusive access to `data` and `pos`
unsafe { *self.pos.get() >= (*self.data.get()).len() }
self.pos.get() >= self.data.len()
}
#[inline(always)]
pub fn set_pos(&self, pos: usize) {
// SAFE: exclusive access to `pos`
unsafe {
*self.pos.get() = pos;
}
self.pos.set(pos);
}
#[inline(always)]
pub fn get_pos(&self) -> usize {
// SAFE: exclusive access to `pos`
unsafe { *self.pos.get() }
self.pos.get()
}
#[inline(always)]
pub fn next(&self) -> Option<&'x u8> {
unsafe {
// SAFE: exclusive access to `data` and `pos`
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
if *pos < data.len() {
// SAFE: bounds are checked
let result = data.get_unchecked(*pos);
*pos += 1;
Some(result)
} else {
None
}
}
let pos = self.pos.get();
let result = self.data.get(pos);
self.pos.set(pos + 1);
result
}
#[inline(always)]
pub fn peek(&self) -> Option<&'x u8> {
// SAFE: exclusive access to `data` and `pos`
unsafe { (*self.data.get()).get(*self.pos.get()) }
self.data.get(self.pos.get())
}
#[inline(always)]
pub fn advance(&self, pos: usize) {
// SAFE: exclusive access to `pos`
unsafe {
*self.pos.get() += pos;
}
self.pos.set(self.pos.get() + pos)
}
pub fn seek_next_part(&self, boundary: &[u8]) -> bool {
if !boundary.is_empty() {
unsafe {
// SAFE: exclusive access to `data` and `pos`
let cur_pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let mut pos = self.pos.get();
let mut pos = *cur_pos;
let mut match_count = 0;
let mut match_count = 0;
for ch in (*data)[*cur_pos..].iter() {
pos += 1;
for ch in self.data[pos..].iter() {
pos += 1;
// SAFE: bounds are checked after the first match occurs
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
*cur_pos = pos;
return true;
} else {
continue;
}
} else if match_count > 0 {
// SAFE: `boundary` can't be empty
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
} else {
match_count = 0;
}
if ch == &boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
self.pos.set(pos);
return true;
} else {
continue;
}
} else if match_count > 0 {
if ch == &boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
@@ -137,145 +97,110 @@ impl<'x> MessageStream<'x> {
false
}
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
// SAFE: exclusive access to `data` and `pos`
let mut data = &mut *self.data.get();
let stream_pos = &mut *self.pos.get();
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, Option<Cow<'x, [u8]>>) {
let mut pos = self.pos.get();
let start_pos = *stream_pos;
let start_pos = pos;
return if !boundary.is_empty() {
let mut pos = *stream_pos;
let mut match_count = 0;
let mut is_utf8_safe = true;
return if !boundary.is_empty() {
let mut match_count = 0;
for ch in (*data)[pos..].iter() {
pos += 1;
for ch in self.data[pos..].iter() {
pos += 1;
if is_utf8_safe && *ch > 0x7f {
is_utf8_safe = false;
}
if ch == &boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
if self.is_boundary_end(pos) {
let match_pos = pos - match_count;
self.pos.set(pos);
// SAFE: bounds are checked after the first match occurs
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
// SAFE: exclusive access to `self.data` is re-obtained after
// is_boundary_end finishes.
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;
return (
true,
is_utf8_safe,
if start_pos < match_pos {
(*data).get(start_pos..match_pos)
} else {
None
},
);
} else {
match_count = 0;
}
}
continue;
} else if match_count > 0 {
// SAFE: `boundary` is never empty
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
return (
true,
if start_pos < match_pos {
Cow::from(&self.data[start_pos..match_pos]).into()
} else {
None
},
);
} else {
match_count = 0;
}
}
continue;
} else if match_count > 0 {
if ch == &boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
(false, false, None)
} else if *stream_pos < (*data).len() {
*stream_pos = (*data).len();
(true, false, (*data).get(start_pos..))
} else {
(false, false, None)
};
}
(false, None)
} else if pos < self.data.len() {
self.pos.set(self.data.len());
(true, Cow::from(&self.data[start_pos..]).into())
} else {
(false, None)
};
}
#[inline(always)]
pub fn skip_crlf(&self) {
unsafe {
// SAFE: exclusive access to `data` and `pos`
let cur_pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let mut pos = self.pos.get();
let mut pos = *cur_pos;
for ch in (*data)[*cur_pos..].iter() {
match ch {
b'\r' | b' ' | b'\t' => pos += 1,
b'\n' => {
*cur_pos = pos + 1;
break;
}
_ => break,
for ch in self.data[pos..].iter() {
match ch {
b'\r' | b' ' | b'\t' => pos += 1,
b'\n' => {
self.pos.set(pos + 1);
break;
}
_ => break,
}
}
}
#[inline(always)]
pub fn skip_byte(&self, ch: &u8) -> bool {
unsafe {
// SAFE: exclusive access to `data` and `pos`
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let pos = self.pos.get();
if (*data).get(*pos) == Some(ch) {
*pos += 1;
true
} else {
false
}
if self.data.get(pos) == Some(ch) {
self.pos.set(pos + 1);
true
} else {
false
}
}
#[inline(always)]
pub fn is_boundary_end(&self, pos: usize) -> bool {
// SAFE: exclusive access to `data` and `pos`
matches!(
unsafe { (*self.data.get()).get(pos..) },
self.data.get(pos..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
)
}
pub fn skip_multipart_end(&self) -> bool {
unsafe {
// SAFE: exclusive access to `pos`
let pos = &mut *self.pos.get();
let pos = self.pos.get();
match (*self.data.get()).get(*pos..*pos + 2) {
Some(b"--") => {
if let Some(byte) = (*self.data.get()).get(*pos + 2) {
if !(*byte).is_ascii_whitespace() {
return false;
}
match self.data.get(pos..pos + 2) {
Some(b"--") => {
if let Some(byte) = self.data.get(pos + 2) {
if !(*byte).is_ascii_whitespace() {
return false;
}
*pos += 2;
true
}
_ => false,
self.pos.set(pos + 2);
true
}
_ => false,
}
}
pub fn rewind(&self, r: usize) {
// SAFE: exclusive access to `pos`
unsafe {
*self.pos.get() -= r;
}
self.pos.set(self.pos.get() - r);
}
}