1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
//! Please refer to [`imap_types::section`].

use std::num::NonZeroU32;

use abnf_core::streaming::sp;
/// Re-export everything from imap-types.
pub use imap_types::section::*;
use nom::{
    branch::alt,
    bytes::streaming::{tag, tag_no_case},
    combinator::{map, opt, value},
    multi::separated_list1,
    sequence::{delimited, tuple},
};

use crate::{
    codec::IMAPResult,
    core::{astring, nz_number, AString, NonEmptyVec},
};

/// `section = "[" [section-spec] "]"`
pub(crate) fn section(input: &[u8]) -> IMAPResult<&[u8], Option<Section>> {
    delimited(tag(b"["), opt(section_spec), tag(b"]"))(input)
}

/// `section-spec = section-msgtext / (section-part ["." section-text])`
pub(crate) fn section_spec(input: &[u8]) -> IMAPResult<&[u8], Section> {
    alt((
        map(section_msgtext, |part_specifier| match part_specifier {
            PartSpecifier::PartNumber(_) => unreachable!(),
            PartSpecifier::Header => Section::Header(None),
            PartSpecifier::HeaderFields(fields) => Section::HeaderFields(None, fields),
            PartSpecifier::HeaderFieldsNot(fields) => Section::HeaderFieldsNot(None, fields),
            PartSpecifier::Text => Section::Text(None),
            PartSpecifier::Mime => unreachable!(),
        }),
        map(
            tuple((section_part, opt(tuple((tag(b"."), section_text))))),
            |(part_number, maybe_part_specifier)| {
                if let Some((_, part_specifier)) = maybe_part_specifier {
                    match part_specifier {
                        PartSpecifier::PartNumber(_) => unreachable!(),
                        PartSpecifier::Header => Section::Header(Some(Part(part_number))),
                        PartSpecifier::HeaderFields(fields) => {
                            Section::HeaderFields(Some(Part(part_number)), fields)
                        }
                        PartSpecifier::HeaderFieldsNot(fields) => {
                            Section::HeaderFieldsNot(Some(Part(part_number)), fields)
                        }
                        PartSpecifier::Text => Section::Text(Some(Part(part_number))),
                        PartSpecifier::Mime => Section::Mime(Part(part_number)),
                    }
                } else {
                    Section::Part(Part(part_number))
                }
            },
        ),
    ))(input)
}

/// `section-msgtext = "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list / "TEXT"`
///
/// Top-level or MESSAGE/RFC822 part
pub(crate) fn section_msgtext(input: &[u8]) -> IMAPResult<&[u8], PartSpecifier> {
    alt((
        map(
            tuple((tag_no_case(b"HEADER.FIELDS.NOT"), sp, header_list)),
            |(_, _, header_list)| PartSpecifier::HeaderFieldsNot(header_list),
        ),
        map(
            tuple((tag_no_case(b"HEADER.FIELDS"), sp, header_list)),
            |(_, _, header_list)| PartSpecifier::HeaderFields(header_list),
        ),
        value(PartSpecifier::Header, tag_no_case(b"HEADER")),
        value(PartSpecifier::Text, tag_no_case(b"TEXT")),
    ))(input)
}

#[inline]
/// `section-part = nz-number *("." nz-number)`
///
/// Body part nesting
pub(crate) fn section_part(input: &[u8]) -> IMAPResult<&[u8], NonEmptyVec<NonZeroU32>> {
    map(
        separated_list1(tag(b"."), nz_number),
        NonEmptyVec::unvalidated,
    )(input)
}

/// `section-text = section-msgtext / "MIME"`
///
/// Text other than actual body part (headers, etc.)
pub(crate) fn section_text(input: &[u8]) -> IMAPResult<&[u8], PartSpecifier> {
    alt((
        section_msgtext,
        value(PartSpecifier::Mime, tag_no_case(b"MIME")),
    ))(input)
}

/// `header-list = "(" header-fld-name *(SP header-fld-name) ")"`
pub(crate) fn header_list(input: &[u8]) -> IMAPResult<&[u8], NonEmptyVec<AString>> {
    map(
        delimited(tag(b"("), separated_list1(sp, header_fld_name), tag(b")")),
        NonEmptyVec::unvalidated,
    )(input)
}

#[inline]
/// `header-fld-name = astring`
pub(crate) fn header_fld_name(input: &[u8]) -> IMAPResult<&[u8], AString> {
    astring(input)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::known_answer_test_encode;

    #[test]
    fn test_encode_section() {
        let tests = [
            (
                Section::Part(Part(NonEmptyVec::from(NonZeroU32::try_from(1).unwrap()))),
                b"1".as_ref(),
            ),
            (Section::Header(None), b"HEADER"),
            (
                Section::Header(Some(Part(NonEmptyVec::from(
                    NonZeroU32::try_from(1).unwrap(),
                )))),
                b"1.HEADER",
            ),
            (
                Section::HeaderFields(None, NonEmptyVec::from(AString::try_from("").unwrap())),
                b"HEADER.FIELDS (\"\")",
            ),
            (
                Section::HeaderFields(
                    Some(Part(NonEmptyVec::from(NonZeroU32::try_from(1).unwrap()))),
                    NonEmptyVec::from(AString::try_from("").unwrap()),
                ),
                b"1.HEADER.FIELDS (\"\")",
            ),
            (
                Section::HeaderFieldsNot(None, NonEmptyVec::from(AString::try_from("").unwrap())),
                b"HEADER.FIELDS.NOT (\"\")",
            ),
            (
                Section::HeaderFieldsNot(
                    Some(Part(NonEmptyVec::from(NonZeroU32::try_from(1).unwrap()))),
                    NonEmptyVec::from(AString::try_from("").unwrap()),
                ),
                b"1.HEADER.FIELDS.NOT (\"\")",
            ),
            (Section::Text(None), b"TEXT"),
            (
                Section::Text(Some(Part(NonEmptyVec::from(
                    NonZeroU32::try_from(1).unwrap(),
                )))),
                b"1.TEXT",
            ),
            (
                Section::Mime(Part(NonEmptyVec::from(NonZeroU32::try_from(1).unwrap()))),
                b"1.MIME",
            ),
        ];

        for test in tests {
            known_answer_test_encode(test)
        }
    }
}