Refactoring or MessageStream to use iterators more efficiently.

This commit is contained in:
Mauro D
2022-10-13 14:09:43 +00:00
parent ef19d20f9c
commit 6fcc57a3d9
117 changed files with 113078 additions and 2038 deletions
+172 -178
View File
@@ -11,7 +11,7 @@
use std::borrow::Cow;
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
pub fn decode_base64(bytes: &[u8]) -> Option<Vec<u8>> {
let mut chunk: u32 = 0;
@@ -79,214 +79,209 @@ pub fn decode_base64(bytes: &[u8]) -> Option<Vec<u8>> {
buf.into()
}
//impl<'x> MessageStream<'x> {
impl<'x> MessageStream<'x> {
pub fn decode_base64_mime(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
pub fn decode_base64_mime<'x>(
stream: &mut MessageStream<'x>,
boundary: &[u8],
) -> (usize, Cow<'x, [u8]>) {
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut buf = Vec::with_capacity(self.remaining() / 4 * 3);
let mut last_ch = b'\n';
let mut before_last_ch = 0;
let mut end_pos = self.offset();
let mut buf = Vec::with_capacity((stream.data.len() - stream.pos) / 4 * 3);
let mut pos = stream.pos;
self.checkpoint();
let mut last_ch = b'\n';
let mut end_pos = stream.pos;
let mut iter = stream.data[stream.pos..].iter();
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];
while let Some(&ch) = iter.next() {
pos += 1;
if val < 0x01ffffff {
byte_count = (byte_count + 1) & 3;
#[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 byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if val < 0x01ffffff {
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if byte_count == 0 {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3));
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]);
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
} else {
match ch {
b'=' => match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
} else {
match ch {
b'=' => match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
self.restore();
return (usize::MAX, b""[..].into());
}
},
b'\n' => {
end_pos = if last_ch == b'\r' {
self.offset() - 2
} else {
self.offset() - 1
}
}
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
b' ' | b'\t' | b'\r' => (),
b'-' => {
if last_ch == b'-' {
return if !boundary.is_empty() && self.try_skip(boundary) {
buf.shrink_to_fit();
(
if before_last_ch == b'\n' {
end_pos
} else {
self.offset() - boundary.len() - 2
},
buf.into(),
)
} else {
self.restore();
(usize::MAX, b""[..].into())
};
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
self.restore();
return (usize::MAX, b""[..].into());
}
},
b'\n' => end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 },
b' ' | b'\t' | b'\r' => (),
b'-' => {
return if !boundary.is_empty()
&& matches!(iter.next(), Some(b'-'))
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
&& matches!(
stream.data.get(pos + 1 + boundary.len()..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
| Some([b'-', b'-', ..])
| Some([])
| None
) {
stream.pos = pos + boundary.len() + 1;
buf.shrink_to_fit();
(if last_ch == b'\n' { end_pos } else { pos - 1 }, buf.into())
} else {
(usize::MAX, b""[..].into())
};
}
_ => {
return (usize::MAX, b""[..].into());
}
}
before_last_ch = last_ch;
last_ch = ch;
}
last_ch = ch;
buf.shrink_to_fit();
(
if boundary.is_empty() {
self.offset()
} else {
self.restore();
usize::MAX
},
buf.into(),
)
}
buf.shrink_to_fit();
(
if boundary.is_empty() {
stream.pos = pos;
pos
} else {
usize::MAX
},
buf.into(),
)
}
pub fn decode_base64_word(&mut self) -> Option<Vec<u8>> {
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut buf = Vec::with_capacity(64);
pub fn decode_base64_word(bytes: &[u8]) -> (usize, Vec<u8>) {
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut bytes_read = 0;
let mut buf = Vec::with_capacity(64);
let mut iter = bytes.iter();
while let Some(&ch) = iter.next() {
bytes_read += 1;
match ch {
b'=' => {
match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
while let Some(&ch) = self.next() {
match ch {
b'=' => {
match byte_count {
1 | 2 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.push(*chunk.to_le_bytes().get_unchecked(0));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
3 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..2));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
// Invalid
break;
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
// Invalid
}
b'?' => {
if let Some(b'=') = self.next() {
return Some(buf);
} else {
break;
}
}
b'\n' => {
if !self.next_is_space() {
break;
}
}
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 {
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if byte_count == 0 {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
} else {
break;
}
}
}
b'?' => {
if let Some(b'=') = iter.next() {
return (bytes_read + 1, buf);
} else {
break;
}
}
b'\n' => {
if let Some(b' ' | b'\t') = iter.next() {
bytes_read += 1;
} else {
break;
}
}
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 {
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if byte_count == 0 {
#[cfg(feature = "ludicrous_mode")]
unsafe {
buf.extend_from_slice(chunk.to_le_bytes().get_unchecked(0..3));
}
#[cfg(not(feature = "ludicrous_mode"))]
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
} else {
break;
}
}
}
}
(usize::MAX, buf)
None
}
}
//}
#[cfg(test)]
mod tests {
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
#[test]
fn decode_base64() {
@@ -346,7 +341,7 @@ mod tests {
),
] {
let mut s = MessageStream::new(encoded_str.as_bytes());
let (_, result) = super::decode_base64_mime(&mut s, b"boundary");
let (_, result) = s.decode_base64_mime(b"boundary");
assert_eq!(
result,
@@ -366,10 +361,9 @@ mod tests {
("w6HDqcOtw7PDug================?=", "áéíóú"),
("?=", ""),
] {
let (bytes, result) = super::decode_base64_word(encoded_str.as_bytes());
assert!(bytes != usize::MAX);
let mut s = MessageStream::new(encoded_str.as_bytes());
assert_eq!(
result,
s.decode_base64_word().unwrap(),
expected_result.as_bytes(),
"Failed for {:?}",
encoded_str
+68 -77
View File
@@ -9,11 +9,9 @@
* except according to those terms.
*/
use crate::{decoders::charsets::map::get_charset_decoder, parsers::message::MessageStream};
use crate::{decoders::charsets::map::get_charset_decoder, parsers::MessageStream};
use super::{
base64::decode_base64_word, quoted_printable::decode_quoted_printable_word, DecodeWordFnc,
};
use super::DecodeWordFnc;
enum Rfc2047State {
Init,
@@ -22,89 +20,82 @@ enum Rfc2047State {
Data,
}
pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Option<String>) {
let mut read_pos: usize = start_pos;
let mut state = Rfc2047State::Init;
impl<'x> MessageStream<'x> {
pub fn decode_rfc2047(&mut self) -> Option<String> {
let mut state = Rfc2047State::Init;
let mut charset_start = 0;
let mut charset_end = 0;
let mut decode_fnc: Option<DecodeWordFnc> = None;
let mut charset_start = 0;
let mut charset_end = 0;
let mut decode_fnc: Option<DecodeWordFnc> = None;
for ch in stream.data[start_pos..].iter() {
read_pos += 1;
match state {
Rfc2047State::Init => {
if ch != &b'?' {
return (0, None);
}
state = Rfc2047State::Charset;
charset_start = read_pos;
charset_end = read_pos;
}
Rfc2047State::Charset => match ch {
b'?' => {
if charset_end == charset_start {
charset_end = read_pos - 1;
while let Some(ch) = self.next() {
match state {
Rfc2047State::Init => {
if ch != &b'?' {
return None;
}
if (charset_end - charset_start) < 2 {
return (0, None);
state = Rfc2047State::Charset;
charset_start = self.offset();
charset_end = self.offset();
}
Rfc2047State::Charset => match ch {
b'?' => {
if charset_end == charset_start {
charset_end = self.offset() - 1;
}
if (charset_end - charset_start) < 2 {
return None;
}
state = Rfc2047State::Encoding;
}
state = Rfc2047State::Encoding;
}
b'*' => {
if charset_end == charset_start {
charset_end = read_pos - 1;
b'*' => {
if charset_end == charset_start {
charset_end = self.offset() - 1;
}
}
}
b'\n' => {
return (0, None);
}
_ => (),
},
Rfc2047State::Encoding => {
match ch {
b'q' | b'Q' => decode_fnc = Some(decode_quoted_printable_word),
b'b' | b'B' => decode_fnc = Some(decode_base64_word),
_ => {
return (0, None);
b'\n' => {
return None;
}
}
state = Rfc2047State::Data;
}
Rfc2047State::Data => {
if ch != &b'?' {
return (0, None);
} else {
break;
}
}
}
}
if let (Some(decode_fnc), Some(enc_bytes)) = (decode_fnc, stream.data.get(read_pos..)) {
let (bytes_read, bytes) = decode_fnc(enc_bytes);
if bytes_read != usize::MAX {
return (
(read_pos - start_pos) + bytes_read,
if let Some(decoder) = get_charset_decoder(&stream.data[charset_start..charset_end])
{
decoder(&bytes).into()
} else {
String::from_utf8(bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
_ => (),
},
);
Rfc2047State::Encoding => {
match ch {
b'q' | b'Q' => {
decode_fnc = Some(MessageStream::decode_quoted_printable_word)
}
b'b' | b'B' => decode_fnc = Some(MessageStream::decode_base64_word),
_ => {
return None;
}
}
state = Rfc2047State::Data;
}
Rfc2047State::Data => {
if ch != &b'?' {
return None;
} else {
break;
}
}
}
}
if let Some(bytes) = decode_fnc.and_then(|fnc| fnc(self)) {
if let Some(decoder) = get_charset_decoder(self.get_bytes(charset_start..charset_end)) {
decoder(&bytes).into()
} else {
String::from_utf8(bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
} else {
None
}
}
(0, None)
}
#[cfg(test)]
mod tests {
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
#[test]
fn decode_rfc2047() {
@@ -176,8 +167,8 @@ mod tests {
true,
),
] {
match super::decode_rfc2047(&MessageStream::new(input.as_bytes()), 0) {
(_, Some(result)) => {
match MessageStream::new(input.as_bytes()).decode_rfc2047() {
Some(result) => {
//println!("Decoded '{}'", string);
assert_eq!(result, expected_result);
}
+2 -2
View File
@@ -11,7 +11,7 @@
use std::borrow::Cow;
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
pub mod base64;
pub mod charsets;
@@ -21,4 +21,4 @@ pub mod html;
pub mod quoted_printable;
pub type DecodeFnc<'x> = fn(&mut MessageStream<'x>, &[u8]) -> (usize, Cow<'x, [u8]>);
pub type DecodeWordFnc<'x> = fn(&[u8]) -> (usize, Vec<u8>);
pub type DecodeWordFnc<'x> = fn(&mut MessageStream<'x>) -> Option<Vec<u8>>;
+154 -170
View File
@@ -11,7 +11,7 @@
use std::borrow::Cow;
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
#[derive(PartialEq, Debug)]
enum QuotedPrintableState {
@@ -83,199 +83,186 @@ pub fn decode_quoted_printable(bytes: &[u8]) -> Option<Vec<u8>> {
buf.into()
}
pub fn decode_quoted_printable_mime<'x>(
stream: &mut MessageStream<'x>,
boundary: &[u8],
) -> (usize, Cow<'x, [u8]>) {
let mut buf = Vec::with_capacity(stream.data.len() - stream.pos);
impl<'x> MessageStream<'x> {
pub fn decode_quoted_printable_mime(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
let mut buf = Vec::with_capacity(128);
let mut state = QuotedPrintableState::None;
let mut hex1 = 0;
let mut state = QuotedPrintableState::None;
let mut hex1 = 0;
let mut last_ch = 0;
let mut before_last_ch = 0;
let mut end_pos = self.offset();
let mut iter = stream.data[stream.pos..].iter().peekable();
let mut last_ch = 0;
let mut pos = stream.pos;
let mut end_pos = stream.pos;
self.checkpoint();
while let Some(&ch) = iter.next() {
pos += 1;
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
return (usize::MAX, b""[..].into());
while let Some(&ch) = self.next() {
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
self.restore();
return (usize::MAX, b""[..].into());
}
}
}
b'\n' => {
end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 };
if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
buf.push(b'\n');
}
}
b'\r' => (),
b'-' if !boundary.is_empty()
&& matches!(iter.peek(), Some(b'-'))
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
&& matches!(
stream.data.get(pos + 1 + boundary.len()..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
| Some([b'-', b'-', ..])
| Some([])
| None
) =>
{
if last_ch == b'\n' {
buf.pop();
} else {
end_pos = pos - 1;
}
stream.pos = pos + boundary.len() + 1;
buf.shrink_to_fit();
return (end_pos, buf.into());
}
_ => match state {
QuotedPrintableState::None => {
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]
b'\n' => {
end_pos = if last_ch == b'\r' {
self.offset() - 2
} else {
self.offset() - 1
};
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
return (usize::MAX, b""[..].into());
buf.push(b'\n');
}
}
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];
b'\r' => (),
b'-' if !boundary.is_empty() && last_ch == b'-' && self.try_skip(boundary) => {
if before_last_ch == b'\n' {
buf.truncate(buf.len() - 2);
} else {
buf.truncate(buf.len() - 1);
end_pos = self.offset() - boundary.len() - 2;
}
state = QuotedPrintableState::None;
if hex2 != -1 {
buf.push(((hex1 as u8) << 4) | hex2 as u8);
} else {
return (usize::MAX, b""[..].into());
}
return (end_pos, buf.into());
}
},
_ => match state {
QuotedPrintableState::None => {
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]
};
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
self.restore();
return (usize::MAX, b""[..].into());
}
}
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);
} else {
self.restore();
return (usize::MAX, b""[..].into());
}
}
},
}
before_last_ch = last_ch;
last_ch = ch;
}
last_ch = ch;
(
if boundary.is_empty() {
self.offset()
} else {
self.restore();
usize::MAX
},
buf.into(),
)
}
buf.shrink_to_fit();
(
if boundary.is_empty() {
stream.pos = pos;
pos
} else {
usize::MAX
},
buf.into(),
)
}
pub fn decode_quoted_printable_word(&mut self) -> Option<Vec<u8>> {
let mut buf = Vec::with_capacity(64);
pub fn decode_quoted_printable_word(bytes: &[u8]) -> (usize, Vec<u8>) {
let mut bytes_read = 0;
let mut state = QuotedPrintableState::None;
let mut hex1 = 0;
let mut buf = Vec::with_capacity(64);
let mut state = QuotedPrintableState::None;
let mut hex1 = 0;
let mut iter = bytes.iter().peekable();
while let Some(&ch) = iter.next() {
bytes_read += 1;
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
break;
while let Some(&ch) = self.next() {
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
break;
}
}
}
b'?' => {
if let Some(b'=') = iter.peek() {
return (bytes_read + 1, buf);
} else {
buf.push(b'?');
b'?' => {
if let Some(b'=') = self.peek() {
self.next();
return buf.into();
} else {
buf.push(b'?');
}
}
}
b'\n' => {
if let Some(b' ' | b'\t') = iter.peek() {
loop {
iter.next();
bytes_read += 1;
if !matches!(iter.peek(), Some(b' ' | b'\t')) {
b'\n' => {
if let Some(b' ' | b'\t') = self.peek() {
loop {
self.next();
if !self.peek_next_is_space() {
break;
}
}
} else {
break;
}
}
b'_' => {
buf.push(b' ');
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
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]
};
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
// Failed
break;
}
}
} else {
break;
}
}
b'_' => {
buf.push(b' ');
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
buf.push(ch);
}
QuotedPrintableState::Eq => {
hex1 = {
QuotedPrintableState::Hex1 => {
#[cfg(feature = "ludicrous_mode")]
unsafe {
*HEX_MAP.get_unchecked(ch as usize)
}
let hex2 = unsafe { *HEX_MAP.get_unchecked(ch as usize) };
#[cfg(not(feature = "ludicrous_mode"))]
HEX_MAP[ch as usize]
};
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
// Failed
break;
}
}
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];
let hex2 = HEX_MAP[ch as usize];
state = QuotedPrintableState::None;
if hex2 != -1 {
buf.push(((hex1 as u8) << 4) | hex2 as u8);
} else {
// Failed
break;
state = QuotedPrintableState::None;
if hex2 != -1 {
buf.push(((hex1 as u8) << 4) | hex2 as u8);
} else {
// Failed
break;
}
}
}
},
},
}
}
None
}
(usize::MAX, buf)
}
#[cfg(test)]
mod tests {
use crate::parsers::message::MessageStream;
use crate::parsers::MessageStream;
#[test]
fn decode_quoted_printable() {
@@ -378,7 +365,7 @@ mod tests {
),
] {
let mut s = MessageStream::new(encoded_str.as_bytes());
let (_, result) = super::decode_quoted_printable_mime(&mut s, b"boundary");
let (_, result) = s.decode_quoted_printable_mime(b"boundary");
assert_eq!(
result,
@@ -407,13 +394,10 @@ mod tests {
("????????=", "???????"),
("\n\n", ""),
] {
let (bytes, mut result) = super::decode_quoted_printable_word(encoded_str.as_bytes());
if bytes == usize::MAX {
result.clear();
}
let mut s = MessageStream::new(encoded_str.as_bytes());
assert_eq!(
result,
s.decode_quoted_printable_word().unwrap_or_default(),
expected_result.as_bytes(),
"Failed for {:?}",
encoded_str
+323 -338
View File
@@ -11,10 +11,7 @@
use std::borrow::Cow;
use crate::{
decoders::encoded_word::decode_rfc2047, parsers::message::MessageStream, Addr, Group,
HeaderValue,
};
use crate::{parsers::MessageStream, Addr, Group, HeaderValue};
#[derive(PartialEq, Clone, Copy, Debug)]
enum AddressState {
@@ -45,45 +42,336 @@ pub struct AddressParser<'x> {
result: Vec<Group<'x>>,
}
pub fn add_token<'x>(
parser: &mut AddressParser<'x>,
stream: &MessageStream<'x>,
add_trail_space: bool,
) {
if parser.token_start > 0 {
let token = String::from_utf8_lossy(&stream.data[parser.token_start - 1..parser.token_end]);
let mut add_space = false;
let list = match parser.state {
AddressState::Address => &mut parser.mail_tokens,
AddressState::Name => {
if parser.is_token_email {
&mut parser.mail_tokens
} else {
add_space = true;
&mut parser.name_tokens
impl<'x> AddressParser<'x> {
pub fn add_token(&mut self, stream: &MessageStream<'x>, add_trail_space: bool) {
if self.token_start > 0 {
let token = String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end]);
let mut add_space = false;
let list = match self.state {
AddressState::Address => &mut self.mail_tokens,
AddressState::Name => {
if self.is_token_email {
&mut self.mail_tokens
} else {
add_space = true;
&mut self.name_tokens
}
}
AddressState::Quote => &mut self.name_tokens,
AddressState::Comment => {
add_space = true;
&mut self.comment_tokens
}
};
if add_space && !list.is_empty() {
list.push(" ".into());
}
AddressState::Quote => &mut parser.name_tokens,
AddressState::Comment => {
add_space = true;
&mut parser.comment_tokens
list.push(token);
if add_trail_space {
list.push(" ".into());
}
self.token_start = 0;
self.is_token_email = false;
self.is_token_start = true;
self.is_escaped = false;
}
}
pub fn add_address(&mut self) {
let has_mail = !self.mail_tokens.is_empty();
let has_name = !self.name_tokens.is_empty();
let has_comment = !self.comment_tokens.is_empty();
self.addresses.push(if has_mail && has_name && has_comment {
Addr {
name: Some(
format!(
"{} ({})",
concat_tokens(&mut self.name_tokens),
concat_tokens(&mut self.comment_tokens)
)
.into(),
),
address: concat_tokens(&mut self.mail_tokens).into(),
}
} else if has_name && has_mail {
Addr {
name: concat_tokens(&mut self.name_tokens).into(),
address: concat_tokens(&mut self.mail_tokens).into(),
}
} else if has_mail && has_comment {
Addr {
name: concat_tokens(&mut self.comment_tokens).into(),
address: concat_tokens(&mut self.mail_tokens).into(),
}
} else if has_mail {
Addr {
name: None,
address: concat_tokens(&mut self.mail_tokens).into(),
}
} else if has_name && has_comment {
Addr {
name: concat_tokens(&mut self.comment_tokens).into(),
address: concat_tokens(&mut self.name_tokens).into(),
}
} else if has_name {
Addr {
name: concat_tokens(&mut self.name_tokens).into(),
address: None,
}
} else if has_comment {
Addr {
name: concat_tokens(&mut self.comment_tokens).into(),
address: None,
}
} else {
return;
});
}
pub fn add_group_details(&mut self) {
if !self.name_tokens.is_empty() {
self.group_name = concat_tokens(&mut self.name_tokens).into();
}
if !self.comment_tokens.is_empty() {
self.group_comment = concat_tokens(&mut self.comment_tokens).into();
}
if !self.mail_tokens.is_empty() {
if self.group_name.is_none() {
self.group_name = concat_tokens(&mut self.mail_tokens).into();
} else {
self.group_name = Some(
(self.group_name.as_ref().unwrap().as_ref().to_owned()
+ " "
+ concat_tokens(&mut self.mail_tokens).as_ref())
.into(),
);
}
}
}
pub fn add_group(&mut self) {
let has_name = self.group_name.is_some();
let has_comment = self.group_comment.is_some();
let has_addresses = !self.addresses.is_empty();
self.result
.push(if has_name && has_addresses && has_comment {
Group {
name: Some(
format!(
"{} ({})",
self.group_name.take().unwrap(),
self.group_comment.take().unwrap()
)
.into(),
),
addresses: std::mem::take(&mut self.addresses),
}
} else if has_addresses && has_name {
Group {
name: self.group_name.take(),
addresses: std::mem::take(&mut self.addresses),
}
} else if has_addresses {
Group {
name: self.group_comment.take(),
addresses: std::mem::take(&mut self.addresses),
}
} else if has_name {
Group {
name: self.group_name.take(),
addresses: Vec::new(),
}
} else {
return;
});
}
}
impl<'x> MessageStream<'x> {
pub fn parse_address(&mut self) -> HeaderValue<'x> {
let mut parser = AddressParser {
token_start: 0,
token_end: 0,
is_token_email: false,
is_token_start: true,
is_escaped: false,
name_tokens: Vec::with_capacity(3),
mail_tokens: Vec::with_capacity(3),
comment_tokens: Vec::with_capacity(3),
state: AddressState::Name,
state_stack: Vec::with_capacity(5),
addresses: Vec::new(),
group_name: None,
group_comment: None,
result: Vec::new(),
};
if add_space && !list.is_empty() {
list.push(" ".into());
while let Some(ch) = self.next() {
match ch {
b'\n' => {
parser.add_token(self, false);
if self.try_next_is_space() {
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
} else {
break;
}
}
b'\\' if parser.state != AddressState::Name => {
if parser.token_start > 0 {
if parser.state == AddressState::Quote {
parser.token_end = self.offset() - 1;
}
parser.add_token(self, false);
}
parser.is_escaped = true;
continue;
}
b',' if parser.state == AddressState::Name => {
parser.add_token(self, false);
parser.add_address();
continue;
}
b'<' if parser.state == AddressState::Name => {
parser.add_token(self, false);
parser.state_stack.push(AddressState::Name);
parser.state = AddressState::Address;
continue;
}
b'>' if parser.state == AddressState::Address => {
parser.add_token(self, false);
parser.state = parser.state_stack.pop().unwrap();
continue;
}
b'"' if !parser.is_escaped => match parser.state {
AddressState::Name => {
parser.state_stack.push(AddressState::Name);
parser.state = AddressState::Quote;
parser.add_token(self, false);
continue;
}
AddressState::Quote => {
parser.add_token(self, false);
parser.state = parser.state_stack.pop().unwrap();
continue;
}
_ => (),
},
b'@' if parser.state == AddressState::Name => {
parser.is_token_email = true;
}
b'=' if parser.is_token_start && !parser.is_escaped && self.peek_char(b'?') => {
self.checkpoint();
if let Some(token) = self.decode_rfc2047() {
let add_space = parser.state != AddressState::Quote; // Make borrow-checker happy
parser.add_token(self, add_space);
(if parser.state != AddressState::Comment {
&mut parser.name_tokens
} else {
&mut parser.comment_tokens
})
.push(token.into());
continue;
}
self.restore();
}
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.state == AddressState::Quote {
if parser.token_start == 0 {
parser.token_start = self.offset();
parser.token_end = parser.token_start;
} else {
parser.token_end = self.offset();
}
}
continue;
}
b'\r' => continue,
b'(' if parser.state != AddressState::Quote && !parser.is_escaped => {
parser.state_stack.push(parser.state);
if parser.state != AddressState::Comment {
parser.add_token(self, false);
parser.state = AddressState::Comment;
continue;
}
}
b')' if parser.state == AddressState::Comment && !parser.is_escaped => {
let new_state = parser.state_stack.pop().unwrap();
if parser.state != new_state {
parser.add_token(self, false);
parser.state = new_state;
continue;
}
}
b':' if parser.state == AddressState::Name && !parser.is_escaped => {
parser.add_group();
parser.add_token(self, false);
parser.add_group_details();
continue;
}
b';' if parser.state == AddressState::Name => {
parser.add_token(self, false);
parser.add_address();
parser.add_group();
continue;
}
_ => (),
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.is_token_start {
parser.is_token_start = false;
}
if parser.token_start == 0 {
parser.token_start = self.offset();
parser.token_end = parser.token_start;
} else {
parser.token_end = self.offset();
}
}
list.push(token);
parser.add_address();
if add_trail_space {
list.push(" ".into());
if parser.group_name.is_some() || !parser.result.is_empty() {
parser.add_group();
if parser.result.len() > 1 {
HeaderValue::GroupList(parser.result)
} else {
HeaderValue::Group(parser.result.pop().unwrap())
}
} else if !parser.addresses.is_empty() {
if parser.addresses.len() > 1 {
HeaderValue::AddressList(parser.addresses)
} else {
HeaderValue::Address(parser.addresses.pop().unwrap())
}
} else {
HeaderValue::Empty
}
parser.token_start = 0;
parser.is_token_email = false;
parser.is_token_start = true;
parser.is_escaped = false;
}
}
@@ -97,307 +385,6 @@ fn concat_tokens<'x>(tokens: &mut Vec<Cow<'x, str>>) -> Cow<'x, str> {
}
}
pub fn add_address(parser: &mut AddressParser) {
let has_mail = !parser.mail_tokens.is_empty();
let has_name = !parser.name_tokens.is_empty();
let has_comment = !parser.comment_tokens.is_empty();
parser
.addresses
.push(if has_mail && has_name && has_comment {
Addr {
name: Some(
format!(
"{} ({})",
concat_tokens(&mut parser.name_tokens),
concat_tokens(&mut parser.comment_tokens)
)
.into(),
),
address: concat_tokens(&mut parser.mail_tokens).into(),
}
} else if has_name && has_mail {
Addr {
name: concat_tokens(&mut parser.name_tokens).into(),
address: concat_tokens(&mut parser.mail_tokens).into(),
}
} else if has_mail && has_comment {
Addr {
name: concat_tokens(&mut parser.comment_tokens).into(),
address: concat_tokens(&mut parser.mail_tokens).into(),
}
} else if has_mail {
Addr {
name: None,
address: concat_tokens(&mut parser.mail_tokens).into(),
}
} else if has_name && has_comment {
Addr {
name: concat_tokens(&mut parser.comment_tokens).into(),
address: concat_tokens(&mut parser.name_tokens).into(),
}
} else if has_name {
Addr {
name: concat_tokens(&mut parser.name_tokens).into(),
address: None,
}
} else if has_comment {
Addr {
name: concat_tokens(&mut parser.comment_tokens).into(),
address: None,
}
} else {
return;
});
}
pub fn add_group_details(parser: &mut AddressParser) {
if !parser.name_tokens.is_empty() {
parser.group_name = concat_tokens(&mut parser.name_tokens).into();
}
if !parser.comment_tokens.is_empty() {
parser.group_comment = concat_tokens(&mut parser.comment_tokens).into();
}
if !parser.mail_tokens.is_empty() {
if parser.group_name.is_none() {
parser.group_name = concat_tokens(&mut parser.mail_tokens).into();
} else {
parser.group_name = Some(
(parser.group_name.as_ref().unwrap().as_ref().to_owned()
+ " "
+ concat_tokens(&mut parser.mail_tokens).as_ref())
.into(),
);
}
}
}
pub fn add_group(parser: &mut AddressParser) {
let has_name = parser.group_name.is_some();
let has_comment = parser.group_comment.is_some();
let has_addresses = !parser.addresses.is_empty();
parser
.result
.push(if has_name && has_addresses && has_comment {
Group {
name: Some(
format!(
"{} ({})",
parser.group_name.take().unwrap(),
parser.group_comment.take().unwrap()
)
.into(),
),
addresses: std::mem::take(&mut parser.addresses),
}
} else if has_addresses && has_name {
Group {
name: parser.group_name.take(),
addresses: std::mem::take(&mut parser.addresses),
}
} else if has_addresses {
Group {
name: parser.group_comment.take(),
addresses: std::mem::take(&mut parser.addresses),
}
} else if has_name {
Group {
name: parser.group_name.take(),
addresses: Vec::new(),
}
} else {
return;
});
}
pub fn parse_address<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut parser = AddressParser {
token_start: 0,
token_end: 0,
is_token_email: false,
is_token_start: true,
is_escaped: false,
name_tokens: Vec::with_capacity(3),
mail_tokens: Vec::with_capacity(3),
comment_tokens: Vec::with_capacity(3),
state: AddressState::Name,
state_stack: Vec::with_capacity(5),
addresses: Vec::new(),
group_name: None,
group_comment: None,
result: Vec::new(),
};
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => {
add_token(&mut parser, stream, false);
match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
}
_ => break,
}
}
b'\\' if parser.state != AddressState::Name => {
if parser.token_start > 0 {
if parser.state == AddressState::Quote {
parser.token_end = stream.pos - 1;
}
add_token(&mut parser, stream, false);
}
parser.is_escaped = true;
continue;
}
b',' if parser.state == AddressState::Name => {
add_token(&mut parser, stream, false);
add_address(&mut parser);
continue;
}
b'<' if parser.state == AddressState::Name => {
add_token(&mut parser, stream, false);
parser.state_stack.push(AddressState::Name);
parser.state = AddressState::Address;
continue;
}
b'>' if parser.state == AddressState::Address => {
add_token(&mut parser, stream, false);
parser.state = parser.state_stack.pop().unwrap();
continue;
}
b'"' if !parser.is_escaped => match parser.state {
AddressState::Name => {
parser.state_stack.push(AddressState::Name);
parser.state = AddressState::Quote;
add_token(&mut parser, stream, false);
continue;
}
AddressState::Quote => {
add_token(&mut parser, stream, false);
parser.state = parser.state_stack.pop().unwrap();
continue;
}
_ => (),
},
b'@' if parser.state == AddressState::Name => {
parser.is_token_email = true;
}
b'=' if parser.is_token_start && !parser.is_escaped => {
if let (d_bytes_read, Some(token)) = decode_rfc2047(stream, stream.pos) {
let add_space = parser.state != AddressState::Quote; // Make borrow-checker happy
add_token(&mut parser, stream, add_space);
(if parser.state != AddressState::Comment {
&mut parser.name_tokens
} else {
&mut parser.comment_tokens
})
.push(token.into());
stream.pos += d_bytes_read;
iter = stream.data[stream.pos..].iter();
continue;
}
}
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.state == AddressState::Quote {
if parser.token_start == 0 {
parser.token_start = stream.pos;
parser.token_end = parser.token_start;
} else {
parser.token_end = stream.pos;
}
}
continue;
}
b'\r' => continue,
b'(' if parser.state != AddressState::Quote && !parser.is_escaped => {
parser.state_stack.push(parser.state);
if parser.state != AddressState::Comment {
add_token(&mut parser, stream, false);
parser.state = AddressState::Comment;
continue;
}
}
b')' if parser.state == AddressState::Comment && !parser.is_escaped => {
let new_state = parser.state_stack.pop().unwrap();
if parser.state != new_state {
add_token(&mut parser, stream, false);
parser.state = new_state;
continue;
}
}
b':' if parser.state == AddressState::Name && !parser.is_escaped => {
add_group(&mut parser);
add_token(&mut parser, stream, false);
add_group_details(&mut parser);
continue;
}
b';' if parser.state == AddressState::Name => {
add_token(&mut parser, stream, false);
add_address(&mut parser);
add_group(&mut parser);
continue;
}
_ => (),
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.is_token_start {
parser.is_token_start = false;
}
if parser.token_start == 0 {
parser.token_start = stream.pos;
parser.token_end = parser.token_start;
} else {
parser.token_end = stream.pos;
}
}
add_address(&mut parser);
if parser.group_name.is_some() || !parser.result.is_empty() {
add_group(&mut parser);
if parser.result.len() > 1 {
HeaderValue::GroupList(parser.result)
} else {
HeaderValue::Group(parser.result.pop().unwrap())
}
} else if !parser.addresses.is_empty() {
if parser.addresses.len() > 1 {
HeaderValue::AddressList(parser.addresses)
} else {
HeaderValue::Address(parser.addresses.pop().unwrap())
}
} else {
HeaderValue::Empty
}
}
pub fn parse_address_local_part(addr: &str) -> Option<&str> {
let addr = addr.as_bytes();
let mut iter = addr.iter().enumerate();
@@ -486,8 +473,6 @@ pub fn parse_address_detail_part(addr: &str) -> Option<&str> {
mod tests {
#[test]
fn parse_addresses() {
use crate::parsers::fields::address::parse_address;
use super::*;
let inputs = [
@@ -1008,7 +993,7 @@ mod tests {
for input in inputs {
let str = input.0.to_string();
let result = parse_address(&mut MessageStream::new(str.as_bytes()));
let result = MessageStream::new(str.as_bytes()).parse_address();
let expected: HeaderValue = serde_yaml::from_str(input.1).unwrap_or(HeaderValue::Empty);
/*if input.0.len() >= 70 {
+416 -424
View File
@@ -12,8 +12,8 @@
use std::borrow::Cow;
use crate::{
decoders::{charsets::map::get_charset_decoder, encoded_word::decode_rfc2047, hex::decode_hex},
parsers::message::MessageStream,
decoders::{charsets::map::get_charset_decoder, hex::decode_hex},
parsers::MessageStream,
ContentType, HeaderValue,
};
@@ -55,476 +55,470 @@ struct ContentTypeParser<'x> {
is_token_start: bool,
}
#[inline(always)]
fn reset_parser(parser: &mut ContentTypeParser) {
parser.token_start = 0;
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 = Some(String::from_utf8_lossy(
&stream.data[parser.token_start - 1..parser.token_end],
));
if !parser.is_lower_case {
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
parser.is_lower_case = true;
}
match parser.state {
ContentState::AttributeName => parser.attr_name = attr,
ContentState::Type => parser.c_type = attr,
ContentState::SubType => parser.c_subtype = attr,
_ => unreachable!(),
}
reset_parser(parser);
true
} else {
false
impl<'x> ContentTypeParser<'x> {
#[inline(always)]
fn reset_parser(&mut self) {
self.token_start = 0;
self.is_token_start = true;
}
}
fn add_attribute_parameter<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) {
if parser.token_start > 0 {
let attr_part =
String::from_utf8_lossy(&stream.data[parser.token_start - 1..parser.token_end]);
fn add_attribute(&mut self, stream: &MessageStream<'x>) -> bool {
if self.token_start > 0 {
let mut attr = Some(String::from_utf8_lossy(
&stream.data[self.token_start - 1..self.token_end],
));
if parser.attr_charset.is_none() {
parser.attr_charset = attr_part.into();
} else {
let attr_name = parser
.attr_name
.as_ref()
.unwrap_or(&"unknown".into())
.clone()
+ "-language";
if !parser.attributes.iter().any(|(name, _)| name == &attr_name) {
parser.attributes.push((attr_name, attr_part));
} else {
parser.values.push("'".into());
parser.values.push(attr_part);
if !self.is_lower_case {
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
self.is_lower_case = true;
}
}
reset_parser(parser);
}
}
fn add_partial_value<'x>(
parser: &mut ContentTypeParser<'x>,
stream: &MessageStream<'x>,
to_cur_pos: bool,
) {
if parser.token_start > 0 {
let in_quote = parser.state == ContentState::AttributeQuotedValue;
parser.values.push(String::from_utf8_lossy(
&stream.data[parser.token_start - 1..if in_quote && to_cur_pos {
stream.pos - 1
} else {
parser.token_end
}],
));
if !in_quote {
parser.values.push(" ".into());
}
reset_parser(parser);
}
}
fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) {
if parser.attr_name.is_none() {
return;
}
let has_values = !parser.values.is_empty();
let value = if parser.token_start > 0 {
let value = &stream.data[parser.token_start - 1..parser.token_end];
Some(if !parser.remove_crlf {
String::from_utf8_lossy(value)
} else {
parser.remove_crlf = false;
match String::from_utf8(
value
.iter()
.filter(|&&ch| ch != b'\r' && ch != b'\n')
.copied()
.collect::<Vec<_>>(),
) {
Ok(value) => value.into(),
Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned().into(),
match self.state {
ContentState::AttributeName => self.attr_name = attr,
ContentState::Type => self.c_type = attr,
ContentState::SubType => self.c_subtype = attr,
_ => unreachable!(),
}
})
} else {
if !has_values {
self.reset_parser();
true
} else {
false
}
}
fn add_attribute_parameter(&mut self, stream: &MessageStream<'x>) {
if self.token_start > 0 {
let attr_part =
String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end]);
if self.attr_charset.is_none() {
self.attr_charset = attr_part.into();
} else {
let attr_name =
self.attr_name.as_ref().unwrap_or(&"unknown".into()).clone() + "-language";
if !self.attributes.iter().any(|(name, _)| name == &attr_name) {
self.attributes.push((attr_name, attr_part));
} else {
self.values.push("'".into());
self.values.push(attr_part);
}
}
self.reset_parser();
}
}
fn add_partial_value(&mut self, stream: &MessageStream<'x>, to_cur_pos: bool) {
if self.token_start > 0 {
let in_quote = self.state == ContentState::AttributeQuotedValue;
self.values.push(String::from_utf8_lossy(
&stream.data[self.token_start - 1..if in_quote && to_cur_pos {
stream.offset() - 1
} else {
self.token_end
}],
));
if !in_quote {
self.values.push(" ".into());
}
self.reset_parser();
}
}
fn add_value(&mut self, stream: &MessageStream<'x>) {
if self.attr_name.is_none() {
return;
}
None
};
if !parser.is_continuation {
parser.attributes.push((
parser.attr_name.take().unwrap(),
if !has_values {
value.unwrap()
let has_values = !self.values.is_empty();
let value = if self.token_start > 0 {
let value = &stream.data[self.token_start - 1..self.token_end];
Some(if !self.remove_crlf {
String::from_utf8_lossy(value)
} else {
if let Some(value) = value {
parser.values.push(value);
self.remove_crlf = false;
match String::from_utf8(
value
.iter()
.filter(|&&ch| ch != b'\r' && ch != b'\n')
.copied()
.collect::<Vec<_>>(),
) {
Ok(value) => value.into(),
Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned().into(),
}
parser.values.concat().into()
},
));
} else {
let attr_name = parser.attr_name.take().unwrap();
let mut value = if let Some(value) = value {
if has_values {
Cow::from(parser.values.concat()) + value
} else {
value
}
})
} else {
parser.values.concat().into()
if !has_values {
return;
}
None
};
if parser.is_encoded_attribute {
if let (true, decoded_bytes) = decode_hex(value.as_bytes()) {
value = if let Some(decoder) = parser
.attr_charset
.as_ref()
.and_then(|c| get_charset_decoder(c.as_bytes()))
{
decoder(&decoded_bytes).into()
if !self.is_continuation {
self.attributes.push((
self.attr_name.take().unwrap(),
if !has_values {
value.unwrap()
} else {
String::from_utf8(decoded_bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
if let Some(value) = value {
self.values.push(value);
}
self.values.concat().into()
},
));
} else {
let attr_name = self.attr_name.take().unwrap();
let mut value = if let Some(value) = value {
if has_values {
Cow::from(self.values.concat()) + value
} else {
value
}
}
parser.is_encoded_attribute = false;
}
if parser.attr_position > 0 {
let continuation = (attr_name, parser.attr_position, value);
if let Some(continuations) = parser.continuations.as_mut() {
continuations.push(continuation);
} else {
parser.continuations = Some(vec![continuation]);
}
self.values.concat().into()
};
parser.attr_position = 0;
} else {
parser.attributes.push((attr_name, value));
}
parser.is_continuation = false;
parser.attr_charset = None;
}
if has_values {
parser.values.clear();
}
reset_parser(parser);
}
fn add_attr_position(parser: &mut ContentTypeParser, stream: &MessageStream) -> bool {
if parser.token_start > 0 {
parser.attr_position =
String::from_utf8_lossy(&stream.data[parser.token_start - 1..parser.token_end])
.parse()
.unwrap_or(0);
reset_parser(parser);
true
} else {
false
}
}
fn merge_continuations(parser: &mut ContentTypeParser) {
let continuations = parser.continuations.as_mut().unwrap();
continuations.sort();
for (key, _, value) in continuations.drain(..) {
if let Some((_, old_value)) = parser.attributes.iter_mut().find(|(name, _)| name == &key) {
*old_value = format!("{}{}", old_value.to_owned(), value).into();
} else {
parser.attributes.push((key, value));
}
}
}
pub fn parse_content_type<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut parser = ContentTypeParser {
state: ContentState::Type,
state_stack: Vec::new(),
c_type: None,
c_subtype: None,
attr_name: None,
attr_charset: None,
attr_position: 0,
attributes: Vec::new(),
values: Vec::new(),
continuations: None,
is_continuation: false,
is_encoded_attribute: false,
is_lower_case: true,
is_token_start: true,
is_escaped: false,
remove_crlf: false,
token_start: 0,
token_end: 0,
};
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
if let ContentState::AttributeQuotedValue = parser.state {
if parser.token_start == 0 {
parser.token_start = stream.pos;
parser.token_end = parser.token_start;
} else {
parser.token_end = stream.pos;
}
}
continue;
}
b'A'..=b'Z' => {
if parser.is_lower_case {
if let ContentState::Type
| ContentState::SubType
| ContentState::AttributeName = parser.state
if self.is_encoded_attribute {
if let (true, decoded_bytes) = decode_hex(value.as_bytes()) {
value = if let Some(decoder) = self
.attr_charset
.as_ref()
.and_then(|c| get_charset_decoder(c.as_bytes()))
{
parser.is_lower_case = false;
decoder(&decoded_bytes).into()
} else {
String::from_utf8(decoded_bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
}
self.is_encoded_attribute = false;
}
b'\n' => {
let next_is_space = matches!(stream.data.get(stream.pos), Some(b' ' | b'\t'));
match parser.state {
ContentState::Type | ContentState::AttributeName | ContentState::SubType => {
add_attribute(&mut parser, stream);
}
ContentState::AttributeValue => {
add_value(&mut parser, stream);
}
ContentState::AttributeQuotedValue => {
if next_is_space {
parser.remove_crlf = true;
continue;
} else {
add_value(&mut parser, stream);
}
}
_ => (),
}
if next_is_space {
parser.state = ContentState::AttributeName;
stream.pos += 1;
iter.next();
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
if self.attr_position > 0 {
let continuation = (attr_name, self.attr_position, value);
if let Some(continuations) = self.continuations.as_mut() {
continuations.push(continuation);
} else {
if parser.continuations.is_some() {
merge_continuations(&mut parser);
}
self.continuations = Some(vec![continuation]);
}
return if let Some(content_type) = parser.c_type {
HeaderValue::ContentType(ContentType {
c_type: content_type,
c_subtype: parser.c_subtype.take(),
attributes: if !parser.attributes.is_empty() {
Some(parser.attributes)
} else {
None
},
})
} else {
HeaderValue::Empty
};
}
self.attr_position = 0;
} else {
self.attributes.push((attr_name, value));
}
b'/' if parser.state == ContentState::Type => {
add_attribute(&mut parser, stream);
parser.state = ContentState::SubType;
continue;
}
b';' => match parser.state {
ContentState::Type | ContentState::SubType | ContentState::AttributeName => {
add_attribute(&mut parser, stream);
parser.state = ContentState::AttributeName;
continue;
}
ContentState::AttributeValue => {
if !parser.is_escaped {
add_value(&mut parser, stream);
parser.state = ContentState::AttributeName;
} else {
parser.is_escaped = false;
}
continue;
}
_ => (),
},
b'*' if parser.state == ContentState::AttributeName => {
if !parser.is_continuation {
parser.is_continuation = add_attribute(&mut parser, stream);
} else if !parser.is_encoded_attribute {
add_attr_position(&mut parser, stream);
parser.is_encoded_attribute = true;
} else {
// Malformed data, reset parser.
reset_parser(&mut parser);
}
continue;
}
b'=' => match parser.state {
ContentState::AttributeName => {
if !parser.is_continuation {
if !add_attribute(&mut parser, stream) {
continue;
}
} else if !parser.is_encoded_attribute {
/* If is_continuation=true && is_encoded_attribute=false,
the last character was a '*' which means encoding */
parser.is_encoded_attribute = !add_attr_position(&mut parser, stream);
} else {
reset_parser(&mut parser);
}
parser.state = ContentState::AttributeValue;
continue;
}
ContentState::AttributeValue | ContentState::AttributeQuotedValue
if parser.is_token_start =>
{
if let (d_bytes_read, Some(token)) = decode_rfc2047(stream, stream.pos) {
add_partial_value(&mut parser, stream, false);
parser.values.push(token.into());
stream.pos += d_bytes_read;
iter = stream.data[stream.pos..].iter();
continue;
}
}
_ => (),
},
b'\"' => match parser.state {
ContentState::AttributeValue => {
if !parser.is_token_start {
parser.is_token_start = true;
}
parser.state = ContentState::AttributeQuotedValue;
continue;
}
ContentState::AttributeQuotedValue => {
if !parser.is_escaped {
add_value(&mut parser, stream);
parser.state = ContentState::AttributeName;
continue;
} else {
parser.is_escaped = false;
}
}
_ => continue,
},
b'\\' => match parser.state {
ContentState::AttributeQuotedValue | ContentState::AttributeValue => {
if !parser.is_escaped {
add_partial_value(&mut parser, stream, true);
parser.is_escaped = true;
continue;
} else {
parser.is_escaped = false;
}
}
ContentState::Comment => parser.is_escaped = !parser.is_escaped,
_ => continue,
},
b'\''
if parser.is_encoded_attribute
&& !parser.is_escaped
&& (parser.state == ContentState::AttributeValue
|| parser.state == ContentState::AttributeQuotedValue) =>
self.is_continuation = false;
self.attr_charset = None;
}
if has_values {
self.values.clear();
}
self.reset_parser();
}
fn add_attr_position(&mut self, stream: &MessageStream) -> bool {
if self.token_start > 0 {
self.attr_position =
String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end])
.parse()
.unwrap_or(0);
self.reset_parser();
true
} else {
false
}
}
fn merge_continuations(&mut self) {
let continuations = self.continuations.as_mut().unwrap();
continuations.sort();
for (key, _, value) in continuations.drain(..) {
if let Some((_, old_value)) = self.attributes.iter_mut().find(|(name, _)| name == &key)
{
add_attribute_parameter(&mut parser, stream);
continue;
*old_value = format!("{}{}", old_value.to_owned(), value).into();
} else {
self.attributes.push((key, value));
}
b'(' if parser.state != ContentState::AttributeQuotedValue => {
if !parser.is_escaped {
}
}
}
impl<'x> MessageStream<'x> {
pub fn parse_content_type(&mut self) -> HeaderValue<'x> {
let mut parser = ContentTypeParser {
state: ContentState::Type,
state_stack: Vec::new(),
c_type: None,
c_subtype: None,
attr_name: None,
attr_charset: None,
attr_position: 0,
attributes: Vec::new(),
values: Vec::new(),
continuations: None,
is_continuation: false,
is_encoded_attribute: false,
is_lower_case: true,
is_token_start: true,
is_escaped: false,
remove_crlf: false,
token_start: 0,
token_end: 0,
};
while let Some(ch) = self.next() {
match ch {
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
if let ContentState::AttributeQuotedValue = parser.state {
if parser.token_start == 0 {
parser.token_start = self.offset();
parser.token_end = parser.token_start;
} else {
parser.token_end = self.offset();
}
}
continue;
}
b'A'..=b'Z' => {
if parser.is_lower_case {
if let ContentState::Type
| ContentState::SubType
| ContentState::AttributeName = parser.state
{
parser.is_lower_case = false;
}
}
}
b'\n' => {
let next_is_space = self.peek_next_is_space();
match parser.state {
ContentState::Type
| ContentState::AttributeName
| ContentState::SubType => {
add_attribute(&mut parser, stream);
parser.add_attribute(self);
}
ContentState::AttributeValue => {
add_value(&mut parser, stream);
parser.add_value(self);
}
ContentState::AttributeQuotedValue => {
if next_is_space {
parser.remove_crlf = true;
continue;
} else {
parser.add_value(self);
}
}
_ => (),
}
parser.state_stack.push(parser.state);
parser.state = ContentState::Comment;
} else {
parser.is_escaped = false;
if next_is_space {
parser.state = ContentState::AttributeName;
self.next();
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
} else {
if parser.continuations.is_some() {
parser.merge_continuations();
}
return if let Some(content_type) = parser.c_type {
HeaderValue::ContentType(ContentType {
c_type: content_type,
c_subtype: parser.c_subtype.take(),
attributes: if !parser.attributes.is_empty() {
Some(parser.attributes)
} else {
None
},
})
} else {
HeaderValue::Empty
};
}
}
continue;
}
b')' if parser.state == ContentState::Comment => {
if !parser.is_escaped {
parser.state = parser.state_stack.pop().unwrap();
reset_parser(&mut parser);
} else {
parser.is_escaped = false;
b'/' if parser.state == ContentState::Type => {
parser.add_attribute(self);
parser.state = ContentState::SubType;
continue;
}
continue;
b';' => match parser.state {
ContentState::Type | ContentState::SubType | ContentState::AttributeName => {
parser.add_attribute(self);
parser.state = ContentState::AttributeName;
continue;
}
ContentState::AttributeValue => {
if !parser.is_escaped {
parser.add_value(self);
parser.state = ContentState::AttributeName;
} else {
parser.is_escaped = false;
}
continue;
}
_ => (),
},
b'*' if parser.state == ContentState::AttributeName => {
if !parser.is_continuation {
parser.is_continuation = parser.add_attribute(self);
} else if !parser.is_encoded_attribute {
parser.add_attr_position(self);
parser.is_encoded_attribute = true;
} else {
// Malformed data, reset parser.
parser.reset_parser();
}
continue;
}
b'=' => match parser.state {
ContentState::AttributeName => {
if !parser.is_continuation {
if !parser.add_attribute(self) {
continue;
}
} else if !parser.is_encoded_attribute {
/* If is_continuation=true && is_encoded_attribute=false,
the last character was a '*' which means encoding */
parser.is_encoded_attribute = !parser.add_attr_position(self);
} else {
parser.reset_parser();
}
parser.state = ContentState::AttributeValue;
continue;
}
ContentState::AttributeValue | ContentState::AttributeQuotedValue
if parser.is_token_start && self.peek_char(b'?') =>
{
self.checkpoint();
if let Some(token) = self.decode_rfc2047() {
parser.add_partial_value(self, false);
parser.values.push(token.into());
continue;
}
self.restore();
}
_ => (),
},
b'\"' => match parser.state {
ContentState::AttributeValue => {
if !parser.is_token_start {
parser.is_token_start = true;
}
parser.state = ContentState::AttributeQuotedValue;
continue;
}
ContentState::AttributeQuotedValue => {
if !parser.is_escaped {
parser.add_value(self);
parser.state = ContentState::AttributeName;
continue;
} else {
parser.is_escaped = false;
}
}
_ => continue,
},
b'\\' => match parser.state {
ContentState::AttributeQuotedValue | ContentState::AttributeValue => {
if !parser.is_escaped {
parser.add_partial_value(self, true);
parser.is_escaped = true;
continue;
} else {
parser.is_escaped = false;
}
}
ContentState::Comment => parser.is_escaped = !parser.is_escaped,
_ => continue,
},
b'\''
if parser.is_encoded_attribute
&& !parser.is_escaped
&& (parser.state == ContentState::AttributeValue
|| parser.state == ContentState::AttributeQuotedValue) =>
{
parser.add_attribute_parameter(self);
continue;
}
b'(' if parser.state != ContentState::AttributeQuotedValue => {
if !parser.is_escaped {
match parser.state {
ContentState::Type
| ContentState::AttributeName
| ContentState::SubType => {
parser.add_attribute(self);
}
ContentState::AttributeValue => {
parser.add_value(self);
}
_ => (),
}
parser.state_stack.push(parser.state);
parser.state = ContentState::Comment;
} else {
parser.is_escaped = false;
}
continue;
}
b')' if parser.state == ContentState::Comment => {
if !parser.is_escaped {
parser.state = parser.state_stack.pop().unwrap();
parser.reset_parser();
} else {
parser.is_escaped = false;
}
continue;
}
b'\r' => continue,
_ => (),
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.is_token_start {
parser.is_token_start = false;
}
if parser.token_start == 0 {
parser.token_start = self.offset();
parser.token_end = parser.token_start;
} else {
parser.token_end = self.offset();
}
b'\r' => continue,
_ => (),
}
if parser.is_escaped {
parser.is_escaped = false;
}
if parser.is_token_start {
parser.is_token_start = false;
}
if parser.token_start == 0 {
parser.token_start = stream.pos;
parser.token_end = parser.token_start;
} else {
parser.token_end = stream.pos;
}
HeaderValue::Empty
}
HeaderValue::Empty
}
#[cfg(test)]
mod tests {
use std::{borrow::Cow, collections::HashMap};
use serde::{Deserialize, Serialize};
use crate::{parsers::message::MessageStream, HeaderValue};
use crate::{parsers::MessageStream, HeaderValue};
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct ContentTypeMap<'x> {
@@ -541,8 +535,6 @@ mod tests {
#[test]
fn parse_content_fields() {
use super::parse_content_type;
let inputs =
[
(
@@ -1571,7 +1563,7 @@ mod tests {
let str = input.0.to_string();
// TODO: Redo tests without using hashmaps.
let result = match parse_content_type(&mut MessageStream::new(str.as_bytes())) {
let result = match MessageStream::new(str.as_bytes()).parse_content_type() {
HeaderValue::ContentType(ct) => HeaderValueMap::ContentType(ContentTypeMap {
c_type: ct.c_type,
c_subtype: ct.c_subtype,
+118 -129
View File
@@ -11,15 +11,12 @@
use std::fmt;
use crate::{parsers::message::MessageStream, DateTime, HeaderValue};
use crate::{parsers::MessageStream, DateTime, HeaderValue};
impl DateTime {
/// Parses an RFC822 date
pub fn parse_rfc822(&self, value: &str) -> Option<Self> {
match parse_date(&mut MessageStream {
data: value.as_bytes(),
pos: 0,
}) {
match MessageStream::new(value.as_bytes()).parse_date() {
HeaderValue::DateTime(dt) => dt.into(),
_ => None,
}
@@ -107,142 +104,137 @@ impl fmt::Display for DateTime {
}
}
pub fn parse_date<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut pos = 0;
let mut parts = [0u32; 7];
let mut parts_sizes = [
2u32, // Day (0)
2u32, // Month (1)
4u32, // Year (2)
2u32, // Hour (3)
2u32, // Minute (4)
2u32, // Second (5)
4u32, // TZ (6)
];
let mut month_hash: usize = 0;
let mut month_pos: usize = 0;
impl<'x> MessageStream<'x> {
pub fn parse_date(&mut self) -> HeaderValue<'x> {
let mut pos = 0;
let mut parts = [0u32; 7];
let mut parts_sizes = [
2u32, // Day (0)
2u32, // Month (1)
4u32, // Year (2)
2u32, // Hour (3)
2u32, // Minute (4)
2u32, // Second (5)
4u32, // TZ (6)
];
let mut month_hash: usize = 0;
let mut month_pos: usize = 0;
let mut is_plus = true;
let mut is_new_token = true;
let mut ignore = true;
let mut comment_count = 0;
let mut is_plus = true;
let mut is_new_token = true;
let mut ignore = true;
let mut comment_count = 0;
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = self.next() {
let mut next_part = false;
while let Some(ch) = iter.next() {
let mut next_part = false;
stream.pos += 1;
match ch {
b'\n' => match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
if !is_new_token && !ignore && comment_count == 0 {
next_part = true;
match ch {
b'\n' => {
if self.try_next_is_space() {
if !is_new_token && !ignore && comment_count == 0 {
next_part = true;
} else {
continue;
}
} else {
continue;
break;
}
}
_ => break,
},
_ if comment_count > 0 => {
if *ch == b')' {
comment_count -= 1;
} else if *ch == b'(' {
_ if comment_count > 0 => {
if *ch == b')' {
comment_count -= 1;
} else if *ch == b'(' {
comment_count += 1;
} else if *ch == b'\\' {
self.try_skip_char(b')');
}
continue;
}
b'0'..=b'9' => {
if pos < 7 && parts_sizes[pos] > 0 {
parts_sizes[pos] -= 1;
parts[pos] += (*ch - b'0') as u32 * u32::pow(10, parts_sizes[pos]);
if ignore {
ignore = false;
}
}
if is_new_token {
is_new_token = false;
}
}
b':' => {
if !is_new_token && !ignore && (pos == 3 || pos == 4) {
next_part = true;
}
}
b'+' => {
pos = 6;
}
b'-' => {
is_plus = false;
pos = 6;
}
b' ' | b'\t' => {
if !is_new_token && !ignore {
next_part = true;
}
}
b'a'..=b'z' | b'A'..=b'Z' => {
if pos == 1 {
if (1..=2).contains(&month_pos) {
month_hash += MONTH_HASH
[(if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize]
as usize;
}
month_pos += 1;
}
if is_new_token {
is_new_token = false;
}
}
b'(' => {
comment_count += 1;
} else if *ch == b'\\' {
if let Some(b')') = stream.data.get(stream.pos) {
stream.pos += 1;
}
is_new_token = true;
continue;
}
continue;
b',' | b'\r' => (),
_ => (),
}
b'0'..=b'9' => {
if next_part {
if pos < 7 && parts_sizes[pos] > 0 {
parts_sizes[pos] -= 1;
parts[pos] += (*ch - b'0') as u32 * u32::pow(10, parts_sizes[pos]);
if ignore {
ignore = false;
}
parts[pos] /= u32::pow(10, parts_sizes[pos]);
}
if is_new_token {
is_new_token = false;
}
}
b':' => {
if !is_new_token && !ignore && (pos == 3 || pos == 4) {
next_part = true;
}
}
b'+' => {
pos = 6;
}
b'-' => {
is_plus = false;
pos = 6;
}
b' ' | b'\t' => {
if !is_new_token && !ignore {
next_part = true;
}
}
b'a'..=b'z' | b'A'..=b'Z' => {
if pos == 1 {
if (1..=2).contains(&month_pos) {
month_hash += MONTH_HASH
[(if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize]
as usize;
}
month_pos += 1;
}
if is_new_token {
is_new_token = false;
}
}
b'(' => {
comment_count += 1;
pos += 1;
is_new_token = true;
continue;
}
b',' | b'\r' => (),
_ => (),
}
if next_part {
if pos < 7 && parts_sizes[pos] > 0 {
parts[pos] /= u32::pow(10, parts_sizes[pos]);
}
pos += 1;
is_new_token = true;
if pos >= 6 {
HeaderValue::DateTime(DateTime {
year: if (1..=99).contains(&parts[2]) {
parts[2] + 1900
} else {
parts[2]
} as u16,
month: if month_pos == 3 && month_hash <= 30 {
MONTH_MAP[month_hash] as u8
} else {
parts[1] as u8
},
day: parts[0] as u8,
hour: parts[3] as u8,
minute: parts[4] as u8,
second: parts[5] as u8,
tz_hour: (parts[6] / 100) as u8,
tz_minute: (parts[6] % 100) as u8,
tz_before_gmt: !is_plus,
})
} else {
HeaderValue::Empty
}
}
if pos >= 6 {
HeaderValue::DateTime(DateTime {
year: if (1..=99).contains(&parts[2]) {
parts[2] + 1900
} else {
parts[2]
} as u16,
month: if month_pos == 3 && month_hash <= 30 {
MONTH_MAP[month_hash] as u8
} else {
parts[1] as u8
},
day: parts[0] as u8,
hour: parts[3] as u8,
minute: parts[4] as u8,
second: parts[5] as u8,
tz_hour: (parts[6] / 100) as u8,
tz_minute: (parts[6] % 100) as u8,
tz_before_gmt: !is_plus,
})
} else {
HeaderValue::Empty
}
}
static MONTH_HASH: &[u8] = &[
@@ -267,10 +259,7 @@ pub static MONTH_MAP: &[u8; 31] = &[
mod tests {
use chrono::{FixedOffset, LocalResult, SecondsFormat, TimeZone, Utc};
use crate::{
parsers::{fields::date::parse_date, message::MessageStream},
HeaderValue,
};
use crate::{parsers::MessageStream, HeaderValue};
#[test]
fn parse_dates() {
@@ -335,7 +324,7 @@ mod tests {
];
for (input, expected_result) in inputs {
match parse_date(&mut MessageStream::new(input.as_bytes())) {
match MessageStream::new(input.as_bytes()).parse_date() {
HeaderValue::DateTime(datetime) => {
assert_eq!(expected_result, datetime.to_rfc3339());
+57 -64
View File
@@ -9,82 +9,75 @@
* except according to those terms.
*/
use crate::{parsers::message::MessageStream, HeaderValue};
use crate::{parsers::MessageStream, HeaderValue};
pub fn parse_id<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut token_invalid_start: usize = 0; // Handle broken clients
let mut token_invalid_end: usize = 0; // Handle broken clients
let mut is_id_part = false;
let mut ids = Vec::new();
impl<'x> MessageStream<'x> {
pub fn parse_id(&mut self) -> HeaderValue<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut token_invalid_start: usize = 0; // Handle broken clients
let mut token_invalid_end: usize = 0; // Handle broken clients
let mut is_id_part = false;
let mut ids = Vec::new();
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
continue;
}
_ => {
return match ids.len() {
1 => HeaderValue::Text(ids.pop().unwrap()),
0 => {
if token_invalid_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
&stream.data[token_invalid_start - 1..token_invalid_end],
))
} else {
HeaderValue::Empty
while let Some(&ch) = self.next() {
match ch {
b'\n' => {
if !self.try_next_is_space() {
return match ids.len() {
1 => HeaderValue::Text(ids.pop().unwrap()),
0 => {
if token_invalid_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
self.get_bytes(token_invalid_start - 1..token_invalid_end),
))
} else {
HeaderValue::Empty
}
}
}
_ => HeaderValue::TextList(ids),
};
_ => HeaderValue::TextList(ids),
};
} else {
continue;
}
}
},
b'<' => {
is_id_part = true;
continue;
}
b'>' => {
is_id_part = false;
if token_start > 0 {
ids.push(String::from_utf8_lossy(
&stream.data[token_start - 1..token_end],
));
token_start = 0;
} else {
b'<' => {
is_id_part = true;
continue;
}
b'>' => {
is_id_part = false;
if token_start > 0 {
ids.push(String::from_utf8_lossy(
self.get_bytes(token_start - 1..token_end),
));
token_start = 0;
} else {
continue;
}
}
b' ' | b'\t' | b'\r' => continue,
_ => {}
}
b' ' | b'\t' | b'\r' => continue,
_ => {}
}
if is_id_part {
if token_start == 0 {
token_start = stream.pos;
if is_id_part {
if token_start == 0 {
token_start = self.offset();
}
token_end = self.offset();
} else {
if token_invalid_start == 0 {
token_invalid_start = self.offset();
}
token_invalid_end = self.offset();
}
token_end = stream.pos;
} else {
if token_invalid_start == 0 {
token_invalid_start = stream.pos;
}
token_invalid_end = stream.pos;
}
HeaderValue::Empty
}
HeaderValue::Empty
}
#[cfg(test)]
mod tests {
use crate::parsers::fields::id::parse_id;
use crate::parsers::message::MessageStream;
use crate::HeaderValue;
use crate::{parsers::MessageStream, HeaderValue};
#[test]
fn parse_message_ids() {
@@ -132,7 +125,7 @@ mod tests {
for input in inputs {
let str = input.0.to_string();
match parse_id(&mut MessageStream::new(str.as_bytes())) {
match MessageStream::new(str.as_bytes()).parse_id() {
HeaderValue::TextList(ids) => {
assert_eq!(ids, input.1, "Failed to parse '{:?}'", input.0);
}
+77 -88
View File
@@ -11,7 +11,7 @@
use std::borrow::Cow;
use crate::{decoders::encoded_word::decode_rfc2047, parsers::message::MessageStream, HeaderValue};
use crate::{parsers::MessageStream, HeaderValue};
struct ListParser<'x> {
token_start: usize,
@@ -21,116 +21,105 @@ struct ListParser<'x> {
list: Vec<Cow<'x, str>>,
}
fn add_token<'x>(parser: &mut ListParser<'x>, stream: &MessageStream<'x>, add_space: bool) {
if parser.token_start > 0 {
if !parser.tokens.is_empty() {
parser.tokens.push(" ".into());
}
parser.tokens.push(String::from_utf8_lossy(
&stream.data[parser.token_start - 1..parser.token_end],
));
impl<'x> ListParser<'x> {
fn add_token(&mut self, stream: &MessageStream<'x>, add_space: bool) {
if self.token_start > 0 {
if !self.tokens.is_empty() {
self.tokens.push(" ".into());
}
self.tokens.push(String::from_utf8_lossy(
&stream.data[self.token_start - 1..self.token_end],
));
if add_space {
parser.tokens.push(" ".into());
}
if add_space {
self.tokens.push(" ".into());
}
parser.token_start = 0;
parser.is_token_start = true;
self.token_start = 0;
self.is_token_start = true;
}
}
fn add_tokens_to_list(&mut self) {
if !self.tokens.is_empty() {
self.list.push(if self.tokens.len() == 1 {
self.tokens.pop().unwrap()
} else {
let value = self.tokens.concat();
self.tokens.clear();
value.into()
});
}
}
}
fn add_tokens_to_list(parser: &mut ListParser) {
if !parser.tokens.is_empty() {
parser.list.push(if parser.tokens.len() == 1 {
parser.tokens.pop().unwrap()
} else {
let value = parser.tokens.concat();
parser.tokens.clear();
value.into()
});
}
}
impl<'x> MessageStream<'x> {
pub fn parse_comma_separared(&mut self) -> HeaderValue<'x> {
let mut parser = ListParser {
token_start: 0,
token_end: 0,
is_token_start: true,
tokens: Vec::new(),
list: Vec::new(),
};
pub fn parse_comma_separared<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut parser = ListParser {
token_start: 0,
token_end: 0,
is_token_start: true,
tokens: Vec::new(),
list: Vec::new(),
};
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => {
add_token(&mut parser, stream, false);
match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
if !parser.is_token_start {
parser.is_token_start = true;
}
iter.next();
stream.pos += 1;
continue;
}
_ => {
add_tokens_to_list(&mut parser);
while let Some(ch) = self.next() {
match ch {
b'\n' => {
parser.add_token(self, false);
if !self.try_next_is_space() {
parser.add_tokens_to_list();
return match parser.list.len() {
1 => HeaderValue::Text(parser.list.pop().unwrap()),
0 => HeaderValue::Empty,
_ => HeaderValue::TextList(parser.list),
};
} else {
continue;
}
}
}
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
}
b'=' if parser.is_token_start => {
if let (bytes_read, Some(token)) = decode_rfc2047(stream, stream.pos) {
add_token(&mut parser, stream, true);
parser.tokens.push(token.into());
stream.pos += bytes_read;
iter = stream.data[stream.pos..].iter();
b' ' | b'\t' => {
if !parser.is_token_start {
parser.is_token_start = true;
}
continue;
}
b'=' if parser.is_token_start && self.peek_char(b'?') => {
self.checkpoint();
if let Some(token) = self.decode_rfc2047() {
parser.add_token(self, true);
parser.tokens.push(token.into());
continue;
}
self.restore();
}
b',' => {
parser.add_token(self, false);
parser.add_tokens_to_list();
continue;
}
b'\r' => continue,
_ => (),
}
b',' => {
add_token(&mut parser, stream, false);
add_tokens_to_list(&mut parser);
continue;
if parser.is_token_start {
parser.is_token_start = false;
}
b'\r' => continue,
_ => (),
if parser.token_start == 0 {
parser.token_start = self.offset();
}
parser.token_end = self.offset();
}
if parser.is_token_start {
parser.is_token_start = false;
}
if parser.token_start == 0 {
parser.token_start = stream.pos;
}
parser.token_end = stream.pos;
HeaderValue::Empty
}
HeaderValue::Empty
}
#[cfg(test)]
mod tests {
use crate::parsers::fields::list::parse_comma_separared;
use crate::parsers::message::MessageStream;
use crate::HeaderValue;
use crate::{parsers::MessageStream, HeaderValue};
#[test]
fn parse_comma_separated_text() {
@@ -174,7 +163,7 @@ mod tests {
for input in inputs {
let str = input.0.to_string();
match parse_comma_separared(&mut MessageStream::new(str.as_bytes())) {
match MessageStream::new(str.as_bytes()).parse_comma_separared() {
HeaderValue::TextList(ids) => {
assert_eq!(ids, input.1, "Failed to parse '{:?}'", input.0);
}
+34 -51
View File
@@ -9,61 +9,46 @@
* except according to those terms.
*/
use crate::{parsers::message::MessageStream, HeaderValue};
use crate::{parsers::MessageStream, HeaderValue};
pub fn parse_raw<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
impl<'x> MessageStream<'x> {
pub fn parse_raw(&mut self) -> HeaderValue<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
continue;
}
_ => {
return if token_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
&stream.data[token_start - 1..token_end],
))
while let Some(ch) = self.next() {
match ch {
b'\n' => {
if !self.try_next_is_space() {
return if token_start > 0 {
HeaderValue::Text(String::from_utf8_lossy(
self.get_bytes(token_start - 1..token_end),
))
} else {
HeaderValue::Empty
};
} else {
HeaderValue::Empty
};
continue;
}
}
},
b' ' | b'\t' | b'\r' => continue,
_ => (),
b' ' | b'\t' | b'\r' => continue,
_ => (),
}
if token_start == 0 {
token_start = self.offset();
}
token_end = self.offset();
}
if token_start == 0 {
token_start = stream.pos;
}
token_end = stream.pos;
HeaderValue::Empty
}
HeaderValue::Empty
}
pub fn parse_and_ignore(stream: &mut MessageStream) {
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
if ch == &b'\n' {
match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
continue;
}
_ => break,
pub fn parse_and_ignore(&mut self) {
while let Some(&ch) = self.next() {
if ch == b'\n' && !self.try_next_is_space() {
break;
}
}
}
@@ -71,9 +56,7 @@ pub fn parse_and_ignore(stream: &mut MessageStream) {
#[cfg(test)]
mod tests {
use crate::parsers::fields::raw::parse_raw;
use crate::parsers::message::MessageStream;
use crate::Message;
use crate::{parsers::MessageStream, Message};
#[test]
fn parse_raw_text() {
@@ -97,7 +80,7 @@ mod tests {
for input in inputs {
let str = input.0.to_string();
assert_eq!(
parse_raw(&mut MessageStream::new(str.as_bytes())).unwrap_text(),
MessageStream::new(str.as_bytes()).parse_raw().unwrap_text(),
input.1,
"Failed for '{:?}'",
input.0
+52 -54
View File
@@ -11,91 +11,87 @@
use std::borrow::Cow;
use crate::{decoders::encoded_word::decode_rfc2047, parsers::message::MessageStream, HeaderValue};
use crate::{parsers::MessageStream, HeaderValue};
struct UnstructuredParser<'x> {
token_start: usize,
token_end: usize,
tokens: Vec<Cow<'x, str>>,
}
fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &MessageStream<'x>, add_space: bool) {
if parser.token_start > 0 {
if !parser.tokens.is_empty() {
parser.tokens.push(" ".into());
}
parser.tokens.push(String::from_utf8_lossy(
&stream.data[parser.token_start - 1..parser.token_end],
));
impl<'x> UnstructuredParser<'x> {
fn add_token(&mut self, stream: &MessageStream<'x>, add_space: bool) {
if self.token_start > 0 {
if !self.tokens.is_empty() {
self.tokens.push(" ".into());
}
self.tokens.push(String::from_utf8_lossy(
stream.get_bytes(self.token_start - 1..self.token_end),
));
if add_space {
parser.tokens.push(" ".into());
}
if add_space {
self.tokens.push(" ".into());
}
parser.token_start = 0;
self.token_start = 0;
}
}
}
pub fn parse_unstructured<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut parser = UnstructuredParser {
token_start: 0,
token_end: 0,
tokens: Vec::new(),
};
impl<'x> MessageStream<'x> {
pub fn parse_unstructured(&mut self) -> HeaderValue<'x> {
let mut parser = UnstructuredParser {
token_start: 0,
token_end: 0,
tokens: Vec::new(),
};
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = self.next() {
match ch {
b'\n' => {
parser.add_token(self, false);
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => {
add_token(&mut parser, stream, false);
match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
continue;
}
_ => {
if !self.try_next_is_space() {
return match parser.tokens.len() {
1 => HeaderValue::Text(parser.tokens.pop().unwrap()),
0 => HeaderValue::Empty,
_ => HeaderValue::Text(parser.tokens.concat().into()),
};
} else {
continue;
}
}
}
b' ' | b'\t' | b'\r' => {
continue;
}
b'=' => {
if let (bytes_read, Some(token)) = decode_rfc2047(stream, stream.pos) {
add_token(&mut parser, stream, true);
parser.tokens.push(token.into());
stream.pos += bytes_read;
iter = stream.data[stream.pos..].iter();
b' ' | b'\t' | b'\r' => {
continue;
}
b'=' if self.peek_char(b'?') => {
self.checkpoint();
if let Some(token) = self.decode_rfc2047() {
parser.add_token(self, true);
parser.tokens.push(token.into());
continue;
}
self.restore();
}
_ => (),
}
_ => (),
if parser.token_start == 0 {
parser.token_start = self.offset();
}
parser.token_end = self.offset();
}
if parser.token_start == 0 {
parser.token_start = stream.pos;
}
parser.token_end = stream.pos;
HeaderValue::Empty
}
HeaderValue::Empty
}
#[cfg(test)]
mod tests {
use crate::parsers::MessageStream;
#[test]
fn parse_unstructured() {
use crate::parsers::message::MessageStream;
let inputs = [
("Saying Hello\n", "Saying Hello", true),
("Re: Saying Hello\r\n", "Re: Saying Hello", true),
@@ -195,7 +191,9 @@ mod tests {
for (input, expected_result, _) in inputs {
assert_eq!(
super::parse_unstructured(&mut MessageStream::new(input.as_bytes()),).unwrap_text(),
MessageStream::new(input.as_bytes())
.parse_unstructured()
.unwrap_text(),
expected_result,
"Failed to parse '{:?}'",
input
+209 -205
View File
@@ -9,154 +9,172 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::{Header, HeaderName, HeaderValue, RfcHeader};
use super::{
fields::{
address::parse_address,
content_type::parse_content_type,
date::parse_date,
id::parse_id,
list::parse_comma_separared,
raw::{parse_and_ignore, parse_raw},
unstructured::parse_unstructured,
},
message::MessageStream,
};
use super::MessageStream;
#[derive(Debug, PartialEq, Eq)]
pub enum HeaderParserResult<'x> {
Rfc(RfcHeader),
Other(Cow<'x, str>),
Lf,
Eof,
}
impl<'x> MessageStream<'x> {
pub fn parse_headers(&mut self, headers: &mut Vec<Header<'x>>) -> bool {
loop {
loop {
match self.peek() {
Some(b'\n') => {
self.next();
return true;
}
None => return false,
Some(ch) if !ch.is_ascii_whitespace() => {
break;
}
_ => {
self.next();
}
}
}
pub fn parse_headers<'x>(headers: &mut Vec<Header<'x>>, stream: &mut MessageStream<'x>) -> bool {
loop {
let offset_field = stream.pos;
let (bytes_read, result) = parse_header_name(&stream.data[stream.pos..]);
stream.pos += bytes_read;
let offset_field = self.offset();
match result {
HeaderParserResult::Rfc(name) => {
let (_, parser) = {
if let Some(header_name) = self.parse_header_name() {
if let HeaderName::Rfc(rfc_name) = &header_name {
let from_offset = self.offset();
let value = match rfc_name {
RfcHeader::Subject
| RfcHeader::Comments
| RfcHeader::ContentDescription
| RfcHeader::ContentLocation
| RfcHeader::ContentTransferEncoding => self.parse_unstructured(),
RfcHeader::From
| RfcHeader::To
| RfcHeader::Cc
| RfcHeader::Bcc
| RfcHeader::ReplyTo
| RfcHeader::Sender
| RfcHeader::ResentTo
| RfcHeader::ResentFrom
| RfcHeader::ResentBcc
| RfcHeader::ResentCc
| RfcHeader::ResentSender
| RfcHeader::ListArchive
| RfcHeader::ListHelp
| RfcHeader::ListId
| RfcHeader::ListOwner
| RfcHeader::ListPost
| RfcHeader::ListSubscribe
| RfcHeader::ListUnsubscribe => self.parse_address(),
RfcHeader::Date | RfcHeader::ResentDate => self.parse_date(),
RfcHeader::MessageId
| RfcHeader::References
| RfcHeader::InReplyTo
| RfcHeader::ReturnPath
| RfcHeader::ContentId
| RfcHeader::ResentMessageId => self.parse_id(),
RfcHeader::Keywords | RfcHeader::ContentLanguage => {
self.parse_comma_separared()
}
RfcHeader::Received | RfcHeader::MimeVersion => self.parse_raw(),
RfcHeader::ContentType | RfcHeader::ContentDisposition => {
self.parse_content_type()
}
};
headers.push(Header {
name: header_name,
value,
offset_field,
offset_start: from_offset,
offset_end: self.offset(),
});
} else {
let from_offset = self.offset();
self.parse_and_ignore();
headers.push(Header {
name: header_name,
value: HeaderValue::Text(String::from_utf8_lossy(
self.get_bytes(from_offset..self.offset()),
)),
offset_field,
offset_start: from_offset,
offset_end: self.offset(),
});
}
} else if self.is_eof() {
return false;
}
}
}
pub fn parse_header_name(&mut self) -> Option<HeaderName<'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;
while let Some(&ch) = self.next() {
match ch {
b':' => {
if token_start != 0 {
break;
}
}
b'\n' => {
return None;
}
_ => {
if !ch.is_ascii_whitespace() {
if token_start == 0 {
token_start = self.offset();
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;
}
token_len += 1;
}
}
}
}
if token_start != 0 {
let field = self.get_bytes(token_start - 1..token_end);
if (2..=25).contains(&token_len) {
token_hash += token_len + {
#[cfg(feature = "ludicrous_mode")]
unsafe {
HDR_PARSER.get_unchecked(name as usize)
*HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize)
}
#[cfg(not(feature = "ludicrous_mode"))]
HDR_PARSER[name as usize]
};
let from_offset = stream.pos;
HDR_HASH[last_ch.to_ascii_lowercase() as usize]
} as usize;
headers.push(Header {
name: HeaderName::Rfc(name),
value: parser(stream),
offset_field,
offset_start: from_offset,
offset_end: stream.pos,
});
}
HeaderParserResult::Other(name) => {
let from_offset = stream.pos;
parse_and_ignore(stream);
if (4..=72).contains(&token_hash) {
let token_hash = token_hash - 4;
headers.push(Header {
name: HeaderName::Other(name),
value: HeaderValue::Text(String::from_utf8_lossy(
&stream.data[from_offset..stream.pos],
)),
offset_field,
offset_start: from_offset,
offset_end: stream.pos,
});
}
HeaderParserResult::Lf => return true,
HeaderParserResult::Eof => return false,
}
}
}
pub fn parse_header_name(data: &[u8]) -> (usize, HeaderParserResult) {
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 bytes_read: usize = 0;
for &ch in data.iter() {
bytes_read += 1;
match ch {
b':' => {
if token_start != 0 {
break;
}
}
b'\n' => {
return (bytes_read - 1, HeaderParserResult::Lf);
}
_ => {
if !ch.is_ascii_whitespace() {
if token_start == 0 {
token_start = bytes_read;
token_end = token_start;
} else {
token_end = bytes_read;
last_ch = ch;
if field.eq_ignore_ascii_case(HDR_NAMES[token_hash]) {
return Some(HeaderName::Rfc(HDR_MAP[token_hash]));
}
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;
}
token_len += 1;
}
}
Some(HeaderName::Other(String::from_utf8_lossy(field)))
} else {
None
}
}
if token_start != 0 {
let field = &data[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 (bytes_read, HeaderParserResult::Rfc(HDR_MAP[token_hash]));
}
}
}
return (
bytes_read,
HeaderParserResult::Other(String::from_utf8_lossy(field)),
);
} else {
(bytes_read, HeaderParserResult::Eof)
}
}
impl RfcHeader {
@@ -210,95 +228,81 @@ impl From<RfcHeader> for u8 {
}
}
impl<'x> From<HeaderParserResult<'x>> for HeaderName<'x> {
fn from(result: HeaderParserResult<'x>) -> Self {
match result {
HeaderParserResult::Rfc(header) => HeaderName::Rfc(header),
HeaderParserResult::Other(header) => HeaderName::Other(header),
_ => HeaderName::Other("".into()),
}
}
}
#[cfg(test)]
mod tests {
use crate::{parsers::header::parse_header_name, RfcHeader};
use super::HeaderParserResult;
use crate::{parsers::MessageStream, HeaderName, RfcHeader};
#[test]
fn header_name_parse() {
let inputs = [
("From: ", HeaderParserResult::Rfc(RfcHeader::From)),
("receiVED: ", HeaderParserResult::Rfc(RfcHeader::Received)),
(" subject : ", HeaderParserResult::Rfc(RfcHeader::Subject)),
("From: ", HeaderName::Rfc(RfcHeader::From)),
("receiVED: ", HeaderName::Rfc(RfcHeader::Received)),
(" subject : ", HeaderName::Rfc(RfcHeader::Subject)),
(
"X-Custom-Field : ",
HeaderParserResult::Other("X-Custom-Field".into()),
),
(" T : ", HeaderParserResult::Other("T".into())),
(
"mal formed: ",
HeaderParserResult::Other("mal formed".into()),
),
(
"MIME-version : ",
HeaderParserResult::Rfc(RfcHeader::MimeVersion),
HeaderName::Other("X-Custom-Field".into()),
),
(" T : ", HeaderName::Other("T".into())),
("mal formed: ", HeaderName::Other("mal formed".into())),
("MIME-version : ", HeaderName::Rfc(RfcHeader::MimeVersion)),
];
for input in inputs {
let str = input.0.to_string();
let (_, result) = parse_header_name(str.as_bytes());
assert_eq!(input.1, result, "Failed to parse '{:?}'", input.0);
for (input, expected_result) in inputs {
assert_eq!(
expected_result,
MessageStream::new(input.as_bytes())
.parse_header_name()
.unwrap(),
"Failed to parse '{:?}'",
input
);
}
}
}
#[allow(clippy::type_complexity)]
static HDR_PARSER: &[(
bool,
for<'x, 'y> fn(&mut MessageStream<'x>) -> HeaderValue<'x>,
)] = &[
(false, parse_unstructured), // Subject = 0,
(false, parse_address), // From = 1,
(false, parse_address), // To = 2,
(false, parse_address), // Cc = 3,
(false, parse_date), // Date = 4,
(false, parse_address), // Bcc = 5,
(false, parse_address), // ReplyTo = 6,
(false, parse_address), // Sender = 7,
(true, parse_unstructured), // Comments = 8,
(false, parse_id), // InReplyTo = 9,
(true, parse_comma_separared), // Keywords = 10,
(true, parse_raw), // Received = 11,
(false, parse_id), // MessageId = 12,
(true, parse_id), // References = 13, (RFC 5322 recommends One)
(false, parse_id), // ReturnPath = 14,
(false, parse_raw), // MimeVersion = 15,
(false, parse_unstructured), // ContentDescription = 16,
(false, parse_id), // ContentId = 17,
(false, parse_comma_separared), // ContentLanguage = 18
(false, parse_unstructured), // ContentLocation = 19
(false, parse_unstructured), // ContentTransferEncoding = 20,
(false, parse_content_type), // ContentType = 21,
(false, parse_content_type), // ContentDisposition = 22,
(true, parse_address), // ResentTo = 23,
(true, parse_address), // ResentFrom = 24,
(true, parse_address), // ResentBcc = 25,
(true, parse_address), // ResentCc = 26,
(true, parse_address), // ResentSender = 27,
(true, parse_date), // ResentDate = 28,
(true, parse_id), // ResentMessageId = 29,
(false, parse_address), // ListArchive = 30,
(false, parse_address), // ListHelp = 31,
(false, parse_address), // ListId = 32,
(false, parse_address), // ListOwner = 33,
(false, parse_address), // ListPost = 34,
(false, parse_address), // ListSubscribe = 35,
(false, parse_address), // ListUnsubscribe = 36,
(true, parse_raw), // Other = 37,
];
/*
type ParserFnc<'x> = fn(&mut MessageStream<'x>) -> HeaderValue<'x>;
static HDR_PARSER: &[(bool, for<'x> fn(&mut MessageStream<'x>) -> HeaderValue<'x>] = &[
(false, MessageStream::parse_unstructured), // Subject = 0,
(false, MessageStream::parse_address), // From = 1,
(false, MessageStream::parse_address), // To = 2,
(false, MessageStream::parse_address), // Cc = 3,
(false, MessageStream::parse_date), // Date = 4,
(false, MessageStream::parse_address), // Bcc = 5,
(false, MessageStream::parse_address), // ReplyTo = 6,
(false, MessageStream::parse_address), // Sender = 7,
(true, MessageStream::parse_unstructured), // Comments = 8,
(false, MessageStream::parse_id), // InReplyTo = 9,
(true, MessageStream::parse_comma_separared), // Keywords = 10,
(true, MessageStream::parse_raw), // Received = 11,
(false, MessageStream::parse_id), // MessageId = 12,
(true, MessageStream::parse_id), // References = 13, (RFC 5322 recommends One)
(false, MessageStream::parse_id), // ReturnPath = 14,
(false, MessageStream::parse_raw), // MimeVersion = 15,
(false, MessageStream::parse_unstructured), // ContentDescription = 16,
(false, MessageStream::parse_id), // ContentId = 17,
(false, MessageStream::parse_comma_separared), // ContentLanguage = 18
(false, MessageStream::parse_unstructured), // ContentLocation = 19
(false, MessageStream::parse_unstructured), // ContentTransferEncoding = 20,
(false, MessageStream::parse_content_type), // ContentType = 21,
(false, MessageStream::parse_content_type), // ContentDisposition = 22,
(true, MessageStream::parse_address), // ResentTo = 23,
(true, MessageStream::parse_address), // ResentFrom = 24,
(true, MessageStream::parse_address), // ResentBcc = 25,
(true, MessageStream::parse_address), // ResentCc = 26,
(true, MessageStream::parse_address), // ResentSender = 27,
(true, MessageStream::parse_date), // ResentDate = 28,
(true, MessageStream::parse_id), // ResentMessageId = 29,
(false, MessageStream::parse_address), // ListArchive = 30,
(false, MessageStream::parse_address), // ListHelp = 31,
(false, MessageStream::parse_address), // ListId = 32,
(false, MessageStream::parse_address), // ListOwner = 33,
(false, MessageStream::parse_address), // ListPost = 34,
(false, MessageStream::parse_address), // ListSubscribe = 35,
(false, MessageStream::parse_address), // ListUnsubscribe = 36,
(true, MessageStream::parse_raw), // Other = 37,
];*/
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,
+71 -56
View File
@@ -9,24 +9,15 @@
* except according to those terms.
*/
use std::{borrow::Cow, iter::Peekable, slice::Iter};
use std::borrow::Cow;
use crate::{
decoders::{
base64::decode_base64_mime, charsets::map::get_charset_decoder,
quoted_printable::decode_quoted_printable_mime, DecodeFnc,
},
parsers::mime::seek_next_part_offset,
decoders::{charsets::map::get_charset_decoder, DecodeFnc},
ContentType, Encoding, GetHeader, HeaderValue, Message, MessagePart, MessagePartId, PartType,
RfcHeader,
};
use super::{
header::parse_headers,
mime::{
get_mime_part, seek_crlf, seek_next_part, seek_part_end, skip_crlf, skip_multipart_end,
},
};
use super::MessageStream;
const MAX_NESTED_ENCODED: usize = 3;
@@ -120,24 +111,6 @@ impl MessageParserState {
}
}
pub struct MessageStream<'x> {
pub data: &'x [u8],
//pub iter: Peekable<Iter<'x, u8>>,
pub pos: usize,
//pub restore_pos: usize,
}
impl<'x> MessageStream<'x> {
pub fn new(data: &'x [u8]) -> MessageStream<'x> {
MessageStream {
data,
//iter: data.iter().peekable(),
pos: 0,
//restore_pos: 0,
}
}
}
impl<'x> Message<'x> {
fn new() -> Message<'x> {
Message {
@@ -172,10 +145,11 @@ impl<'x> Message<'x> {
'outer: loop {
// Parse headers
state.offset_header = stream.pos;
if !parse_headers(&mut part_headers, &mut stream) {
state.offset_header = stream.offset();
if !stream.parse_headers(&mut part_headers) {
break;
}
state.offset_body = stream.offset();
state.parts += 1;
state.sub_part_ids.push(message.parts.len());
@@ -191,9 +165,7 @@ impl<'x> Message<'x> {
if let Some(mime_boundary) =
content_type.map_or_else(|| None, |f| f.get_attribute("boundary"))
{
state.offset_body = seek_crlf(&stream, stream.pos);
if seek_next_part(&mut stream, mime_boundary.as_bytes()) {
if stream.seek_next_part(mime_boundary.as_bytes()) {
let part_id = message.parts.len();
let new_state = MessageParserState {
in_alternative: state.in_alternative
@@ -219,7 +191,7 @@ impl<'x> Message<'x> {
});
state_stack.push((state, None));
state = new_state;
skip_crlf(&mut stream);
stream.skip_crlf();
continue;
} else {
mime_type = MimeType::TextOther;
@@ -228,21 +200,21 @@ impl<'x> Message<'x> {
}
}
skip_crlf(&mut stream);
state.offset_body = stream.pos;
let (mut encoding, decode_fnc): (Encoding, DecodeFnc) = match part_headers
.get_rfc(&RfcHeader::ContentTransferEncoding)
{
Some(HeaderValue::Text(encoding)) if encoding.eq_ignore_ascii_case("base64") => {
(Encoding::Base64, decode_base64_mime)
(Encoding::Base64, MessageStream::decode_base64_mime)
}
Some(HeaderValue::Text(encoding))
if encoding.eq_ignore_ascii_case("quoted-printable") =>
{
(Encoding::QuotedPrintable, decode_quoted_printable_mime)
(
Encoding::QuotedPrintable,
MessageStream::decode_quoted_printable_mime,
)
}
_ => (Encoding::None, get_mime_part),
_ => (Encoding::None, MessageStream::get_mime_part),
};
if mime_type == MimeType::Message && encoding == Encoding::None {
@@ -284,7 +256,7 @@ impl<'x> Message<'x> {
is_text = true;
let (offset_end, boundary_found) =
seek_part_end(&mut stream, state.mime_boundary.as_deref());
stream.seek_part_end(state.mime_boundary.as_deref());
state.offset_end = offset_end;
bytes = stream.data[state.offset_body..state.offset_end].into();
@@ -432,7 +404,7 @@ impl<'x> Message<'x> {
.mime_boundary
.as_ref()
.map(|b| {
let pos = stream.pos.saturating_sub(b.len() + 2);
let pos = stream.offset().saturating_sub(b.len() + 2);
stream.data.get(pos - 2).map_or(pos - 1, |&ch| {
if ch == b'\r' {
pos - 2
@@ -441,7 +413,7 @@ impl<'x> Message<'x> {
}
})
})
.unwrap_or(stream.pos);
.unwrap_or_else(|| stream.offset());
message.raw_message = raw_message.into();
//raw_message[state.offset_header..offset_end].as_ref().into();
@@ -461,7 +433,7 @@ impl<'x> Message<'x> {
}
}
if skip_multipart_end(&mut stream) {
if stream.is_multipart_end() {
// End of MIME part reached
if MimeType::MultipartAlernative == state.mime_type
@@ -499,7 +471,7 @@ impl<'x> Message<'x> {
if let Some(ref mime_boundary) = state.mime_boundary {
// Ancestor has a MIME boundary, seek it.
if let Some(offset) =
seek_next_part_offset(&mut stream, mime_boundary)
stream.seek_next_part_offset(mime_boundary)
{
part.offset_end = offset;
continue 'inner;
@@ -508,19 +480,18 @@ impl<'x> Message<'x> {
}
// This part has no boundary, update end offset
part.offset_end = seek_crlf(&stream, stream.pos);
part.offset_end = stream.offset();
} else {
debug_assert!(false, "Invalid part ID, could not find multipart.");
}
break 'outer;
} else {
skip_crlf(&mut stream);
// Headers of next part expected next, break inner look.
break 'inner;
}
}
} else if stream.pos >= stream.data.len() {
} else if stream.offset() >= stream.data.len() {
break 'outer;
}
}
@@ -528,18 +499,18 @@ impl<'x> Message<'x> {
// Corrupted MIME message, try to recover whatever is possible.
while let Some((prev_state, prev_message)) = state_stack.pop() {
if let Some(mut prev_message) = prev_message {
message.raw_message = raw_message[state.offset_header..stream.pos].as_ref().into();
message.raw_message = raw_message.into(); //raw_message[state.offset_header..stream.offset()].as_ref().into();
if let Some(part) = prev_message.parts.get_mut(state.part_id) {
part.body = PartType::Message(message);
part.offset_end = stream.pos;
part.offset_end = stream.offset();
} else {
debug_assert!(false, "Invalid part ID, could not find message.");
}
message = prev_message;
} else if let Some(part) = message.parts.get_mut(state.part_id) {
part.offset_end = stream.pos;
part.offset_end = stream.offset();
part.body = PartType::Multipart(state.sub_part_ids);
} else {
debug_assert!(false, "This should not have happened.");
@@ -588,12 +559,14 @@ 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") {
let raw_message = fs::read(&file_name).unwrap();
let raw_original = fs::read(&file_name).unwrap();
tests_run += 1;
// Test without CRs
let raw_message = strip_crlf(&raw_original);
file_name.set_extension("json");
let expected_result = fs::read(&file_name).unwrap();
tests_run += 1;
let message = Message::parse(&raw_message).unwrap();
let json_message = serde_json::to_string_pretty(&message).unwrap();
@@ -605,6 +578,23 @@ mod tests {
file_name.display()
);
}
// Test with CRs
let raw_message = add_crlf(&raw_original);
file_name.set_extension("crlf.json");
let expected_result = fs::read(&file_name).unwrap();
let message = Message::parse(&raw_message).unwrap();
let json_message = serde_json::to_string_pretty(&message).unwrap();
if json_message.as_bytes() != expected_result {
file_name.set_extension("crlf.failed");
fs::write(&file_name, json_message.as_bytes()).unwrap();
panic!(
"Test failed, parsed message saved to {}",
file_name.display()
);
}
}
}
@@ -615,4 +605,29 @@ mod tests {
);
}
}
fn add_crlf(bytes: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len());
let mut last_ch = 0;
for &ch in bytes {
if ch == b'\n' && last_ch != b'\r' {
result.push(b'\r');
}
result.push(ch);
last_ch = ch;
}
result
}
fn strip_crlf(bytes: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len());
for &ch in bytes {
if !ch != b'\r' {
result.push(ch);
}
}
result
}
}
+139 -163
View File
@@ -11,186 +11,162 @@
use std::borrow::Cow;
use super::message::MessageStream;
use super::MessageStream;
pub fn seek_next_part(stream: &mut MessageStream, boundary: &[u8]) -> bool {
if !boundary.is_empty() {
let mut pos = stream.pos;
impl<'x> MessageStream<'x> {
pub fn seek_next_part(&mut self, boundary: &[u8]) -> bool {
if !boundary.is_empty() {
let mut last_ch = 0;
let mut iter = stream.data[stream.pos..].iter().peekable();
while let Some(&ch) = iter.next() {
pos += 1;
self.checkpoint();
if ch == b'-'
&& matches!(iter.peek(), Some(b'-'))
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
{
stream.pos = pos + boundary.len() + 1;
return true;
}
}
}
false
}
pub fn seek_next_part_offset(stream: &mut MessageStream, boundary: &[u8]) -> Option<usize> {
let mut pos = stream.pos;
let mut last_ch = b'\n';
let mut iter = stream.data[stream.pos..].iter().peekable();
let mut offset_pos = stream.pos;
while let Some(&ch) = iter.next() {
pos += 1;
if ch == b'\n' {
offset_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 };
} else if ch == b'-'
&& matches!(iter.peek(), Some(b'-'))
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
{
stream.pos = pos + boundary.len() + 1;
return offset_pos.into();
}
last_ch = ch;
}
None
}
pub fn get_mime_part<'x>(
stream: &mut MessageStream<'x>,
boundary: &[u8],
) -> (usize, Cow<'x, [u8]>) {
let mut last_ch = b'\n';
let start_pos = stream.pos;
let mut end_pos = stream.pos;
let mut pos = stream.pos;
let mut iter = stream.data[stream.pos..].iter().peekable();
while let Some(&ch) = iter.next() {
pos += 1;
if ch == b'\n' {
end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 };
} else if ch == b'-'
&& !boundary.is_empty()
&& matches!(iter.peek(), Some(b'-'))
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
&& matches!(
stream.data.get(pos + 1 + boundary.len()..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
)
{
stream.pos = pos + boundary.len() + 1;
if last_ch != b'\n' {
end_pos = pos - 1;
}
return (end_pos, stream.data[start_pos..end_pos].into());
}
last_ch = ch;
}
(
if boundary.is_empty() {
stream.pos = pos;
stream.pos
} else {
usize::MAX
},
stream.data[start_pos..pos].into(),
)
}
pub fn seek_part_end<'x>(stream: &mut MessageStream<'x>, boundary: Option<&[u8]>) -> (usize, bool) {
let mut last_ch = b'\n';
let mut end_pos = stream.pos;
if let Some(boundary) = boundary {
let mut iter = stream.data[stream.pos..].iter().peekable();
while let Some(&ch) = iter.next() {
stream.pos += 1;
if ch == b'\n' {
end_pos = if last_ch == b'\r' {
stream.pos - 2
} else {
stream.pos - 1
};
} else if ch == b'-'
&& matches!(iter.peek(), Some(b'-'))
&& stream
.data
.get(stream.pos + 1..stream.pos + 1 + boundary.len())
== Some(boundary)
&& matches!(
stream.data.get(stream.pos + 1 + boundary.len()..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
| Some([b'-', b'-', ..])
| Some([])
| None
)
{
if last_ch != b'\n' {
end_pos = stream.pos - 1;
while let Some(&ch) = self.next() {
if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) {
return true;
}
stream.pos += boundary.len() + 1;
return (end_pos, true);
last_ch = ch;
}
self.restore();
}
false
}
pub fn seek_next_part_offset(&mut self, boundary: &[u8]) -> Option<usize> {
let mut last_ch = b'\n';
let mut offset_pos = self.offset();
self.checkpoint();
while let Some(&ch) = self.next() {
if ch == b'\n' {
offset_pos = if last_ch == b'\r' {
self.offset() - 2
} else {
self.offset() - 1
};
} else if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) {
return offset_pos.into();
}
last_ch = ch;
}
(stream.pos, false)
} else {
stream.pos = stream.data.len();
(stream.pos, true)
}
}
self.restore();
pub fn skip_multipart_end(stream: &mut MessageStream) -> bool {
match stream.data.get(stream.pos..stream.pos + 2) {
Some(b"--") => {
if let Some(byte) = stream.data.get(stream.pos + 2) {
if !(*byte).is_ascii_whitespace() {
return false;
None
}
pub fn get_mime_part(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) {
let mut last_ch = b'\n';
let mut before_last_ch = 0;
let start_pos = self.offset();
let mut end_pos = self.offset();
self.checkpoint();
while let Some(&ch) = self.next() {
if ch == b'\n' {
end_pos = if last_ch == b'\r' {
self.offset() - 2
} else {
self.offset() - 1
};
} else if ch == b'-'
&& !boundary.is_empty()
&& last_ch == b'-'
&& self.try_skip(boundary)
{
if before_last_ch != b'\n' {
end_pos = self.offset() - boundary.len() - 2;
}
return (end_pos, self.get_bytes(start_pos..end_pos).into());
}
stream.pos += 2;
true
}
_ => false,
}
}
#[inline(always)]
pub fn skip_crlf(stream: &mut MessageStream) {
for ch in &stream.data[stream.pos..] {
match ch {
b'\r' | b' ' | b'\t' => stream.pos += 1,
b'\n' => {
stream.pos += 1;
break;
}
_ => break,
before_last_ch = last_ch;
last_ch = ch;
}
}
}
#[inline(always)]
pub fn seek_crlf(stream: &MessageStream, mut start_pos: usize) -> usize {
for ch in &stream.data[start_pos..] {
match ch {
b'\r' | b' ' | b'\t' => start_pos += 1,
b'\n' => {
start_pos += 1;
break;
(
if boundary.is_empty() {
self.offset()
} else {
self.restore();
usize::MAX
},
self.get_bytes(start_pos..self.len()).into(),
)
}
pub fn seek_part_end(&mut self, boundary: Option<&[u8]>) -> (usize, bool) {
let mut last_ch = b'\n';
let mut before_last_ch = 0;
let mut end_pos = self.offset();
if let Some(boundary) = boundary {
while let Some(&ch) = self.next() {
if ch == b'\n' {
end_pos = if last_ch == b'\r' {
self.offset() - 2
} else {
self.offset() - 1
};
} else if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) {
if before_last_ch != b'\n' {
end_pos = self.offset() - boundary.len() - 2;
}
return (end_pos, true);
}
before_last_ch = last_ch;
last_ch = ch;
}
_ => break,
(self.offset(), false)
} else {
self.seek_end();
(self.offset(), true)
}
}
start_pos
pub fn is_multipart_end(&mut self) -> bool {
self.checkpoint();
match (self.next(), self.peek()) {
(Some(&a), Some(&&b)) if a == b'\r' && b == b'\n' => {
self.next();
false
}
(Some(&a), Some(&&b)) if a == b'-' && b == b'-' => {
self.next();
true
}
(Some(&a), _) if a == b'\n' => false,
(Some(&a), _) if a.is_ascii_whitespace() => {
self.skip_crlf();
false
}
_ => {
self.restore();
false
}
}
}
#[inline(always)]
pub fn skip_crlf(&mut self) {
while let Some(ch) = self.peek() {
match ch {
b'\r' | b' ' | b'\t' => {
self.next();
}
b'\n' => {
self.next();
break;
}
_ => break,
}
}
}
}
+84 -6
View File
@@ -9,7 +9,7 @@
* except according to those terms.
*/
use std::{iter::Peekable, slice::Iter};
use std::{iter::Peekable, ops::Range, slice::Iter};
pub mod fields;
pub mod header;
@@ -17,7 +17,7 @@ pub mod message;
pub mod mime;
pub mod preview;
/*pub struct MessageStream<'x> {
pub struct MessageStream<'x> {
data: &'x [u8],
iter: Peekable<Iter<'x, u8>>,
pos: usize,
@@ -41,17 +41,17 @@ impl<'x> MessageStream<'x> {
#[inline(always)]
pub fn offset(&self) -> usize {
self.pos
std::cmp::min(self.pos, self.data.len())
}
#[inline(always)]
pub fn remaining(&self) -> usize {
self.data.len() - self.pos
self.data.len() - self.offset()
}
#[inline(always)]
pub fn checkpoint(&mut self) {
self.restore_pos = self.pos;
self.restore_pos = self.offset();
}
#[inline(always)]
@@ -65,6 +65,85 @@ impl<'x> MessageStream<'x> {
pub fn reset(&mut self) {
self.restore_pos = 0;
}
#[inline(always)]
pub fn peek_bytes(&self, len: usize) -> Option<&[u8]> {
let pos = self.offset();
self.data.get(pos..pos + len)
}
#[inline(always)]
pub fn peek_char(&mut self, ch: u8) -> bool {
matches!(self.peek(), Some(&&ch_) if ch_ == ch)
}
#[inline(always)]
pub fn skip_bytes(&mut self, len: usize) {
self.pos += len;
self.iter = self.data[self.pos..].iter().peekable();
}
#[inline(always)]
pub fn try_skip(&mut self, bytes: &[u8]) -> bool {
if self.peek_bytes(bytes.len()) == Some(bytes) {
self.skip_bytes(bytes.len());
true
} else {
false
}
}
#[inline(always)]
pub fn try_skip_char(&mut self, ch: u8) -> bool {
if self.peek_char(ch) {
self.next();
true
} else {
false
}
}
#[inline(always)]
pub fn get_bytes(&self, range: Range<usize>) -> &'x [u8] {
&self.data[range]
}
#[inline(always)]
pub fn seek_end(&mut self) {
self.pos = self.data.len();
self.iter = [][..].iter().peekable();
}
#[inline(always)]
pub fn next_is_space(&mut self) -> bool {
matches!(self.next(), Some(b' ' | b'\t'))
}
#[inline(always)]
pub fn peek_next_is_space(&mut self) -> bool {
matches!(self.peek(), Some(b' ' | b'\t'))
}
#[inline(always)]
pub fn try_next_is_space(&mut self) -> bool {
if self.peek_next_is_space() {
self.next();
true
} else {
false
}
}
#[allow(clippy::len_without_is_empty)]
#[inline(always)]
pub fn len(&self) -> usize {
self.data.len()
}
#[inline(always)]
pub fn is_eof(&mut self) -> bool {
self.iter.peek().is_none()
}
}
impl<'x> Iterator for MessageStream<'x> {
@@ -76,4 +155,3 @@ impl<'x> Iterator for MessageStream<'x> {
self.iter.next()
}
}
*/