Refactor external linking into trait

This commit is contained in:
Matthias Beyer 2016-02-15 13:22:10 +01:00
parent 277c31237a
commit 1e17b10568

View file

@ -7,44 +7,58 @@ use result::Result;
use toml::Value; use toml::Value;
use toml::Table; use toml::Table;
pub fn get_link(header: &EntryHeader) -> Result<Option<Link>> { pub trait ExternalLinker {
let uri = header.read("imag.content.uri");
if uri.is_err() { /// get the external link from the implementor object
let kind = LinkErrorKind::EntryHeaderReadError; fn get_external_link(&self) -> Result<Option<Link>>;
let lerr = LinkError::new(kind, Some(Box::new(uri.err().unwrap())));
return Err(lerr);
}
let uri = uri.unwrap();
match uri { /// set the external link for the implementor object and return the current link from the entry,
Some(Value::String(s)) => Ok(Some(Link::new(s))), /// if any.
_ => Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)), fn set_external_link(&mut self, l: Link) -> Result<Option<Link>>;
}
} }
/// Set an external link in the header impl ExternalLinker for EntryHeader {
///
/// Return the previous set link if there was any
pub fn set_link(header: &mut EntryHeader, l: Link) -> Result<Option<Link>> {
let old_link = header.set("imag.content.uri", Value::String(l.into()));
if old_link.is_err() { fn get_external_link(&self) -> Result<Option<Link>> {
let kind = LinkErrorKind::EntryHeaderWriteError; let uri = self.read("imag.content.uri");
let lerr = LinkError::new(kind, Some(Box::new(old_link.err().unwrap())));
return Err(lerr);
}
let old_link = old_link.unwrap();
if old_link.is_none() { if uri.is_err() {
return Ok(None); let kind = LinkErrorKind::EntryHeaderReadError;
let lerr = LinkError::new(kind, Some(Box::new(uri.err().unwrap())));
return Err(lerr);
}
let uri = uri.unwrap();
match uri {
Some(Value::String(s)) => Ok(Some(Link::new(s))),
_ => Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None)),
}
} }
match old_link.unwrap() { /// Set an external link in the header
Value::String(s) => Ok(Some(Link::new(s))), ///
/// Return the previous set link if there was any
fn set_external_link(&mut self, l: Link) -> Result<Option<Link>> {
let old_link = self.set("imag.content.uri", Value::String(l.into()));
// We don't do anything in this case and be glad we corrected the type error with this set() if old_link.is_err() {
_ => Ok(None), let kind = LinkErrorKind::EntryHeaderWriteError;
let lerr = LinkError::new(kind, Some(Box::new(old_link.err().unwrap())));
return Err(lerr);
}
let old_link = old_link.unwrap();
if old_link.is_none() {
return Ok(None);
}
match old_link.unwrap() {
Value::String(s) => Ok(Some(Link::new(s))),
// We don't do anything in this case and be glad we corrected the type error with this set()
_ => Ok(None),
}
} }
} }