Add: EntryHeader::parse()

Introduce Error + Error-kind for it, return Result<> from the ::parse()
function.
This commit is contained in:
Matthias Beyer 2016-01-18 14:12:12 +01:00
parent b44fd9fec0
commit 6be3011e85

View file

@ -1,5 +1,75 @@
use std::error::Error;
use std::result::Result as RResult;
use toml::Table; use toml::Table;
pub mod error {
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::error::Error;
use toml;
#[derive(Clone)]
pub enum ParserErrorKind {
TOMLParserErrors,
MissingMainSection,
}
pub struct ParserError {
kind: ParserErrorKind,
cause: Option<Box<Error>>,
}
impl ParserError {
pub fn new(k: ParserErrorKind, cause: Option<Box<Error>>) -> ParserError {
ParserError {
kind: k,
cause: cause,
}
}
}
impl Debug for ParserError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "{:?}", self.description()));
Ok(())
}
}
impl Display for ParserError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "{}", self.description()));
Ok(())
}
}
impl Error for ParserError {
fn description(&self) -> &str {
match self.kind {
ParserErrorKind::MissingMainSection => "Missing main section",
ParserErrorKind::TOMLParserErrors => "Several TOML-Parser-Errors",
}
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}
}
use self::error::ParserErrorKind;
use self::error::ParserError;
/** /**
* EntryHeader * EntryHeader
* *
@ -11,6 +81,11 @@ pub struct EntryHeader {
toml: Table, toml: Table,
} }
pub type Result<V> = RResult<V, error::ParserError>;
/**
* Wrapper type around file header (TOML) object
*/
impl EntryHeader { impl EntryHeader {
/** /**
@ -29,4 +104,13 @@ impl EntryHeader {
&self.toml &self.toml
} }
pub fn parse(s: &str) -> Result<EntryHeader> {
use toml::Parser;
let mut parser = Parser::new(s);
parser.parse()
.ok_or(ParserError::new(ParserErrorKind::TOMLParserErrors, None))
.map(|table| EntryHeader::new(table))
}
} }