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
use std::borrow::Cow;

use nom::{
    bytes::complete::{tag, take_while},
    combinator::opt,
    sequence::delimited,
    IResult,
};

/// Link Object
#[cfg_attr(test, derive(PartialEq))]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
#[derive(Debug, Clone)]
pub struct Link<'a> {
    /// Link destination
    pub path: Cow<'a, str>,
    #[cfg_attr(feature = "ser", serde(skip_serializing_if = "Option::is_none"))]
    pub desc: Option<Cow<'a, str>>,
}

impl Link<'_> {
    #[inline]
    pub(crate) fn parse(input: &str) -> Option<(&str, Link)> {
        parse_internal(input).ok()
    }

    pub fn into_owned(self) -> Link<'static> {
        Link {
            path: self.path.into_owned().into(),
            desc: self.desc.map(Into::into).map(Cow::Owned),
        }
    }
}

#[inline]
fn parse_internal(input: &str) -> IResult<&str, Link, ()> {
    let (input, path) = delimited(
        tag("[["),
        take_while(|c: char| c != '<' && c != '>' && c != '\n' && c != ']'),
        tag("]"),
    )(input)?;
    let (input, desc) = opt(delimited(
        tag("["),
        take_while(|c: char| c != '[' && c != ']'),
        tag("]"),
    ))(input)?;
    let (input, _) = tag("]")(input)?;
    Ok((
        input,
        Link {
            path: path.into(),
            desc: desc.map(Into::into),
        },
    ))
}

#[test]
fn parse() {
    assert_eq!(
        Link::parse("[[#id]]"),
        Some((
            "",
            Link {
                path: "#id".into(),
                desc: None
            }
        ))
    );
    assert_eq!(
        Link::parse("[[#id][desc]]"),
        Some((
            "",
            Link {
                path: "#id".into(),
                desc: Some("desc".into())
            }
        ))
    );
    assert!(Link::parse("[[#id][desc]").is_none());
}