From defec535c8e22233c5168751cef7d9897339e283 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 15 Feb 2016 13:26:00 +0100 Subject: [PATCH] Refactor internal link helpers into trait --- libimaglink/src/internal.rs | 60 +++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 19 deletions(-) diff --git a/libimaglink/src/internal.rs b/libimaglink/src/internal.rs index c34476c8..bfee3c64 100644 --- a/libimaglink/src/internal.rs +++ b/libimaglink/src/internal.rs @@ -7,29 +7,51 @@ use result::Result; use toml::Value; -pub fn get_links(header: &EntryHeader) -> Result { - process_rw_result(header.read("imag.links")) +pub trait InternalLinker { + + /// Get the internal links from the implementor object + fn get_internal_links(&self) -> Result; + + /// Set the internal links for the implementor object + fn set_internal_links(&mut self, links: Links) -> Result; + + /// Add an internal link to the implementor object + fn add_internal_link(&mut self, link: Link) -> Result<()>; + + /// Remove an internal link from the implementor object + fn remove_internal_link(&mut self, link: Link) -> Result<()>; + } -/// Set the links in a header and return the old links, if any. -pub fn set_links(header: &mut EntryHeader, links: Links) -> Result { - let links : Vec = links.into(); - let links : Vec = links.into_iter().map(|link| Value::String(link.into())).collect(); - process_rw_result(header.set("imag.links", Value::Array(links))) -} +impl InternalLinker for EntryHeader { -pub fn add_link(header: &mut EntryHeader, link: Link) -> Result<()> { - get_links(header).and_then(|mut links| { - links.add(link); - set_links(header, links).map(|_| ()) - }) -} + fn get_internal_links(self: &EntryHeader) -> Result { + process_rw_result(self.read("imag.links")) + } + + /// Set the links in a header and return the old links, if any. + fn set_internal_links(&mut self, links: Links) -> Result { + let links : Vec = links.into(); + let links : Vec = links.into_iter().map(|link| Value::String(link.into())).collect(); + process_rw_result(self.set("imag.links", Value::Array(links))) + } + + fn add_internal_link(&mut self, link: Link) -> Result<()> { + self.get_internal_links() + .and_then(|mut links| { + links.add(link); + self.set_internal_links(links).map(|_| ()) + }) + } + + fn remove_internal_link(&mut self, link: Link) -> Result<()> { + self.get_internal_links() + .and_then(|mut links| { + links.remove(link); + self.set_internal_links(links).map(|_| ()) + }) + } -pub fn remove_link(header: &mut EntryHeader, link: Link) -> Result<()> { - get_links(header).and_then(|mut links| { - links.remove(link); - set_links(header, links).map(|_| ()) - }) } fn process_rw_result(links: StoreResult>) -> Result {