2022-07-01 15:07:22 +00:00
|
|
|
use indexmap::IndexMap;
|
|
|
|
|
2022-06-11 18:51:37 +00:00
|
|
|
use crate::Random;
|
2022-06-11 15:22:46 +00:00
|
|
|
use crate::StringKey;
|
2021-01-30 21:29:59 +00:00
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// 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.
|
2021-01-30 21:29:59 +00:00
|
|
|
pub trait DataLibrary<'a, T: 'a> {
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Returns the underlying map.
|
|
|
|
fn map(&self) -> &IndexMap<StringKey, T>;
|
|
|
|
/// Returns the underlying map in mutable manner.
|
|
|
|
fn get_modify(&mut self) -> &mut IndexMap<StringKey, T>;
|
2021-01-30 21:29:59 +00:00
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Adds a new value to the library.
|
2022-06-11 15:22:46 +00:00
|
|
|
fn add(&mut self, key: &StringKey, value: T) {
|
2022-07-01 15:07:22 +00:00
|
|
|
self.get_modify().insert(key.clone(), value);
|
2021-01-30 21:29:59 +00:00
|
|
|
}
|
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Removes a value from the library.
|
2022-06-11 15:22:46 +00:00
|
|
|
fn remove(&mut self, key: &StringKey) {
|
2022-07-01 15:07:22 +00:00
|
|
|
self.get_modify().remove(key);
|
2021-01-30 21:29:59 +00:00
|
|
|
}
|
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Gets a value from the library.
|
2022-06-17 17:53:33 +00:00
|
|
|
fn get(&'a self, key: &StringKey) -> Option<&'a T> {
|
2022-07-01 15:07:22 +00:00
|
|
|
self.map().get::<StringKey>(key)
|
2021-01-30 21:29:59 +00:00
|
|
|
}
|
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Gets a mutable value from the library.
|
2022-06-11 15:22:46 +00:00
|
|
|
fn get_mut(&mut self, key: &StringKey) -> Option<&mut T> {
|
2022-07-01 15:07:22 +00:00
|
|
|
self.get_modify().get_mut(key)
|
2021-01-30 21:29:59 +00:00
|
|
|
}
|
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Gets the amount of values in the library.
|
2021-01-30 21:29:59 +00:00
|
|
|
fn len(&self) -> usize {
|
|
|
|
self.map().len()
|
|
|
|
}
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Returns whether the library has no values.
|
2021-01-30 21:29:59 +00:00
|
|
|
fn is_empty(&self) -> bool {
|
|
|
|
self.map().is_empty()
|
|
|
|
}
|
|
|
|
|
2022-07-01 15:07:22 +00:00
|
|
|
/// Gets a random value from the library.
|
2021-01-30 21:29:59 +00:00
|
|
|
fn random_value(&self, rand: &mut Random) -> &T {
|
2022-07-01 15:07:22 +00:00
|
|
|
let i = rand.get_between(0, self.len() as i32);
|
|
|
|
return &self.map().get_index(i as usize).unwrap().1;
|
2021-01-30 21:29:59 +00:00
|
|
|
}
|
|
|
|
}
|