Add "checked" variant of set_category()

This commit is contained in:
Matthias Beyer 2017-05-31 19:21:44 +02:00
parent af4612deef
commit c3088faa4c
2 changed files with 19 additions and 1 deletions

View file

@ -28,6 +28,7 @@ use libimagerror::into::IntoError;
use error::CategoryErrorKind as CEK; use error::CategoryErrorKind as CEK;
use error::MapErrInto; use error::MapErrInto;
use result::Result; use result::Result;
use register::CategoryRegister;
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Category(String); pub struct Category(String);
@ -49,6 +50,9 @@ impl Into<String> for Category {
pub trait EntryCategory { pub trait EntryCategory {
fn set_category(&mut self, s: Category) -> Result<()>; fn set_category(&mut self, s: Category) -> Result<()>;
fn set_category_checked(&mut self, register: &CategoryRegister, s: Category) -> Result<()>;
fn get_category(&self) -> Result<Option<Category>>; fn get_category(&self) -> Result<Option<Category>>;
fn has_category(&self) -> Result<bool>; fn has_category(&self) -> Result<bool>;
@ -64,6 +68,18 @@ impl EntryCategory for Entry {
.map(|_| ()) .map(|_| ())
} }
/// Check whether a category exists before setting it.
///
/// This function should be used by default over EntryCategory::set_category()!
fn set_category_checked(&mut self, register: &CategoryRegister, s: Category) -> Result<()> {
register.category_exists(&s.0)
.and_then(|bl| if bl {
self.set_category(s)
} else {
Err(CEK::CategoryDoesNotExist.into_error())
})
}
fn get_category(&self) -> Result<Option<Category>> { fn get_category(&self) -> Result<Option<Category>> {
match self.get_header().read(&String::from("category.value")) { match self.get_header().read(&String::from("category.value")) {
Err(res) => match res.kind() { Err(res) => match res.kind() {

View file

@ -24,7 +24,9 @@ generate_error_module!(
StoreIdHandlingError => "StoreId handling error", StoreIdHandlingError => "StoreId handling error",
HeaderReadError => "Header read error", HeaderReadError => "Header read error",
HeaderWriteError => "Header write error", HeaderWriteError => "Header write error",
TypeError => "Found wrong type in header" TypeError => "Found wrong type in header",
CategoryDoesNotExist => "Category does not exist"
); );
); );