imag/libimaglink/src/internal.rs

59 lines
1.7 KiB
Rust
Raw Normal View History

2016-02-03 14:47:14 +00:00
use libimagstore::store::EntryHeader;
2016-02-14 16:50:06 +00:00
use libimagstore::store::Result as StoreResult;
2016-02-03 14:47:14 +00:00
use error::{LinkError, LinkErrorKind};
use link::{Link, Links};
use result::Result;
2016-02-07 15:25:17 +00:00
use toml::Value;
2016-02-03 14:47:14 +00:00
pub fn get_links(header: &EntryHeader) -> Result<Links> {
2016-02-07 15:25:17 +00:00
process_rw_result(header.read("imag.links"))
2016-02-03 14:47:14 +00:00
}
2016-02-07 15:40:33 +00:00
/// Set the links in a header and return the old links, if any.
2016-02-03 14:47:14 +00:00
pub fn set_links(header: &mut EntryHeader, links: Links) -> Result<Links> {
2016-02-07 15:40:33 +00:00
let links : Vec<Link> = links.into();
let links : Vec<Value> = links.into_iter().map(|link| Value::String(link.into())).collect();
process_rw_result(header.set("imag.links", Value::Array(links)))
2016-02-03 14:47:14 +00:00
}
pub fn add_link(header: &mut EntryHeader, link: Link) -> Result<()> {
2016-02-15 12:18:57 +00:00
get_links(header).and_then(|mut links| {
links.add(link);
set_links(header, links).map(|_| ())
})
2016-02-03 14:47:14 +00:00
}
2016-02-15 12:19:34 +00:00
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(|_| ())
})
}
2016-02-14 16:50:06 +00:00
fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Links> {
if links.is_err() {
let lerr = LinkError::new(LinkErrorKind::EntryHeaderReadError,
Some(Box::new(links.err().unwrap())));
return Err(lerr);
}
let links = links.unwrap();
if links.iter().any(|l| match l { &Value::String(_) => true, _ => false }) {
return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
}
let links : Vec<Link> = links.into_iter()
.map(|link| {
match link {
Value::String(s) => Link::new(s),
_ => unreachable!(),
}
})
.collect();
Ok(Links::new(links))
}