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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use std::{
    fmt::{self, Write},
    str::FromStr,
};

use crate::{parser::utils::valid_key_sequence_cow, properties::fold_line};

use super::{
    parameters::{parameters, Parameter},
    parsed_string::ParseString,
    utils::property_key,
};
use nom::{
    branch::alt,
    bytes::complete::{tag, take_until, take_while},
    character::complete::{line_ending, multispace0},
    combinator::{cut, map, opt},
    error::{context, convert_error, ContextError, ParseError, VerboseError},
    sequence::{preceded, separated_pair, tuple},
    Finish, IResult,
};

#[cfg(test)]
use nom::error::ErrorKind;

/// Zero-copy version of [`crate::properties::Property`]
#[derive(PartialEq, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Property<'a> {
    pub name: ParseString<'a>,
    pub val: ParseString<'a>,
    pub params: Vec<Parameter<'a>>,
}

impl<'a> Property<'a> {
    pub fn new_ref(key: &'a str, val: &'a str) -> Property<'a> {
        Property {
            name: key.into(),
            val: val.into(),
            params: vec![],
        }
    }
}

impl Property<'_> {
    pub(crate) fn fmt_write<W: Write>(&self, out: &mut W) -> Result<(), fmt::Error> {
        // A nice starting capacity for the majority of content lines
        let mut line = String::with_capacity(150);

        write!(line, "{}", self.name.as_str())?;
        for &Parameter { ref key, ref val } in &self.params {
            if let Some(val) = val {
                write!(line, ";{}={}", key.as_str(), val.as_str())?;
            } else {
                write!(line, ";{}", key.as_str())?;
            }
        }
        write!(line, ":{}", self.val.as_str())?;
        write_crlf!(out, "{}", fold_line(&line))?;
        Ok(())
    }
}

impl fmt::Display for Property<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_write(f)
    }
}

impl<'a> TryFrom<&'a str> for Property<'a> {
    type Error = String;

    fn try_from(input: &'a str) -> Result<Self, Self::Error> {
        property(input)
            .finish()
            .map(|(_, x)| x)
            .map_err(|e: VerboseError<&str>| format!("error: {}", convert_error(input, e.clone())))
    }
}

impl From<Property<'_>> for crate::Property {
    fn from(parsed: Property<'_>) -> Self {
        Self {
            key: parsed.name.as_ref().to_owned(),
            val: parsed.val.as_ref().to_owned(),
            params: parsed
                .params
                .into_iter()
                .map(|p| (p.key.as_ref().to_owned(), p.into()))
                .collect(),
        }
    }
}

impl FromStr for crate::Property {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(crate::parser::Property::try_from(s)?.into())
    }
}

#[test]
fn test_property() {
    assert_parser!(
        property,
        "KEY:VALUE\n",
        Property {
            name: "KEY".into(),
            val: "VALUE".into(),
            params: vec![]
        }
    );

    assert_parser!(
        property,
        "KEY1;foo=bar:VALUE\n",
        Property {
            name: "KEY1".into(),
            val: "VALUE".into(),
            params: vec![Parameter::new_ref("foo", Some("bar"))]
        }
    );

    assert_parser!(
        property,
        "KEY2;foo=bar:VALUE space separated\n",
        Property {
            name: "KEY2".into(),
            val: "VALUE space separated".into(),
            params: vec![Parameter::new_ref("foo", Some("bar"))]
        }
    );

    assert_parser!(
        property,
        "KEY2;foo=bar:important:VALUE\n",
        Property {
            name: "KEY2".into(),
            val: "important:VALUE".into(),
            params: vec![Parameter::new_ref("foo", Some("bar"))]
        }
    );

    // TODO: newlines followed by spaces must be ignored
    assert_parser!(
        property,
        "KEY3;foo=bar:VALUE\\n newline separated\n",
        Property {
            name: "KEY3".into(),
            val: "VALUE\\n newline separated".into(),
            params: vec![Parameter::new_ref("foo", Some("bar"))]
        }
    );
}

