Gen7ScriptsRs/pkmn_lib_interface/src/app_interface/library/data_libraries/mod.rs

74 lines
1.8 KiB
Rust

use crate::{impl_extern_ctor, ExternRef, ExternalReferenceType, StringKey};
use alloc::collections::BTreeMap;
use move_library::MoveLibrary;
use spin::rwlock::RwLock;
pub mod item_library;
pub mod move_library;
use crate::handling::Cacheable;
pub use item_library::*;
pub use move_library::*;
pub struct StaticData {
ptr: ExternRef<Self>,
}
impl_extern_ctor!(StaticData);
impl StaticData {
pub fn move_library(&self) -> MoveLibrary {
unsafe { MoveLibrary::new(static_data_get_move_library(self.ptr)) }
}
}
extern "wasm" {
fn static_data_get_move_library(ptr: ExternRef<StaticData>) -> ExternRef<MoveLibrary>;
}
pub trait DataLibrary<T>: Cacheable
where
T: ExternalReferenceType,
T: Clone,
{
fn get_cache(&self) -> &RwLock<BTreeMap<u32, T>>;
fn get_self_ref(&self) -> ExternRef<Self>
where
Self: Sized;
fn _get_ref_by_name(ptr: ExternRef<Self>, name: ExternRef<StringKey>) -> ExternRef<T>
where
Self: Sized;
fn _get_ref_by_hash(ptr: ExternRef<Self>, hash: u32) -> ExternRef<T>
where
Self: Sized;
fn get(&self, name: &StringKey) -> Option<T>
where
Self: Sized,
{
if let Some(v) = self.get_cache().read().get(&name.hash()) {
return Some(v.clone());
}
let v = Self::_get_ref_by_name(self.get_self_ref(), name.ptr()).get_value();
if let Some(v) = &v {
self.get_cache().write().insert(name.hash(), v.clone());
}
v
}
fn get_by_hash(&self, hash: u32) -> Option<T>
where
Self: Sized,
{
if let Some(v) = self.get_cache().read().get(&hash) {
return Some(v.clone());
}
let v = Self::_get_ref_by_hash(self.get_self_ref(), hash).get_value();
if let Some(v) = &v {
self.get_cache().write().insert(hash, v.clone());
}
v
}
}