fabaccess-bffh/bffhd/resources/search.rs

60 lines
1.5 KiB
Rust
Raw 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;
2023-01-09 16:58:32 +01:00
#[derive(Debug)]
2022-03-13 17:29:21 +01:00
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
}
}
2023-01-09 16:58:32 +01:00
#[derive(Clone, Debug)]
2022-03-13 17:29:21 +01:00
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
}
}