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
use crate::{MarkdownExt, Share};
use equt_md as markdown;
use equt_md_error::Result;
use equt_md_frontmatter::FrontMatter;
use serde_yaml;
use std::iter::Peekable;
use std::rc::Rc;
use std::cell::RefCell;

/// A wrapper for the original [`Parser`].
///
/// [`Parser`]: https://docs.rs/equt-md/*/equt_md/struct.Parser.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Parser<'e> {
    parser: Peekable<markdown::Parser<'e>>,
    frontmatter: Share<RefCell<Option<FrontMatter>>>,
}

impl<'e> Parser<'e> {
    /// Create a **full-feature** parser.
    pub fn new(text: &'e str) -> Result<Parser<'e>> {
        let mut parser = markdown::Parser::new_ext(text, markdown::Options::all()).peekable();
        return if let Some(markdown::Event::Frontmatter(s)) = parser.peek() {
            let fm: FrontMatter = serde_yaml::from_str(s)?;
            parser.next();
            Ok(Parser {
                parser,
                frontmatter: Rc::new(RefCell::new(Some(fm))).into(),
            })
        } else {
            Ok(Parser {
                parser,
                frontmatter: Rc::new(RefCell::new(None)).into(),
            })
        };
    }
}

impl<'e> Iterator for Parser<'e> {
    type Item = markdown::Event<'e>;

    fn next(&mut self) -> Option<Self::Item> {
        self.parser.next()
    }
}

impl<'e> MarkdownExt<markdown::Event<'e>> for Parser<'e> {
    fn frontmatter(&mut self) -> &mut Share<RefCell<Option<FrontMatter>>> {
        &mut self.frontmatter
    }
}