PkmnLib_rs/src/static_data/libraries/item_library.rs

81 lines
2.0 KiB
Rust
Raw Normal View History

2022-12-24 11:00:50 +00:00
use std::fmt::Debug;
use std::sync::Arc;
2022-07-01 15:07:22 +00:00
use indexmap::IndexMap;
2022-06-11 18:51:37 +00:00
use crate::static_data::DataLibrary;
use crate::static_data::Item;
use crate::{StringKey, ValueIdentifiable, ValueIdentifier};
2022-07-01 15:07:22 +00:00
/// A library to store all items.
2022-12-24 11:00:50 +00:00
pub trait ItemLibrary: DataLibrary<dyn Item> + ValueIdentifiable + Debug {}
2022-11-27 16:29:29 +00:00
2022-12-24 11:00:50 +00:00
/// A library to store all items.
#[derive(Debug)]
pub struct ItemLibraryImpl {
/// A unique identifier so we know what value this is.
identifier: ValueIdentifier,
2022-07-01 15:07:22 +00:00
/// The underlying data structure.
2022-11-27 16:29:29 +00:00
map: IndexMap<StringKey, Arc<dyn Item>>,
}
2022-12-24 11:00:50 +00:00
impl ItemLibraryImpl {
2022-07-01 15:07:22 +00:00
/// Instantiates a new Item Library.
2022-12-24 11:00:50 +00:00
pub fn new(capacity: usize) -> Self {
Self {
identifier: Default::default(),
2022-07-01 15:07:22 +00:00
map: IndexMap::with_capacity(capacity),
}
}
}
2022-12-24 11:00:50 +00:00
impl ItemLibrary for ItemLibraryImpl {}
impl DataLibrary<dyn Item> for ItemLibraryImpl {
2022-11-27 16:29:29 +00:00
fn map(&self) -> &IndexMap<StringKey, Arc<dyn Item>> {
&self.map
}
2022-11-27 16:29:29 +00:00
fn get_modify(&mut self) -> &mut IndexMap<StringKey, Arc<dyn Item>> {
2022-07-01 15:07:22 +00:00
&mut self.map
}
}
2022-12-24 11:00:50 +00:00
impl ValueIdentifiable for ItemLibraryImpl {
fn value_identifier(&self) -> ValueIdentifier {
self.identifier
}
}
#[cfg(test)]
pub mod tests {
use hashbrown::HashSet;
use std::sync::Arc;
use crate::static_data::libraries::data_library::DataLibrary;
use crate::static_data::libraries::item_library::ItemLibrary;
use crate::static_data::{BattleItemCategory, ItemCategory};
2022-12-24 11:00:50 +00:00
use crate::static_data::{ItemImpl, ItemLibraryImpl};
2022-11-27 16:29:29 +00:00
fn build_item() -> ItemImpl {
ItemImpl::new(
&"foo".into(),
ItemCategory::MiscItem,
BattleItemCategory::MiscBattleItem,
100,
HashSet::new(),
)
}
2022-12-24 11:00:50 +00:00
pub fn build() -> Box<dyn ItemLibrary> {
let mut lib = ItemLibraryImpl::new(1);
let m = build_item();
// Borrow as mut so we can insert
let w = &mut lib;
w.add(&"foo".into(), Arc::new(m));
// Drops borrow as mut
2022-12-24 11:00:50 +00:00
Box::new(lib)
}
}