PkmnLib_rs/src/dynamic_data/script_handling/script_set.rs

70 lines
1.8 KiB
Rust
Raw Normal View History

2022-06-03 14:35:18 +00:00
use crate::dynamic_data::script_handling::script::Script;
2022-06-06 11:54:59 +00:00
use crate::PkmnResult;
use indexmap::IndexMap;
use std::sync::Arc;
2022-06-03 14:35:18 +00:00
2022-06-06 11:54:59 +00:00
#[derive(Debug, Default)]
pub struct ScriptSet {
scripts: IndexMap<String, Arc<Box<dyn Script>>>,
}
2022-06-03 14:35:18 +00:00
impl ScriptSet {
2022-06-06 11:54:59 +00:00
pub fn add(&mut self, script: Box<dyn Script>) -> Arc<Box<dyn Script>> {
if let Some(existing) = self.scripts.get(script.name()) {
existing.stack();
return existing.clone();
}
let arc = Arc::new(script);
self.scripts.insert(arc.name().to_string(), arc.clone());
self.scripts.last().unwrap().1.clone()
}
pub fn stack_or_add<'b, F>(
&mut self,
key: &str,
instantiation: &'b F,
) -> PkmnResult<Arc<Box<dyn Script>>>
where
F: Fn() -> PkmnResult<Box<dyn Script>>,
{
if let Some(existing) = self.scripts.get(key) {
existing.stack();
return Ok(existing.clone());
}
let script = instantiation()?;
let arc = Arc::new(script);
self.scripts.insert(arc.name().to_string(), arc.clone());
Ok(self.scripts.last().unwrap().1.clone())
}
pub fn get(&self, key: &str) -> Option<&Arc<Box<dyn Script>>> {
self.scripts.get(key)
}
pub fn remove(&mut self, key: &str) {
let value = self.scripts.shift_remove(key);
if let Some(script) = value {
script.on_remove();
}
2022-06-03 14:35:18 +00:00
}
2022-06-06 11:54:59 +00:00
pub fn clear(&mut self) {
for script in &self.scripts {
script.1.on_remove();
}
self.scripts.clear();
}
pub fn has(&self, key: &str) -> bool {
self.scripts.contains_key(key)
}
pub fn at(&self, index: usize) -> &Arc<Box<dyn Script>> {
&self.scripts[index]
}
pub fn count(&self) -> usize {
self.scripts.len()
2022-06-03 14:35:18 +00:00
}
}