mirror of
https://github.com/stalwartlabs/mail-parser.git
synced 2026-11-29 00:01:49 +00:00
Decoder refactoring.
This commit is contained in:
+125
-113
@@ -1,9 +1,6 @@
|
||||
use super::{Decoder, DecoderResult};
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
|
||||
pub struct Base64Decoder {
|
||||
chunk: Base64Chunk,
|
||||
count: u8,
|
||||
}
|
||||
use super::Writer;
|
||||
|
||||
#[repr(C)]
|
||||
union Base64Chunk {
|
||||
@@ -11,148 +8,163 @@ union Base64Chunk {
|
||||
bytes: [u8; std::mem::size_of::<u32>()],
|
||||
}
|
||||
|
||||
impl Base64Decoder {
|
||||
pub fn new() -> Base64Decoder {
|
||||
Base64Decoder {
|
||||
chunk: Base64Chunk { val: 0 },
|
||||
count: 0,
|
||||
}
|
||||
}
|
||||
pub trait Base64Decoder<'y> {
|
||||
fn decode_base64(&self, boundary: &[u8], is_word: bool, dest: &mut dyn Writer) -> bool;
|
||||
}
|
||||
|
||||
impl Decoder for Base64Decoder {
|
||||
fn ingest(&mut self, ch: &u8) -> DecoderResult {
|
||||
if *ch != b'=' {
|
||||
impl<'x> Base64Decoder<'x> for MessageStream<'x> {
|
||||
fn decode_base64(&self, boundary: &[u8], is_word: bool, dest: &mut dyn Writer) -> bool {
|
||||
let mut chunk = Base64Chunk { val: 0 };
|
||||
let mut byte_count: u8 = 0;
|
||||
let mut match_count: usize = 0;
|
||||
let mut pos = self.get_pos();
|
||||
|
||||
for ch in self.data[pos..].iter() {
|
||||
pos += 1;
|
||||
|
||||
if match_count < boundary.len() {
|
||||
if ch == unsafe { boundary.get_unchecked(match_count) } {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
self.set_pos(pos + match_count);
|
||||
return true;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else if match_count > 0 {
|
||||
if ch == unsafe { boundary.get_unchecked(0) } {
|
||||
match_count = 1;
|
||||
continue;
|
||||
} else {
|
||||
match_count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let val = unsafe {
|
||||
BASE64_MAP
|
||||
.get_unchecked(self.count as usize)
|
||||
.get_unchecked(byte_count as usize)
|
||||
.get_unchecked(*ch as usize)
|
||||
};
|
||||
|
||||
if *val >= 0x01ffffff {
|
||||
return DecoderResult::Error;
|
||||
if *ch == b'=' {
|
||||
match byte_count {
|
||||
1 | 2 => {
|
||||
byte_count = 0;
|
||||
dest.write_byte(unsafe { chunk.bytes.get_unchecked(0) });
|
||||
}
|
||||
3 => {
|
||||
byte_count = 0;
|
||||
dest.write_bytes(unsafe { chunk.bytes.get_unchecked(0..2) });
|
||||
}
|
||||
0 => (),
|
||||
_ => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if !(*ch).is_ascii_whitespace() || is_word {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
self.count = (self.count + 1) & 3;
|
||||
byte_count = (byte_count + 1) & 3;
|
||||
|
||||
if self.count == 1 {
|
||||
self.chunk.val = *val;
|
||||
if byte_count == 1 {
|
||||
chunk.val = *val;
|
||||
} else {
|
||||
self.chunk.val = unsafe { self.chunk.val } | *val;
|
||||
chunk.val = unsafe { chunk.val } | *val;
|
||||
|
||||
if self.count == 0 {
|
||||
return DecoderResult::ByteArray(unsafe {
|
||||
self.chunk.bytes.get_unchecked(0..3)
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match self.count {
|
||||
1 | 2 => {
|
||||
self.count = 0;
|
||||
return DecoderResult::Byte(unsafe { *self.chunk.bytes.get_unchecked(0) });
|
||||
}
|
||||
3 => {
|
||||
self.count = 0;
|
||||
return DecoderResult::ByteArray(unsafe {
|
||||
self.chunk.bytes.get_unchecked(0..2)
|
||||
});
|
||||
}
|
||||
0 => (),
|
||||
_ => {
|
||||
return DecoderResult::Error;
|
||||
if byte_count == 0 {
|
||||
dest.write_bytes(unsafe { chunk.bytes.get_unchecked(0..3) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DecoderResult::NeedData
|
||||
boundary.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
decoders::{buffer_writer::BufferWriter, Writer},
|
||||
parsers::message_stream::MessageStream,
|
||||
};
|
||||
|
||||
use super::Base64Decoder;
|
||||
use crate::decoders::{Decoder, DecoderResult};
|
||||
|
||||
#[test]
|
||||
fn decode_success() {
|
||||
fn decode_base64() {
|
||||
let inputs = [
|
||||
("VGVzdA==".as_bytes(), "Test".as_bytes()),
|
||||
("WWU=".as_bytes(), "Ye".as_bytes()),
|
||||
("QQ==".as_bytes(), "A".as_bytes()),
|
||||
("cm8=".as_bytes(), "ro".as_bytes()),
|
||||
("VGVzdA==", "Test", "", true),
|
||||
("WWU=", "Ye", "", true),
|
||||
("QQ==", "A", "", true),
|
||||
("cm8=", "ro", "", true),
|
||||
(
|
||||
"QXJlIHlvdSBhIFNoaW1hbm8gb3IgQ2FtcGFnbm9sbyBwZXJzb24/".as_bytes(),
|
||||
"Are you a Shimano or Campagnolo person?".as_bytes(),
|
||||
"QXJlIHlvdSBhIFNoaW1hbm8gb3IgQ2FtcGFnbm9sbyBwZXJzb24/",
|
||||
"Are you a Shimano or Campagnolo person?",
|
||||
"",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPgo8Ym9keT4KPC9ib2R5Pgo8L2h0bWw+Cg==".as_bytes(),
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n".as_bytes(),
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPgo8Ym9keT4KPC9ib2R5Pgo8L2h0bWw+Cg==",
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n",
|
||||
"",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPg\no8Ym9ke\nT4KPC 9ib2R5Pg\n o8L2h0bWw+Cg==",
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n",
|
||||
"",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPg\no8Ym9ke\nT4KPC 9ib2R5Pg\n o8L2h0bWw+Cg==",
|
||||
"",
|
||||
"",
|
||||
true,
|
||||
),
|
||||
("w6HDqcOtw7PDug==", "áéíóú", "", true),
|
||||
("====", "", "\n--boundary", true),
|
||||
("w6HDq!cOtw7PDug=", "", "", true),
|
||||
("w6 HD", "", "", true),
|
||||
("cmáé", "", "", true),
|
||||
("áé", "", "", true),
|
||||
("w6HDqcOtw7PDug==?=", "áéíóú", "?=", true),
|
||||
(
|
||||
"w\n6\nH\nD\nq\nc\nO\nt\nw\n7\n P\tD u g\n==\n--boundary",
|
||||
"áéíóú",
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
("w6HDqcOtw7PDug================?=", "áéíóú", "?=", false),
|
||||
(
|
||||
"w6HDqcOtw7PDug==\n--\n--boundary",
|
||||
"áéíóú",
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
("w6HDqcOtw7PDug==".as_bytes(), "áéíóú".as_bytes()),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let mut decoder = Base64Decoder::new();
|
||||
let mut output = Vec::new();
|
||||
let stream = MessageStream::new(input.0.as_bytes());
|
||||
let mut writer = BufferWriter::with_capacity(input.0.len());
|
||||
|
||||
for ch in input.0 {
|
||||
match decoder.ingest(ch) {
|
||||
DecoderResult::Byte(v) => {
|
||||
output.push(v);
|
||||
}
|
||||
DecoderResult::ByteArray(v) => {
|
||||
output.extend_from_slice(v);
|
||||
}
|
||||
DecoderResult::NeedData => (),
|
||||
DecoderResult::Error => {
|
||||
panic!(
|
||||
"Failed to decode Base64: {}",
|
||||
std::str::from_utf8(input.0).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
//println!("'{}'", std::str::from_utf8(&output).unwrap());
|
||||
assert_eq!(output, input.1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_invalid() {
|
||||
let inputs = [
|
||||
"====".as_bytes(),
|
||||
"w6HDq!cOtw7PDug=".as_bytes(),
|
||||
"w6 HD".as_bytes(),
|
||||
"cmáé".as_bytes(),
|
||||
"áé".as_bytes(),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let mut decoder = Base64Decoder::new();
|
||||
let mut failed = false;
|
||||
let mut is_empty = true;
|
||||
|
||||
for ch in input {
|
||||
match decoder.ingest(ch) {
|
||||
DecoderResult::Byte(_) => {
|
||||
is_empty = false;
|
||||
}
|
||||
DecoderResult::ByteArray(_) => {
|
||||
is_empty = false;
|
||||
}
|
||||
DecoderResult::NeedData => (),
|
||||
DecoderResult::Error => {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
failed || is_empty,
|
||||
"Test failed on '{}'",
|
||||
std::str::from_utf8(input).unwrap()
|
||||
assert_eq!(
|
||||
stream.decode_base64(input.2.as_bytes(), input.3, &mut writer),
|
||||
!input.1.is_empty(),
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
|
||||
if !input.1.is_empty() {
|
||||
let result = writer.get_bytes().unwrap_or_else(|| [].into());
|
||||
let result_str = std::str::from_utf8(result.as_ref()).unwrap();
|
||||
//println!("'{}' -> '{}'", input.0.escape_debug(), result_str.escape_debug());
|
||||
assert_eq!(result_str, input.1, "Failed for '{}'", input.0.escape_debug());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
pub mod multi_byte;
|
||||
pub mod parser;
|
||||
pub mod map;
|
||||
pub mod single_byte;
|
||||
pub mod utf8;
|
||||
|
||||
@@ -14,12 +14,13 @@ pub trait CharsetDecoder {
|
||||
fn to_string(&mut self) -> Option<String>;
|
||||
}
|
||||
|
||||
/*
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parser::CharsetParser;
|
||||
|
||||
#[test]
|
||||
fn decode() {
|
||||
fn decode_charset() {
|
||||
let mut parser = CharsetParser::new();
|
||||
let inputs = [
|
||||
("iso-8859-1".as_bytes(), b"\xe1\xe9\xed\xf3\xfa".to_vec(), "áéíóú"),
|
||||
@@ -68,9 +69,9 @@ mod tests {
|
||||
}
|
||||
//parser.ingest_slice(input.0);
|
||||
decoder = parser.get_decoder(50).unwrap();
|
||||
decoder.ingest_slice(&input.1);
|
||||
decoder.write_bytes(&input.1);
|
||||
|
||||
let result = decoder.to_string().unwrap();
|
||||
let result = decoder.get_string().unwrap();
|
||||
//println!("{}", result);
|
||||
assert_eq!(result, input.2);
|
||||
|
||||
@@ -78,3 +79,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -1,90 +1,115 @@
|
||||
use super::CharsetDecoder;
|
||||
use encoding_rs::*;
|
||||
|
||||
use crate::decoders::Writer;
|
||||
|
||||
pub struct MultiByteDecoder {
|
||||
decoder: Decoder,
|
||||
result: String,
|
||||
}
|
||||
|
||||
impl CharsetDecoder for MultiByteDecoder {
|
||||
fn ingest(&mut self, ch: &u8) {
|
||||
self.ingest_slice(&[*ch]);
|
||||
impl Writer for MultiByteDecoder {
|
||||
fn write_byte(&mut self, byte: &u8) -> bool {
|
||||
self.write_bytes(&[*byte])
|
||||
}
|
||||
|
||||
fn ingest_slice(&mut self, chs: &[u8]) {
|
||||
let (_, _, _) = self.decoder.decode_to_string(chs, &mut self.result, false);
|
||||
fn write_bytes(&mut self, bytes: &[u8]) -> bool {
|
||||
match self
|
||||
.decoder
|
||||
.decode_to_string(bytes, &mut self.result, false)
|
||||
{
|
||||
(encoding_rs::CoderResult::OutputFull, _, _) => false,
|
||||
(_, _, _) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_string(&mut self) -> Option<String> {
|
||||
fn get_string(&mut self) -> Option<String> {
|
||||
if !self.result.is_empty() {
|
||||
Some(std::mem::take(&mut self.result))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_bytes(&mut self) -> Option<Box<[u8]>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl MultiByteDecoder {
|
||||
pub fn get_shift_jis(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_shift_jis(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: SHIFT_JIS.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_big5(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_big5(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: BIG5.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_euc_jp(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_euc_jp(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: EUC_JP.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_euc_kr(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_euc_kr(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: EUC_KR.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_gb18030(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_gb18030(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: GB18030.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_gbk(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_gbk(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: GBK.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_iso2022_jp(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_iso2022_jp(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: ISO_2022_JP.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_utf16_be(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_utf16_be(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: UTF_16BE.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_utf16_le(capacity: usize) -> MultiByteDecoder {
|
||||
MultiByteDecoder {
|
||||
pub fn get_utf16_le(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: UTF_16LE.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_windows874(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: WINDOWS_874.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_ibm866(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(MultiByteDecoder {
|
||||
decoder: IBM866.new_decoder(),
|
||||
result: String::with_capacity(capacity),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::{single_byte::SingleByteDecoder, CharsetDecoder};
|
||||
use crate::decoders::Writer;
|
||||
|
||||
use super::{single_byte::SingleByteDecoder};
|
||||
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
use super::multi_byte::MultiByteDecoder;
|
||||
@@ -18,7 +20,7 @@ impl CharsetParser {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_default_decoder(capacity: usize) -> Box<dyn CharsetDecoder> {
|
||||
pub fn get_default_decoder(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_1,
|
||||
capacity,
|
||||
@@ -67,7 +69,7 @@ impl CharsetParser {
|
||||
&self.charset[0..self.len as usize]
|
||||
}
|
||||
|
||||
pub fn get_decoder(&mut self, capacity: usize) -> Option<Box<dyn CharsetDecoder>> {
|
||||
pub fn get_decoder(&mut self, capacity: usize) -> Option<Box<dyn Writer>> {
|
||||
if self.len < 2 {
|
||||
return None;
|
||||
}
|
||||
@@ -88,6 +90,23 @@ impl CharsetParser {
|
||||
// As of 2021, Rust does not support fallthrough or multiple guards per match arm.
|
||||
|
||||
match hash - 30 {
|
||||
// UTF-8
|
||||
935 if charset == b"utf-8" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
551 if charset == b"csutf8" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// US-ASCII
|
||||
1788 if charset == b"us-ascii" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
503 if charset == b"iso-ir-6" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
2695 if charset == b"ansi_x3.4-1968" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
2770 if charset == b"ansi_x3.4-1986" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1916 if charset == b"iso_646.irv:1991" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1095 if charset == b"iso646-us" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
442 if charset == b"us" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
986 if charset == b"ibm367" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1210 if charset == b"cp367" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
762 if charset == b"csascii" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
|
||||
|
||||
// ISO_8859-1:1987
|
||||
1399 if charset == b"iso-8859-1" => Some(Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_1,
|
||||
@@ -658,6 +677,22 @@ impl CharsetParser {
|
||||
Some(Box::new(MultiByteDecoder::get_shift_jis(capacity)))
|
||||
}
|
||||
|
||||
// IBM866
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
531 if charset == b"ibm866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
755 if charset == b"cp866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
523 if charset == b"866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
1098 if charset == b"csibm866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// WINDOWS-874
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
2716 if charset == b"windows-874" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
1442 if charset == b"cswindows874" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// BIG5
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
1729 if charset == b"big5" => Some(Box::new(MultiByteDecoder::get_big5(capacity))),
|
||||
@@ -745,7 +780,7 @@ impl CharsetParser {
|
||||
707 if charset == b"csutf16" => {
|
||||
Some(Box::new(MultiByteDecoder::get_utf16_le(capacity)))
|
||||
}
|
||||
|
||||
|
||||
// UTF-8, US-ASCII and other encodings fall back here
|
||||
_ => None,
|
||||
}
|
||||
@@ -809,21 +844,6 @@ mod tests {
|
||||
Generated from http://www.iana.org/assignments/character-sets/character-sets.xhtml
|
||||
Keep for future support of additional character sets.
|
||||
|
||||
// UTF-8
|
||||
935 if charset == b"utf-8" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
551 if charset == b"csutf8" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// US-ASCII
|
||||
1788 if charset == b"us-ascii" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
503 if charset == b"iso-ir-6" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
2695 if charset == b"ansi_x3.4-1968" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
2770 if charset == b"ansi_x3.4-1986" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1916 if charset == b"iso_646.irv:1991" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1095 if charset == b"iso646-us" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
442 if charset == b"us" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
986 if charset == b"ibm367" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
1210 if charset == b"cp367" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
762 if charset == b"csascii" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_1, capacity))),
|
||||
|
||||
// ISO_6937-2-ADD
|
||||
4435 if charset == b"iso_6937-2-add" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
@@ -1652,11 +1672,7 @@ mod tests {
|
||||
|
||||
// HZ-GB-2312
|
||||
1941 if charset == b"hz-gb-2312" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
// IBM866
|
||||
531 if charset == b"ibm866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
755 if charset == b"cp866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
523 if charset == b"866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
1098 if charset == b"csibm866" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// IBM775
|
||||
446 if charset == b"ibm775" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
670 if charset == b"cp775" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
@@ -1767,9 +1783,6 @@ mod tests {
|
||||
// CP51932
|
||||
1082 if charset == b"cp51932" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
1039 if charset == b"cscp51932" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
// WINDOWS-874
|
||||
2716 if charset == b"windows-874" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
1442 if charset == b"cswindows874" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
// CP50220
|
||||
437 if charset == b"cp50220" => Some(Box::new(SingleByteDecoder::new(SingleByteDecoder::ISO_8859_2, capacity))),
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
use super::CharsetDecoder;
|
||||
use crate::decoders::Writer;
|
||||
|
||||
pub struct SingleByteDecoder {
|
||||
table: &'static [char],
|
||||
result: String,
|
||||
}
|
||||
|
||||
impl CharsetDecoder for SingleByteDecoder {
|
||||
fn ingest(&mut self, ch: &u8) {
|
||||
self.result
|
||||
.push(unsafe { *self.table.get_unchecked(*ch as usize) });
|
||||
}
|
||||
|
||||
fn to_string(&mut self) -> Option<String> {
|
||||
impl Writer for SingleByteDecoder {
|
||||
fn get_string(&mut self) -> Option<String> {
|
||||
if !self.result.is_empty() {
|
||||
Some(std::mem::take(&mut self.result))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn write_byte(&mut self, byte: &u8) -> bool {
|
||||
self.result
|
||||
.push(unsafe { *self.table.get_unchecked(*byte as usize) });
|
||||
true
|
||||
}
|
||||
|
||||
fn get_bytes(&mut self) -> Option<Box<[u8]>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl SingleByteDecoder {
|
||||
@@ -28,6 +33,202 @@ impl SingleByteDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_1(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_1,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_2(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_2,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_3(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_3,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_4(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_4,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_5(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_5,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_6(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_6,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_7(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_7,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_8(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_8,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_9(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_9,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_10(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_10,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_13(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_13,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_14(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_14,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_15(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_15,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_iso_8859_16(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_16,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1250(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1250,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1251(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1251,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1252(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1252,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1253(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1253,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1254(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1254,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1255(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1255,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1256(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1256,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1257(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1257,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_cp1258(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::CP1258,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_koi8_r(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::KOI8_R,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_koi8_u(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::KOI8_U,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_macintosh(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::MACINTOSH,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_ibm_850(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::IBM850,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_tis_620(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::TIS_620,
|
||||
capacity,
|
||||
))
|
||||
}
|
||||
|
||||
pub const ISO_8859_1: &'static [char] = &[
|
||||
'\u{0}', '\u{1}', '\u{2}', '\u{3}', '\u{4}', '\u{5}', '\u{6}', '\u{7}', '\u{8}', '\u{9}',
|
||||
'\u{a}', '\u{b}', '\u{c}', '\u{d}', '\u{e}', '\u{f}', '\u{10}', '\u{11}', '\u{12}',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::char::REPLACEMENT_CHARACTER;
|
||||
|
||||
use super::CharsetDecoder;
|
||||
use crate::decoders::Writer;
|
||||
|
||||
enum Utf8State {
|
||||
Start,
|
||||
@@ -15,51 +15,56 @@ pub struct Utf8Decoder {
|
||||
result: String,
|
||||
}
|
||||
|
||||
impl CharsetDecoder for Utf8Decoder {
|
||||
fn ingest(&mut self, ch: &u8) {
|
||||
impl Writer for Utf8Decoder {
|
||||
fn write_byte(&mut self, byte: &u8) -> bool {
|
||||
match self.state {
|
||||
Utf8State::Start => {
|
||||
if *ch < 0x80 {
|
||||
if *byte < 0x80 {
|
||||
self.result
|
||||
.push(unsafe { char::from_u32_unchecked(*ch as u32) });
|
||||
} else if (*ch & 0xe0) == 0xc0 {
|
||||
self.char = (*ch as u32 & 0x1f) << 6;
|
||||
.push(unsafe { char::from_u32_unchecked(*byte as u32) });
|
||||
} else if (*byte & 0xe0) == 0xc0 {
|
||||
self.char = (*byte as u32 & 0x1f) << 6;
|
||||
self.state = Utf8State::Shift0;
|
||||
} else if (*ch & 0xf0) == 0xe0 {
|
||||
self.char = (*ch as u32 & 0x0f) << 12;
|
||||
} else if (*byte & 0xf0) == 0xe0 {
|
||||
self.char = (*byte as u32 & 0x0f) << 12;
|
||||
self.state = Utf8State::Shift6;
|
||||
} else if (*ch & 0xf8) == 0xf0 && (*ch <= 0xf4) {
|
||||
self.char = (*ch as u32 & 0x07) << 18;
|
||||
} else if (*byte & 0xf8) == 0xf0 && (*byte <= 0xf4) {
|
||||
self.char = (*byte as u32 & 0x07) << 18;
|
||||
self.state = Utf8State::Shift12;
|
||||
} else {
|
||||
self.result.push(REPLACEMENT_CHARACTER);
|
||||
}
|
||||
}
|
||||
Utf8State::Shift12 => {
|
||||
self.char |= (*ch as u32 & 0x3f) << 12;
|
||||
self.char |= (*byte as u32 & 0x3f) << 12;
|
||||
self.state = Utf8State::Shift6;
|
||||
}
|
||||
Utf8State::Shift6 => {
|
||||
self.char |= (*ch as u32 & 0x3f) << 6;
|
||||
self.char |= (*byte as u32 & 0x3f) << 6;
|
||||
self.state = Utf8State::Shift0;
|
||||
}
|
||||
Utf8State::Shift0 => {
|
||||
self.char |= *ch as u32 & 0x3f;
|
||||
self.char |= *byte as u32 & 0x3f;
|
||||
self.state = Utf8State::Start;
|
||||
self.result
|
||||
.push(char::from_u32(self.char).unwrap_or(REPLACEMENT_CHARACTER));
|
||||
self.char = 0;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn to_string(&mut self) -> Option<String> {
|
||||
fn get_string(&mut self) -> Option<String> {
|
||||
if !self.result.is_empty() {
|
||||
Some(std::mem::take(&mut self.result))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn get_bytes(&mut self) -> Option<Box<[u8]>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Utf8Decoder {
|
||||
@@ -70,11 +75,15 @@ impl Utf8Decoder {
|
||||
char: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_utf8(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(Utf8Decoder::new(capacity))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::decoders::charsets::CharsetDecoder;
|
||||
use crate::decoders::Writer;
|
||||
|
||||
use super::Utf8Decoder;
|
||||
|
||||
@@ -91,9 +100,9 @@ mod tests {
|
||||
|
||||
for input in inputs {
|
||||
let mut parser = Utf8Decoder::new(10);
|
||||
parser.ingest_slice(&input.0);
|
||||
parser.write_bytes(&input.0);
|
||||
|
||||
assert_eq!(parser.to_string().unwrap(), input.1);
|
||||
assert_eq!(parser.get_string().unwrap(), input.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+63
-69
@@ -1,96 +1,90 @@
|
||||
use super::{quoted_printable::HEX_MAP, Decoder, DecoderResult};
|
||||
use super::{quoted_printable::HEX_MAP, Writer};
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum HexState {
|
||||
None,
|
||||
Eq,
|
||||
Percent,
|
||||
Hex1,
|
||||
}
|
||||
|
||||
pub struct HexDecoder {
|
||||
state: HexState,
|
||||
hex_1: i8,
|
||||
}
|
||||
fn decode_hex(src: &[u8], dest: &mut dyn Writer) -> bool {
|
||||
let mut state = HexState::None;
|
||||
let mut hex1 = 0;
|
||||
|
||||
impl HexDecoder {
|
||||
pub fn new() -> HexDecoder {
|
||||
HexDecoder {
|
||||
state: HexState::None,
|
||||
hex_1: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
for ch in src {
|
||||
match ch {
|
||||
b'%' => {
|
||||
if let HexState::None = state {
|
||||
state = HexState::Percent
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => match state {
|
||||
HexState::None => {
|
||||
dest.write_byte(ch);
|
||||
}
|
||||
HexState::Percent => {
|
||||
hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
if hex1 != -1 {
|
||||
state = HexState::Hex1;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
HexState::Hex1 => {
|
||||
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
|
||||
impl Decoder for HexDecoder {
|
||||
fn ingest(&mut self, ch: &u8) -> DecoderResult {
|
||||
match self.state {
|
||||
HexState::None => match ch {
|
||||
b'%' => {
|
||||
self.state = HexState::Eq;
|
||||
}
|
||||
0..=126 => {
|
||||
return DecoderResult::Byte(*ch);
|
||||
}
|
||||
_ => {
|
||||
return DecoderResult::Byte(b'!');
|
||||
state = HexState::None;
|
||||
if hex2 != -1 {
|
||||
dest.write_byte(&(((hex1 as u8) << 4) | hex2 as u8));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
},
|
||||
HexState::Eq => {
|
||||
if *ch != b'\n' && *ch != b'\r' {
|
||||
self.hex_1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
if self.hex_1 != -1 {
|
||||
self.state = HexState::Hex1;
|
||||
} else {
|
||||
self.state = HexState::None;
|
||||
return DecoderResult::Error;
|
||||
}
|
||||
} else {
|
||||
self.state = HexState::None;
|
||||
}
|
||||
}
|
||||
HexState::Hex1 => {
|
||||
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
|
||||
self.state = HexState::None;
|
||||
if hex2 == -1 {
|
||||
return DecoderResult::Error;
|
||||
} else {
|
||||
return DecoderResult::Byte(((self.hex_1 as u8) << 4) | hex2 as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DecoderResult::NeedData
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::decoders::{hex::HexDecoder, Decoder, DecoderResult};
|
||||
use crate::decoders::{Writer, buffer_writer::BufferWriter, hex::decode_hex};
|
||||
|
||||
#[test]
|
||||
fn hex_decode_line() {
|
||||
fn decode_hex_line() {
|
||||
let inputs = [
|
||||
("this%20is%20some%20text".as_bytes(), "this is some text"),
|
||||
("this is some text".as_bytes(), "this is some text"),
|
||||
("this%20is%20some%20text", "this is some text"),
|
||||
("this is some text", "this is some text"),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let mut decoder = HexDecoder::new();
|
||||
let mut result = String::new();
|
||||
let mut writer = BufferWriter::with_capacity(input.0.len());
|
||||
|
||||
for ch in input.0 {
|
||||
match decoder.ingest(ch) {
|
||||
DecoderResult::Byte(val) => {
|
||||
result.push(char::from(val));
|
||||
}
|
||||
DecoderResult::NeedData => (),
|
||||
_ => {
|
||||
panic!("Error decoding '{}'", std::str::from_utf8(input.0).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
decode_hex(input.0.as_bytes(), &mut writer),
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
|
||||
assert_eq!(result, input.1);
|
||||
let result = &writer.get_bytes().unwrap();
|
||||
let result_str = std::str::from_utf8(result).unwrap();
|
||||
|
||||
/*println!(
|
||||
"Decoded '{}'\n -> to ->\n'{}'\n{}",
|
||||
input.0.escape_debug(),
|
||||
result_str.escape_debug(),
|
||||
"-".repeat(50)
|
||||
);*/
|
||||
|
||||
assert_eq!(
|
||||
input.1,
|
||||
result_str,
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+15
-8
@@ -2,14 +2,21 @@ pub mod base64;
|
||||
pub mod charsets;
|
||||
pub mod hex;
|
||||
pub mod quoted_printable;
|
||||
pub mod buffer_writer;
|
||||
|
||||
pub enum DecoderResult<'x> {
|
||||
Byte(u8),
|
||||
ByteArray(&'x [u8]),
|
||||
NeedData,
|
||||
Error,
|
||||
}
|
||||
pub trait Writer {
|
||||
fn write_byte(&mut self, byte: &u8) -> bool;
|
||||
fn write_bytes(&mut self, bytes: &[u8]) -> bool {
|
||||
for byte in bytes {
|
||||
if !self.write_byte(byte) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
pub trait Decoder {
|
||||
fn ingest(&mut self, ch: &u8) -> DecoderResult;
|
||||
fn get_bytes(&mut self) -> Option<Box<[u8]>>;
|
||||
fn get_string(&mut self) -> Option<String> {
|
||||
String::from_utf8(self.get_bytes()?.into()).map_or_else(|_| None, Some)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,76 +10,21 @@ enum QuotedPrintableState {
|
||||
}
|
||||
|
||||
pub trait QuotedPrintableDecoder<'y> {
|
||||
fn decode_qp_word(&self, dest: &mut dyn Writer) -> bool;
|
||||
fn decode_qp_text(&self, boundary: &[u8], dest: &mut dyn Writer) -> bool;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn decode_digit(
|
||||
dest: &mut dyn Writer,
|
||||
state: &mut QuotedPrintableState,
|
||||
ch: &u8,
|
||||
hex1: &mut i8,
|
||||
) -> bool {
|
||||
match state {
|
||||
QuotedPrintableState::None => dest.write_byte(ch),
|
||||
QuotedPrintableState::Eq => {
|
||||
*hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
if *hex1 != -1 {
|
||||
*state = QuotedPrintableState::Hex1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
|
||||
*state = QuotedPrintableState::None;
|
||||
if hex2 != -1 {
|
||||
dest.write_byte(&(((*hex1 as u8) << 4) | hex2 as u8))
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
fn decode_quoted_printable(
|
||||
&self,
|
||||
boundary: &[u8],
|
||||
is_word: bool,
|
||||
dest: &mut dyn Writer,
|
||||
) -> bool;
|
||||
}
|
||||
|
||||
impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
fn decode_qp_word(&self, dest: &mut dyn Writer) -> bool {
|
||||
let mut pos = self.get_pos();
|
||||
let mut state = QuotedPrintableState::None;
|
||||
let mut hex1: i8 = 0;
|
||||
|
||||
for ch in self.data[pos..].iter() {
|
||||
pos += 1;
|
||||
match ch {
|
||||
b'=' => {
|
||||
if let QuotedPrintableState::None = state {
|
||||
state = QuotedPrintableState::Eq
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
b'_' => {
|
||||
dest.write_byte(&b' ');
|
||||
}
|
||||
b'?' if self.data.get(pos).map_or_else(|| false, |ch| ch == &b'=') => {
|
||||
self.set_pos(pos + 1);
|
||||
return true;
|
||||
}
|
||||
b'\n' => return false,
|
||||
_ => {
|
||||
if !decode_digit(dest, &mut state, ch, &mut hex1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn decode_qp_text(&self, boundary: &[u8], dest: &mut dyn Writer) -> bool {
|
||||
fn decode_quoted_printable(
|
||||
&self,
|
||||
boundary: &[u8],
|
||||
is_word: bool,
|
||||
dest: &mut dyn Writer,
|
||||
) -> bool {
|
||||
let mut pos = self.get_pos();
|
||||
let mut state = QuotedPrintableState::None;
|
||||
let mut match_count = 0;
|
||||
@@ -122,14 +67,41 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
b'\n' if QuotedPrintableState::Eq == state => {
|
||||
state = QuotedPrintableState::None;
|
||||
}
|
||||
_ => {
|
||||
if !decode_digit(dest, &mut state, ch, &mut hex1) {
|
||||
b'\n' => {
|
||||
if is_word {
|
||||
return false;
|
||||
} else if QuotedPrintableState::Eq == state {
|
||||
state = QuotedPrintableState::None;
|
||||
} else {
|
||||
dest.write_byte(&b'\n');
|
||||
}
|
||||
}
|
||||
b'_' if is_word => {
|
||||
dest.write_byte(&b' ');
|
||||
}
|
||||
_ => match state {
|
||||
QuotedPrintableState::None => {
|
||||
dest.write_byte(ch);
|
||||
}
|
||||
QuotedPrintableState::Eq => {
|
||||
hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
if hex1 != -1 {
|
||||
state = QuotedPrintableState::Hex1;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
|
||||
state = QuotedPrintableState::None;
|
||||
if hex2 != -1 {
|
||||
dest.write_byte(&(((hex1 as u8) << 4) | hex2 as u8));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +117,7 @@ mod tests {
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn qp_decode_body() {
|
||||
fn decode_quoted_printable() {
|
||||
let inputs = [
|
||||
(
|
||||
concat!(
|
||||
@@ -165,77 +137,64 @@ mod tests {
|
||||
"est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.\n",
|
||||
"— Antoine de Saint-Exupéry, Citadelle (1948)"
|
||||
),
|
||||
"".as_bytes(),
|
||||
"",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--boundary",
|
||||
"— Antoine de Saint-Exupéry",
|
||||
"\n--boundary".as_bytes(),
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry\n--",
|
||||
"\n--boundary".as_bytes(),
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry=\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry--",
|
||||
"\n--boundary".as_bytes(),
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
("this=20is=20some=20text?=", "this is some text", "?=", true),
|
||||
("this is some text?=", "this is some text", "?=", true),
|
||||
("Keith_Moore?=", "Keith Moore", "?=", true),
|
||||
("=2=123?=", "", "?=", true),
|
||||
("= 20?=", "", "?=", true),
|
||||
("=====?=", "", "?=", true),
|
||||
("=20=20=XX?=", "", "?=", true),
|
||||
("=AX?=", "", "?=", true),
|
||||
("=\n=\n==?=", "", "?=", true),
|
||||
("=\r=1z?=", "", "?=", true),
|
||||
("=|?=", "", "?=", true),
|
||||
("????????=", "???????", "?=", true),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let stream = MessageStream::new(input.0.as_bytes());
|
||||
let mut writer = BufferWriter::with_capacity(input.0.len());
|
||||
|
||||
assert!(
|
||||
stream.decode_qp_text(input.2, &mut writer),
|
||||
"{}",
|
||||
assert_eq!(
|
||||
stream.decode_quoted_printable(input.2.as_bytes(), input.3, &mut writer),
|
||||
!input.1.is_empty(),
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
|
||||
let result = &writer.get_bytes().unwrap();
|
||||
let result_str = std::str::from_utf8(result).unwrap();
|
||||
|
||||
/*println!(
|
||||
"Decoded '{}'\n -> to ->\n'{}'\n{}",
|
||||
input.0.escape_debug(),
|
||||
result_str.escape_debug(),
|
||||
"-".repeat(50)
|
||||
);*/
|
||||
|
||||
assert_eq!(input.1, result_str);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qp_decode_headers() {
|
||||
let inputs = [
|
||||
("this=20is=20some=20text?=", "this is some text"),
|
||||
("this is some text?=", "this is some text"),
|
||||
("Keith_Moore?=", "Keith Moore"),
|
||||
("=2=123?=", ""),
|
||||
("= 20?=", ""),
|
||||
("=====?=", ""),
|
||||
("=20=20=XX?=", ""),
|
||||
("=AX?=", ""),
|
||||
("=\n=\n==?=", ""),
|
||||
("=\r=1z?=", ""),
|
||||
("=|?=", ""),
|
||||
("????????=", "???????"),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let stream = MessageStream::new(input.0.as_bytes());
|
||||
let mut writer = BufferWriter::with_capacity(input.0.len());
|
||||
|
||||
let success = stream.decode_qp_word(&mut writer);
|
||||
assert_eq!(success, !input.1.is_empty(), "{}", input.0.escape_debug());
|
||||
if !input.1.is_empty() {
|
||||
assert_eq!(
|
||||
std::str::from_utf8(&writer.get_bytes().unwrap()).unwrap(),
|
||||
input.1
|
||||
);
|
||||
let result = &writer.get_bytes().unwrap();
|
||||
let result_str = std::str::from_utf8(result).unwrap();
|
||||
|
||||
/*println!(
|
||||
"Decoded '{}'\n -> to ->\n'{}'\n{}",
|
||||
input.0.escape_debug(),
|
||||
result_str.escape_debug(),
|
||||
"-".repeat(50)
|
||||
);*/
|
||||
|
||||
assert_eq!(input.1, result_str, "Failed for '{}'", input.0.escape_debug());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
mod decoders;
|
||||
mod parsers;
|
||||
|
||||
|
||||
use crate::decoders::buffer_writer::BufferWriter;
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
use crate::decoders::quoted_printable::QuotedPrintableDecoder;
|
||||
|
||||
fn main() {
|
||||
let mail = concat!(
|
||||
@@ -25,5 +28,8 @@ fn main() {
|
||||
)
|
||||
.to_string();
|
||||
|
||||
//println!("{}", vec![0u8; 100].as_mut_slice().len());
|
||||
|
||||
let mut parser = MessageStream::new(mail.as_bytes());
|
||||
|
||||
}
|
||||
|
||||
@@ -88,43 +88,49 @@ pub struct AddressParser<'x> {
|
||||
group_comment: Option<Cow<'x, str>>,
|
||||
}
|
||||
|
||||
pub fn add_token<'x>(parser: &mut AddressParser<'x>, stream: &'x MessageStream) {
|
||||
let token = stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap();
|
||||
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
|
||||
pub fn add_token<'x>(parser: &mut AddressParser<'x>, stream: &'x MessageStream, add_trail_space: bool) {
|
||||
if parser.token_start > 0 {
|
||||
let token = stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap();
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
AddressState::Quote => &mut parser.name_tokens,
|
||||
AddressState::Comment => {
|
||||
add_space = true;
|
||||
&mut parser.comment_tokens
|
||||
}
|
||||
};
|
||||
AddressState::Quote => &mut parser.name_tokens,
|
||||
AddressState::Comment => {
|
||||
add_space = true;
|
||||
&mut parser.comment_tokens
|
||||
}
|
||||
};
|
||||
|
||||
if add_space && !list.is_empty() {
|
||||
list.push(" ".into());
|
||||
if add_space && !list.is_empty() {
|
||||
list.push(" ".into());
|
||||
}
|
||||
|
||||
list.push(token);
|
||||
|
||||
if add_trail_space {
|
||||
list.push(" ".into());
|
||||
}
|
||||
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_email = false;
|
||||
parser.is_token_start = true;
|
||||
parser.is_escaped = false;
|
||||
}
|
||||
|
||||
list.push(token);
|
||||
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_email = false;
|
||||
parser.is_token_start = true;
|
||||
parser.is_escaped = false;
|
||||
}
|
||||
|
||||
fn concat_tokens<'x>(tokens: &mut Vec<Cow<'x, str>>) -> Cow<'x, str> {
|
||||
@@ -229,10 +235,7 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
while let Some(ch) = stream.next() {
|
||||
match ch {
|
||||
b'\n' => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
|
||||
add_token(&mut parser, stream, false);
|
||||
match stream.peek() {
|
||||
Some(b' ' | b'\t') => {
|
||||
stream.advance(1);
|
||||
@@ -249,31 +252,24 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
if parser.state == AddressState::Quote {
|
||||
parser.token_end = stream.get_pos() - 1;
|
||||
}
|
||||
add_token(&mut parser, stream);
|
||||
add_token(&mut parser, stream, false);
|
||||
}
|
||||
|
||||
parser.is_escaped = true;
|
||||
continue;
|
||||
}
|
||||
b',' if parser.state == AddressState::Name => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
add_address(&mut parser);
|
||||
continue;
|
||||
}
|
||||
b'<' if parser.state == AddressState::Name => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
parser.state_stack.push(AddressState::Name);
|
||||
parser.state = AddressState::Address;
|
||||
continue;
|
||||
}
|
||||
b'>' if parser.state == AddressState::Address => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
parser.state = parser.state_stack.pop().unwrap();
|
||||
continue;
|
||||
}
|
||||
@@ -281,15 +277,11 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
AddressState::Name => {
|
||||
parser.state_stack.push(AddressState::Name);
|
||||
parser.state = AddressState::Quote;
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
continue;
|
||||
}
|
||||
AddressState::Quote => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
parser.state = parser.state_stack.pop().unwrap();
|
||||
continue;
|
||||
}
|
||||
@@ -301,21 +293,13 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
b'=' if parser.is_token_start && !parser.is_escaped && stream.skip_byte(&b'?') => {
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
let add_space = if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
parser.state != AddressState::Quote
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let list = if parser.state != AddressState::Comment {
|
||||
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
|
||||
};
|
||||
if add_space {
|
||||
list.push(" ".into());
|
||||
}
|
||||
list.push(token.into());
|
||||
}).push(token.into());
|
||||
continue;
|
||||
}
|
||||
stream.set_pos(pos_back);
|
||||
@@ -340,11 +324,8 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
b'\r' => continue,
|
||||
b'(' if parser.state != AddressState::Quote && !parser.is_escaped => {
|
||||
parser.state_stack.push(parser.state);
|
||||
|
||||
if parser.state != AddressState::Comment {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
parser.state = AddressState::Comment;
|
||||
continue;
|
||||
}
|
||||
@@ -352,24 +333,18 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
b')' if parser.state == AddressState::Comment && !parser.is_escaped => {
|
||||
let new_state = parser.state_stack.pop().unwrap();
|
||||
if parser.state != new_state {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
parser.state = new_state;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
b':' if parser.state == AddressState::Name && !parser.is_escaped => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
add_group(&mut parser);
|
||||
continue;
|
||||
}
|
||||
b';' if parser.state == AddressState::Name => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
add_address(&mut parser);
|
||||
parser.is_group_end = true;
|
||||
continue;
|
||||
|
||||
@@ -47,27 +47,78 @@ struct ContentTypeParser<'x> {
|
||||
}
|
||||
|
||||
fn add_attribute<'x>(parser: &mut ContentTypeParser<'x>, stream: &'x MessageStream) {
|
||||
let mut attr = stream.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
);
|
||||
if parser.token_start > 0 {
|
||||
let mut attr = stream.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
);
|
||||
|
||||
if !parser.is_lower_case {
|
||||
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
|
||||
parser.is_lower_case = true;
|
||||
if !parser.is_lower_case {
|
||||
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
|
||||
parser.is_lower_case = true;
|
||||
}
|
||||
|
||||
match parser.state {
|
||||
ContentState::Type => parser.c_type = attr,
|
||||
ContentState::SubType => parser.c_subtype = attr,
|
||||
ContentState::AttributeName => parser.attr_name = attr,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_start = true;
|
||||
}
|
||||
}
|
||||
|
||||
match parser.state {
|
||||
ContentState::Type => parser.c_type = attr,
|
||||
ContentState::SubType => parser.c_subtype = attr,
|
||||
ContentState::AttributeName => parser.attr_name = attr,
|
||||
_ => unreachable!(),
|
||||
fn add_attribute_parameter<'x>(parser: &mut ContentTypeParser<'x>, stream: &'x MessageStream) {
|
||||
if parser.token_start > 0 {
|
||||
let attr_part = stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap();
|
||||
let mut attr_name = parser.attr_name.as_ref().unwrap().clone() + "-charset";
|
||||
|
||||
if parser.attributes.contains_key(&attr_name) {
|
||||
attr_name = parser.attr_name.as_ref().unwrap().clone() + "-language";
|
||||
}
|
||||
parser.attributes.insert(attr_name, attr_part);
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
}
|
||||
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_start = true;
|
||||
fn add_partial_value<'x>(
|
||||
parser: &mut ContentTypeParser<'x>,
|
||||
stream: &'x MessageStream,
|
||||
to_cur_pos: bool,
|
||||
) {
|
||||
if parser.token_start > 0 {
|
||||
let in_quote = parser.state == ContentState::AttributeQuotedValue;
|
||||
|
||||
parser.values.push(
|
||||
stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
if in_quote && to_cur_pos {
|
||||
stream.get_pos() - 1
|
||||
} else {
|
||||
parser.token_end
|
||||
},
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
if !in_quote {
|
||||
parser.values.push(" ".into());
|
||||
}
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &'x MessageStream) {
|
||||
@@ -203,9 +254,7 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
}
|
||||
b'\n' => {
|
||||
match parser.state {
|
||||
ContentState::Type | ContentState::AttributeName | ContentState::SubType
|
||||
if parser.token_start > 0 =>
|
||||
{
|
||||
ContentState::Type | ContentState::AttributeName | ContentState::SubType => {
|
||||
add_attribute(&mut parser, stream)
|
||||
}
|
||||
ContentState::AttributeValue | ContentState::AttributeQuotedValue => {
|
||||
@@ -235,17 +284,13 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
}
|
||||
}
|
||||
b'/' if parser.state == ContentState::Type => {
|
||||
if parser.token_start > 0 {
|
||||
add_attribute(&mut parser, stream);
|
||||
}
|
||||
add_attribute(&mut parser, stream);
|
||||
parser.state = ContentState::SubType;
|
||||
continue;
|
||||
}
|
||||
b';' => match parser.state {
|
||||
ContentState::Type | ContentState::SubType | ContentState::AttributeName => {
|
||||
if parser.token_start > 0 {
|
||||
add_attribute(&mut parser, stream);
|
||||
}
|
||||
add_attribute(&mut parser, stream);
|
||||
parser.state = ContentState::AttributeName;
|
||||
continue;
|
||||
}
|
||||
@@ -262,24 +307,19 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
},
|
||||
b'*' if parser.state == ContentState::AttributeName => {
|
||||
if !parser.is_encoded_attribute {
|
||||
if parser.token_start > 0 {
|
||||
add_attribute(&mut parser, stream);
|
||||
}
|
||||
add_attribute(&mut parser, stream);
|
||||
parser.is_encoded_attribute = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'=' => match parser.state {
|
||||
ContentState::AttributeName => {
|
||||
if parser.token_start > 0 {
|
||||
if !parser.is_encoded_attribute {
|
||||
add_attribute(&mut parser, stream);
|
||||
} else {
|
||||
parser.token_start = 0;
|
||||
}
|
||||
if !parser.is_encoded_attribute {
|
||||
add_attribute(&mut parser, stream);
|
||||
} else {
|
||||
parser.token_start = 0;
|
||||
}
|
||||
parser.state = ContentState::AttributeValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
ContentState::AttributeValue | ContentState::AttributeQuotedValue
|
||||
@@ -288,22 +328,7 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
if parser.token_start > 0 {
|
||||
parser.values.push(
|
||||
stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
if parser.state != ContentState::AttributeQuotedValue {
|
||||
parser.values.push(" ".into());
|
||||
}
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
add_partial_value(&mut parser, stream, false);
|
||||
parser.values.push(token.into());
|
||||
continue;
|
||||
} else {
|
||||
@@ -334,23 +359,7 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
b'\\' => match parser.state {
|
||||
ContentState::AttributeQuotedValue | ContentState::AttributeValue => {
|
||||
if !parser.is_escaped {
|
||||
if parser.token_start > 0 {
|
||||
parser.values.push(
|
||||
stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
if parser.state == ContentState::AttributeQuotedValue {
|
||||
stream.get_pos() - 1
|
||||
} else {
|
||||
parser.token_end
|
||||
},
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
add_partial_value(&mut parser, stream, true);
|
||||
parser.is_escaped = true;
|
||||
continue;
|
||||
} else {
|
||||
@@ -365,23 +374,7 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
&& !parser.is_escaped
|
||||
&& parser.state == ContentState::AttributeValue =>
|
||||
{
|
||||
if parser.token_start > 0 {
|
||||
let attr_part = stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap();
|
||||
let mut attr_name = parser.attr_name.as_ref().unwrap().clone() + "-charset";
|
||||
|
||||
if parser.attributes.contains_key(&attr_name) {
|
||||
attr_name = parser.attr_name.as_ref().unwrap().clone() + "-language";
|
||||
}
|
||||
parser.attributes.insert(attr_name, attr_part);
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
add_attribute_parameter(&mut parser, stream);
|
||||
continue;
|
||||
}
|
||||
b'(' if parser.state != ContentState::AttributeQuotedValue => {
|
||||
@@ -389,11 +382,7 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
match parser.state {
|
||||
ContentState::Type
|
||||
| ContentState::AttributeName
|
||||
| ContentState::SubType
|
||||
if parser.token_start > 0 =>
|
||||
{
|
||||
add_attribute(&mut parser, stream);
|
||||
}
|
||||
| ContentState::SubType => add_attribute(&mut parser, stream),
|
||||
ContentState::AttributeValue => add_value(&mut parser, stream),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
@@ -40,15 +40,15 @@ impl fmt::Display for DateTime {
|
||||
|
||||
pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<DateTime> {
|
||||
let mut pos = 0;
|
||||
let mut parts: [u32; 7] = [0; 7];
|
||||
let mut parts_sizes: [u32; 7] = [
|
||||
2, // Day (0)
|
||||
2, // Month (1)
|
||||
4, // Year (2)
|
||||
2, // Hour (3)
|
||||
2, // Minute (4)
|
||||
2, // Second (5)
|
||||
4, // TZ (6)
|
||||
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;
|
||||
|
||||
@@ -9,22 +9,29 @@ pub struct UnstructuredParser<'x> {
|
||||
tokens: Vec<Cow<'x, str>>,
|
||||
}
|
||||
|
||||
pub fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &'x MessageStream) {
|
||||
if !parser.tokens.is_empty() {
|
||||
parser.tokens.push(" ".into());
|
||||
pub fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &'x MessageStream, add_space: bool) {
|
||||
if parser.token_start > 0 {
|
||||
if !parser.tokens.is_empty() {
|
||||
parser.tokens.push(" ".into());
|
||||
}
|
||||
parser.tokens.push(
|
||||
stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if add_space {
|
||||
parser.tokens.push(" ".into());
|
||||
}
|
||||
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_start = true;
|
||||
}
|
||||
parser.tokens.push(
|
||||
stream
|
||||
.get_string(
|
||||
parser.token_start - 1,
|
||||
parser.token_end,
|
||||
parser.is_token_safe,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
parser.token_start = 0;
|
||||
parser.is_token_safe = true;
|
||||
parser.is_token_start = true;
|
||||
}
|
||||
|
||||
pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>> {
|
||||
@@ -39,9 +46,8 @@ pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>>
|
||||
while let Some(ch) = stream.next() {
|
||||
match ch {
|
||||
b'\n' => {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
}
|
||||
add_token(&mut parser, stream, false);
|
||||
|
||||
match stream.peek() {
|
||||
Some(b' ' | b'\t') => {
|
||||
if !parser.is_token_start {
|
||||
@@ -69,10 +75,7 @@ pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>>
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
if parser.token_start > 0 {
|
||||
add_token(&mut parser, stream);
|
||||
parser.tokens.push(" ".into());
|
||||
}
|
||||
add_token(&mut parser, stream, true);
|
||||
parser.tokens.push(token.into());
|
||||
continue;
|
||||
} else {
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
pub mod encoded_word;
|
||||
pub mod fields;
|
||||
pub mod header;
|
||||
//pub mod encoded_word;
|
||||
//pub mod fields;
|
||||
//pub mod header;
|
||||
pub mod message_stream;
|
||||
|
||||
Reference in New Issue
Block a user