eml-codec/src/header.rs

78 lines
2.1 KiB
Rust
Raw Normal View History

2023-07-24 14:41:21 +02:00
2023-07-23 16:37:47 +02:00
use crate::text::misc_token::{unstructured, Unstructured};
use crate::text::whitespace::{foldable_line, obs_crlf};
2023-07-20 16:26:59 +02:00
use nom::{
2023-07-22 13:51:19 +02:00
branch::alt,
2023-07-23 16:37:47 +02:00
bytes::complete::{tag, tag_no_case, take_while1},
2023-07-20 16:26:59 +02:00
character::complete::space0,
2023-07-23 16:37:47 +02:00
combinator::map,
2023-07-22 13:51:19 +02:00
multi::many0,
2023-07-23 09:46:57 +02:00
sequence::{pair, terminated, tuple},
2023-07-23 16:37:47 +02:00
IResult,
2023-07-20 16:26:59 +02:00
};
#[derive(Debug, PartialEq)]
pub enum CompField<'a, T> {
Known(T),
Unknown(&'a [u8], Unstructured<'a>),
Bad(&'a [u8]),
}
#[derive(Debug, PartialEq)]
pub struct CompFieldList<'a, T>(pub Vec<CompField<'a, T>>);
impl<'a, T> CompFieldList<'a, T> {
pub fn known(self) -> Vec<T> {
2023-07-23 16:37:47 +02:00
self.0
.into_iter()
2023-07-24 09:24:38 +02:00
.filter_map(|v| match v {
2023-07-23 16:37:47 +02:00
CompField::Known(f) => Some(f),
_ => None,
})
.collect()
2023-07-20 16:26:59 +02:00
}
}
2023-07-23 16:37:47 +02:00
pub fn header<'a, T>(
fx: impl Fn(&'a [u8]) -> IResult<&'a [u8], T> + Copy,
) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], CompFieldList<T>> {
move |input| {
map(
terminated(
many0(alt((
map(fx, CompField::Known),
map(opt_field, |(k, v)| CompField::Unknown(k, v)),
map(foldable_line, CompField::Bad),
))),
obs_crlf,
),
CompFieldList,
)(input)
}
2023-07-22 13:51:19 +02:00
}
2023-07-20 16:26:59 +02:00
pub fn field_name<'a>(name: &'static [u8]) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8]> {
2023-07-23 16:37:47 +02:00
move |input| terminated(tag_no_case(name), tuple((space0, tag(b":"), space0)))(input)
2023-07-20 16:26:59 +02:00
}
/// Optional field
///
/// ```abnf
/// field = field-name ":" unstructured CRLF
/// field-name = 1*ftext
/// ftext = %d33-57 / ; Printable US-ASCII
/// %d59-126 ; characters not including
/// ; ":".
/// ```
pub fn opt_field(input: &[u8]) -> IResult<&[u8], (&[u8], Unstructured)> {
2023-07-22 13:51:19 +02:00
terminated(
pair(
terminated(
2023-07-24 09:24:38 +02:00
take_while1(|c| (0x21..=0x7E).contains(&c) && c != 0x3A),
2023-07-22 13:51:19 +02:00
tuple((space0, tag(b":"), space0)),
),
unstructured,
2023-07-23 16:37:47 +02:00
),
obs_crlf,
)(input)
2023-07-20 16:26:59 +02:00
}