use crate::Builtins::Core::{DixValue, IBuiltinMethod};
use std::collections::HashMap;
pub trait IStaticObject: Send + Sync {
fn name(&self) -> &str;
fn call_method(&self, method_name: &str, args: &[DixValue]) -> Result<DixValue, String>;
fn has_method(&self, method_name: &str) -> bool;
fn get_method_names(&self) -> Vec<String>;
fn get_method(&self, method_name: &str) -> Option<&dyn IBuiltinMethod>;
}
pub struct StaticObjectBase {
name: String,
methods: HashMap<String, Box<dyn IBuiltinMethod>>,
}
impl StaticObjectBase {
pub fn new(name: String) -> Self {
StaticObjectBase {
name,
methods: HashMap::new(),
}
}
pub fn register_method(&mut self, method: Box<dyn IBuiltinMethod>) {
let name = method.name().to_string();
self.methods.insert(name, method);
}
pub fn name(&self) -> &str {
&self.name
}
pub fn call_method(&self, method_name: &str, args: &[DixValue]) -> Result<DixValue, String> {
let method = self
.methods
.get(method_name)
.ok_or_else(|| format!("{} object has no method: {}", self.name, method_name))?;
method.call(args)
}
pub fn has_method(&self, method_name: &str) -> bool {
self.methods.contains_key(method_name)
}
pub fn get_method_names(&self) -> Vec<String> {
self.methods.keys().cloned().collect()
}
pub fn get_method(&self, method_name: &str) -> Option<&dyn IBuiltinMethod> {
self.methods
.get(method_name)
.map(|boxed| &**boxed as &dyn IBuiltinMethod)
}
}