add constructor for pulldown-cmark options; fixes #1
This commit is contained in:
parent
43e6e3e508
commit
fbd6f63ca4
60
src/lib.rs
60
src/lib.rs
|
@ -1,20 +1,72 @@
|
|||
use pulldown_cmark::{Options, Parser};
|
||||
use roxy_core::roxy::Parse;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MarkdownParser;
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MarkdownParser {
|
||||
options: Option<Options>
|
||||
}
|
||||
|
||||
impl MarkdownParser {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_options(options: Options) -> Self {
|
||||
Self {
|
||||
options: Some(options)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_parser<'a, 'b>(&self, input: &'a str) -> Parser<'a, 'b> {
|
||||
match self.options {
|
||||
Some(options) => Parser::new_ext(input, options),
|
||||
None => Parser::new(input),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for MarkdownParser {
|
||||
fn parse(&mut self, _path: &str, src: &[u8], dst: &mut Vec<u8>) -> Result<(), roxy_core::error::Error> {
|
||||
let src = String::from_utf8_lossy(src).to_string();
|
||||
let parser = pulldown_cmark::Parser::new(src.as_str());
|
||||
let parser = self.get_parser(src.as_str());
|
||||
pulldown_cmark::html::write_html(dst, parser)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pulldown_cmark::Options;
|
||||
use roxy_core::roxy::Parse;
|
||||
|
||||
use crate::MarkdownParser;
|
||||
|
||||
#[test]
|
||||
fn basic_markdown() {
|
||||
let expected = b"<p><em>this</em> <strong>is</strong> <strong>some</strong> <a href=\"google.com\">markdown</a></p>\n";
|
||||
let input = b"*this* **is** __some__ [markdown](google.com)";
|
||||
let mut parser = MarkdownParser::new();
|
||||
let mut buf = Vec::new();
|
||||
let result = parser.parse("", input, &mut buf);
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(buf, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables() {
|
||||
let expected = b"<table><thead><tr><th>Header 1</th><th>Header 2</th></tr></thead><tbody>
|
||||
<tr><td>Cell 1</td><td>Cell 2</td></tr>
|
||||
<tr><td>Cell 3</td><td>Cell 4</td></tr>
|
||||
</tbody></table>\n";
|
||||
|
||||
let input = b"| Header 1 | Header 2 |
|
||||
| -------- | -------- |
|
||||
| Cell 1 | Cell 2 |
|
||||
| Cell 3 | Cell 4 |";
|
||||
let mut parser = MarkdownParser::with_options(Options::ENABLE_TABLES);
|
||||
let mut buf = Vec::new();
|
||||
let result = parser.parse("", input, &mut buf);
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(buf, expected);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue