57 lines
1.3 KiB
Rust
57 lines
1.3 KiB
Rust
#[derive (Debug, thiserror::Error, PartialEq)]
|
|
pub enum Error {
|
|
#[error ("File is too big to preview as Markdown")]
|
|
TooBig,
|
|
|
|
#[error ("File is not UTF-8")]
|
|
NotUtf8,
|
|
}
|
|
|
|
fn render (bytes: &[u8], out: &mut String) -> Result <(), Error> {
|
|
use pulldown_cmark::{Parser, Options, html};
|
|
|
|
let markdown_input = match std::str::from_utf8 (bytes) {
|
|
Err (_) => return Err (Error::NotUtf8),
|
|
Ok (x) => x,
|
|
};
|
|
|
|
let mut options = Options::empty ();
|
|
options.insert (Options::ENABLE_STRIKETHROUGH);
|
|
let parser = Parser::new_ext (markdown_input, options);
|
|
|
|
html::push_html (out, parser);
|
|
|
|
Ok (())
|
|
}
|
|
|
|
pub fn render_styled (bytes: &[u8]) -> Result <String, Error> {
|
|
// Write to String buffer.
|
|
let mut out = String::new ();
|
|
|
|
out.push_str ("<body style=\"font-family: sans-serif;\">");
|
|
render (bytes, &mut out)?;
|
|
out.push_str ("</body>");
|
|
|
|
Ok (out)
|
|
}
|
|
|
|
#[cfg (test)]
|
|
mod tests {
|
|
#[test]
|
|
fn markdown () {
|
|
use super::*;
|
|
|
|
for (input, expected) in vec! [
|
|
("", ""),
|
|
(
|
|
"Hello world, this is a ~~complicated~~ *very simple* example.",
|
|
"<p>Hello world, this is a <del>complicated</del> <em>very simple</em> example.</p>\n"
|
|
),
|
|
].into_iter () {
|
|
let mut out = String::default ();
|
|
render (input.as_bytes (), &mut out).expect ("Markdown sample failed");
|
|
assert_eq! (expected, &out);
|
|
}
|
|
}
|
|
}
|