feat(export): handler with custom error type

This commit is contained in:
PoiScript 2019-03-13 16:16:57 +08:00
parent 355ea8b46e
commit 0b22db1f0f
4 changed files with 256 additions and 237 deletions

View file

@ -1,26 +1,53 @@
use std::env::args;
use std::fs::File;
use std::io::{Cursor, Read, Result, Write};
use orgize::export::*;
use orgize::headline::Headline;
use slugify::slugify;
use std::convert::From;
use std::env::args;
use std::fs::File;
use std::io::{Cursor, Error as IOError, Read, Write};
use std::string::FromUtf8Error;
struct CustomHtmlHandler;
impl<W: Write> HtmlHandler<W> for CustomHtmlHandler {
fn handle_headline_beg(&mut self, w: &mut W, hdl: Headline) -> Result<()> {
write!(
w,
r##"<h{0}><a class="anchor" href="#{1}">{2}</a></h{0}>"##,
if hdl.level <= 6 { hdl.level } else { 6 },
slugify!(hdl.title),
hdl.title,
)
#[derive(Debug)]
enum Error {
IO(IOError),
Heading,
Utf8(FromUtf8Error),
}
// From<std::io::Error> trait is required
impl From<IOError> for Error {
fn from(err: IOError) -> Error {
Error::IO(err)
}
}
fn main() -> Result<()> {
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::Utf8(err)
}
}
type Result = std::result::Result<(), Error>;
impl<W: Write> HtmlHandler<W, Error> for CustomHtmlHandler {
fn handle_headline_beg(&mut self, w: &mut W, hdl: Headline) -> Result {
if hdl.level > 6 {
Err(Error::Heading)
} else {
Ok(write!(
w,
r##"<h{0}><a class="anchor" href="#{1}">{2}</a></h{0}>"##,
hdl.level,
slugify!(hdl.title),
hdl.title,
)?)
}
}
}
fn main() -> Result {
let args: Vec<_> = args().collect();
if args.len() < 2 {
@ -39,10 +66,7 @@ fn main() -> Result<()> {
render.render()?;
println!(
"{}",
String::from_utf8(cursor.into_inner()).expect("invalid utf-8")
);
println!("{}", String::from_utf8(cursor.into_inner())?);
}
Ok(())