Add StoreId::is_in_collection()

The concept of this function was introduced in

    37076f028c6cde0924b820154f3464f53ef65268

but here added to StoreId as function.
This commit is contained in:
Matthias Beyer 2016-08-28 13:39:37 +02:00
parent 82f08c6021
commit b1898887c2

View file

@ -86,6 +86,29 @@ impl StoreId {
self.id.components()
}
/// Check whether a StoreId points to an entry in a specific collection.
///
/// A "collection" here is simply a directory. So `foo/bar/baz` is an entry which is in
/// collection ["foo", "bar"].
///
/// # Warning
///
/// The collection specification _has_ to start with the module name. Otherwise this function
/// may return false negatives.
///
pub fn is_in_collection(&self, colls: &[&str]) -> bool {
use std::path::Component;
self.id
.components()
.zip(colls)
.map(|(component, pred_coll)| match component {
Component::Normal(ref s) => s.to_str().map(|ref s| s == pred_coll).unwrap_or(false),
_ => false
})
.all(|x| x) && colls.last().map(|last| !self.id.ends_with(last)).unwrap_or(false)
}
}
impl Into<PathBuf> for StoreId {
@ -219,4 +242,26 @@ mod test {
assert_eq!(p.into_storeid().unwrap().to_str().unwrap(), "test/test");
}
#[test]
fn storeid_in_collection() {
let p = module_path::ModuleEntryPath::new("1/2/3/4/5/6/7/8/9/0").into_storeid().unwrap();
assert!(p.is_in_collection(&["test", "1"]));
assert!(p.is_in_collection(&["test", "1", "2"]));
assert!(p.is_in_collection(&["test", "1", "2", "3"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4", "5"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6", "7"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6", "7", "8"]));
assert!(p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6", "7", "8", "9"]));
// "0" is the filename, not a collection
assert!(!p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]));
assert!(!p.is_in_collection(&["test", "0", "2", "3", "4", "5", "6", "7", "8", "9", "0"]));
assert!(!p.is_in_collection(&["test", "1", "2", "3", "4", "5", "6", "8"]));
assert!(!p.is_in_collection(&["test", "1", "2", "3", "leet", "5", "6", "7"]));
}
}