This commit is contained in:
@@ -1,43 +1,48 @@
|
||||
use indexmap::IndexMap;
|
||||
|
||||
use crate::Random;
|
||||
use crate::StringKey;
|
||||
use hashbrown::HashMap;
|
||||
|
||||
/// 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> {
|
||||
fn map(&self) -> &HashMap<StringKey, T>;
|
||||
fn list_values(&self) -> &Vec<StringKey>;
|
||||
fn get_modify(&mut self) -> (&mut HashMap<StringKey, T>, &mut Vec<StringKey>);
|
||||
/// 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>;
|
||||
|
||||
/// Adds a new value to the library.
|
||||
fn add(&mut self, key: &StringKey, value: T) {
|
||||
let modifies = self.get_modify();
|
||||
modifies.0.insert(key.clone(), value);
|
||||
modifies.1.push(key.clone());
|
||||
self.get_modify().insert(key.clone(), value);
|
||||
}
|
||||
|
||||
/// Removes a value from the library.
|
||||
fn remove(&mut self, key: &StringKey) {
|
||||
let modifies = self.get_modify();
|
||||
let index = modifies.1.iter().position(|r| r == key).unwrap();
|
||||
modifies.0.remove(key);
|
||||
modifies.1.remove(index);
|
||||
self.get_modify().remove(key);
|
||||
}
|
||||
|
||||
/// Gets a value from the library.
|
||||
fn get(&'a self, key: &StringKey) -> Option<&'a T> {
|
||||
self.map().get(key)
|
||||
self.map().get::<StringKey>(key)
|
||||
}
|
||||
|
||||
/// Gets a mutable value from the library.
|
||||
fn get_mut(&mut self, key: &StringKey) -> Option<&mut T> {
|
||||
self.get_modify().0.get_mut(key)
|
||||
self.get_modify().get_mut(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) -> &T {
|
||||
let i = rand.get_between(0, self.list_values().len() as i32);
|
||||
let key = &self.list_values()[i as usize];
|
||||
return &self.map()[key];
|
||||
let i = rand.get_between(0, self.len() as i32);
|
||||
return &self.map().get_index(i as usize).unwrap().1;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user