plantuml_parser/dsl/token/
diagram_id.rs

1use crate::{ParseContainer, ParseResult, wr};
2use nom::bytes::complete::take_while1;
3use nom::{AsChar, Parser};
4
5/// A token sequence of `ID` included in the around of start keyword (like `"@startuml ID"` or `"@startuml(id=ID)"`)
6///
7/// # Examples
8///
9/// ```
10/// use plantuml_parser::DiagramIdToken;
11///
12/// # fn main() -> anyhow::Result<()> {
13/// let input = "id_0 rest";
14/// let (rest, (raw, token)) = DiagramIdToken::parse(input.into())?;
15/// assert_eq!(rest, " rest");
16/// assert_eq!(raw, "id_0");
17/// assert_eq!(token.id(), "id_0");
18/// # Ok(())
19/// # }
20/// ```
21#[derive(Clone, Debug)]
22pub struct DiagramIdToken {
23    id: ParseContainer,
24}
25
26impl DiagramIdToken {
27    /// Tries to parse [`DiagramIdToken`]
28    pub fn parse(input: ParseContainer) -> ParseResult<Self> {
29        let (rest, (id,)) =
30            (wr!(take_while1(|c: char| c.is_alphanum() || '_' == c)),).parse(input)?;
31
32        Ok((rest, (id.clone(), Self { id })))
33    }
34
35    /// Returns parsed `ID`
36    pub fn id(&self) -> &str {
37        self.id.as_str()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_parse() -> anyhow::Result<()> {
47        assert!(DiagramIdToken::parse("".into()).is_err());
48        assert!(DiagramIdToken::parse(" ".into()).is_err());
49
50        let testdata = "aaa  ";
51        let (rest, (parsed, id)) = DiagramIdToken::parse(testdata.into())?;
52        assert_eq!(rest, "  ");
53        assert_eq!(parsed, "aaa");
54        assert_eq!(id.id(), "aaa");
55
56        Ok(())
57    }
58}