#[test]
fn test_property_with_dash() {
    assert_parser!(
        property,
        "X-HOODIE-KEY:VALUE\n",
        Property {
            name: "X-HOODIE-KEY".into(),
            val: "VALUE".into(),
            params: vec![]
        }
    );
}

#[test]
#[rustfmt::skip]
fn parse_properties_from_rfc() {
    // TODO: newlines followed by spaces must be ignored
    assert_parser!(
        property,
        "home.tel;type=fax,voice,msg:+49 3581 123456\n",
        Property {
            name: "home.tel".into(),
            val: "+49 3581 123456".into(),
            params: vec![Parameter ::new_ref(
                "type",
                Some("fax,voice,msg"),
            )]
        }
    );
    // TODO: newlines followed by spaces must be ignored
    assert_parser!(
        property,
        "email;internet:mb@goerlitz.de\n",
        Property {
            name: "email".into(),
            val: "mb@goerlitz.de".into(),
            params: vec![
                Parameter ::new_ref(
                "internet"  ,
                None,
            )]
        }
    );
}

#[test]
#[rustfmt::skip]
fn parse_property_with_breaks() {

    let sample_0 = "DESCRIPTION:Hey, I'm gonna have a party\\n BYOB: Bring your own beer.\\n Hendrik\\n\n";

    let expectation = Property {
        name: "DESCRIPTION".into(),
        val: "Hey, I'm gonna have a party\\n BYOB: Bring your own beer.\\n Hendrik\\n".into(),
        params: vec![]
    };

    assert_parser!(property, sample_0, expectation);
}
#[test]
#[rustfmt::skip]
fn parse_property_with_colon() {

    let sample_0 = "RELATED-TO;RELTYPE=:c605e4e8-8ea3-4315-b139-19394ab3ced6\n";
    // let sample_0 = "RELATED-TO;RELTYPE:c605e4e8-8ea3-4315-b139-19394ab3ced6\n";

    let expectation = Property {
        name: "RELATED-TO".into(),
        val: "c605e4e8-8ea3-4315-b139-19394ab3ced6".into(),
        params: vec![Parameter {
            key: "RELTYPE".into(),
            val: None
        }]
    };

    assert_parser!(property, sample_0, expectation);
}

#[test]
#[rustfmt::skip]
fn parse_property_with_no_value() {

    let sample_0 = "X-NO-VALUE";

    let expectation = Property {
        name: "X-NO-VALUE".into(),
        val: "".into(),
        params: vec![]
    };

    assert_parser!(property, sample_0, expectation);
}

pub fn property<'a, E: ParseError<&'a str> + ContextError<&'a str>>(
    input: &'a str,
) -> IResult<&'a str, Property, E> {
    context(
        "property",
        cut(map(
            tuple((
                alt((
                    separated_pair(
                        tuple((
                            // preceded(multispace0, alpha_or_dash), // key
                            cut(context(
                                // this must be interpretet as component by `component()`
                                // if you get here at all then the parser is in a wrong state
                                "property can't be END or BEGIN",
                                map(preceded(multispace0, property_key), ParseString::from),
                            )), // key
                            parameters, // params
                        )),
                        context("property sparator", tag(":")), // separator
                        context(
                            "property value",
                            map(
                                alt((
                                    take_until("\r\n"),
                                    take_until("\n"),
                                    // this is for single line prop parsing, just so I can leave off the '\n'
                                    take_while(|_| true),
                                )),
                                ParseString::from,
                            ),
                        ), // val TODO: replace this with something simpler!
                    ),
                    context(
                        "no-value property",
                        map(valid_key_sequence_cow, |key| {
                            ((key, vec![]), ParseString::from(""))
                        }), // key and nothing else
                    ),
                )),
                opt(line_ending),
            )),
            |(((key, params), val), _)| Property {
                name: key,
                val,
                params,
            },
        )),
    )(input)
}