PkmnLib_rs/src/static_data/libraries/data_library.rs

51 lines
1.5 KiB
Rust
Executable File

use std::sync::Arc;
use indexmap::IndexMap;
use crate::Random;
use crate::StringKey;
/// A data library is a collection of methods to set up a default library, where values are stored
/// by both key, while keeping their insertion order.
pub trait DataLibrary<'a, T: 'a> {
/// Returns the underlying map.
fn map(&self) -> &IndexMap<StringKey, Arc<T>>;
/// Returns the underlying map in mutable manner.
fn get_modify(&mut self) -> &mut IndexMap<StringKey, Arc<T>>;
/// Adds a new value to the library.
fn add(&mut self, key: &StringKey, value: T) {
self.get_modify().insert(key.clone(), Arc::new(value));
}
/// Removes a value from the library.
fn remove(&mut self, key: &StringKey) {
self.get_modify().remove(key);
}
/// Gets a value from the library.
fn get(&'a self, key: &StringKey) -> Option<&Arc<T>> {
self.map().get::<StringKey>(key)
}
/// Gets a value from the library.
fn get_by_hash(&'a self, key: u32) -> Option<&Arc<T>> {
self.map().get::<u32>(&key)
}
/// Gets the amount of values in the library.
fn len(&self) -> usize {
self.map().len()
}
/// Returns whether the library has no values.
fn is_empty(&self) -> bool {
self.map().is_empty()
}
/// Gets a random value from the library.
fn random_value(&self, rand: &mut Random) -> &Arc<T> {
let i = rand.get_between(0, self.len() as i32);
return self.map().get_index(i as usize).unwrap().1;
}
}