fabaccess-bffh/bffhd/resources/search.rs

59 lines
1.5 KiB
Rust
Raw Permalink Normal View History

2022-05-05 15:50:44 +02:00
use crate::resources::Resource;
2022-03-13 20:33:26 +01:00
use std::collections::HashMap;
2022-03-13 17:29:21 +01:00
use std::sync::Arc;
struct Inner {
2022-03-13 20:33:26 +01:00
id: HashMap<String, Resource>,
2022-03-13 17:29:21 +01:00
}
impl Inner {
2022-05-05 15:50:44 +02:00
pub fn new(resources: impl IntoIterator<Item = Resource>) -> Self {
2022-03-13 20:33:26 +01:00
let mut id = HashMap::new();
for resource in resources {
let old = id.insert(resource.inner.id.clone(), resource);
assert!(old.is_none());
}
Self { id }
2022-03-13 17:29:21 +01:00
}
}
#[derive(Clone)]
pub struct ResourcesHandle {
inner: Arc<Inner>,
}
impl ResourcesHandle {
2022-05-05 15:50:44 +02:00
pub fn new(resources: impl IntoIterator<Item = Resource>) -> Self {
2022-03-13 17:29:21 +01:00
Self {
2022-03-13 20:33:26 +01:00
inner: Arc::new(Inner::new(resources)),
2022-03-13 17:29:21 +01:00
}
}
2022-05-05 15:50:44 +02:00
pub fn list_all(&self) -> impl IntoIterator<Item = &Resource> {
2022-03-13 20:33:26 +01:00
self.inner.id.values()
2022-03-13 17:29:21 +01:00
}
pub fn get_by_id(&self, id: &str) -> Option<&Resource> {
2022-03-13 20:33:26 +01:00
self.inner.id.get(id)
2022-03-13 17:29:21 +01:00
}
pub fn get_by_urn(&self, urn: &str) -> Option<&Resource> {
2022-03-13 20:33:26 +01:00
if let Some(id) = {
let mut parts = urn.split_terminator(':');
let part_urn = parts.next().map(|u| u == "urn").unwrap_or(false);
let part_fabaccess = parts.next().map(|f| f == "fabaccess").unwrap_or(false);
let part_resource = parts.next().map(|r| r == "resource").unwrap_or(false);
if !(part_urn && part_fabaccess && part_resource) {
return None;
}
parts.next().map(|s| s.to_string())
} {
self.get_by_id(&id)
} else {
None
}
2022-03-13 17:29:21 +01:00
}
}