//! An item is something the player can hold. Some are raw, some are craftable.
use crate::recipe::{Recipe, RECIPES};
use lazy_static::lazy_static;
use serde::Deserialize;
use std::fmt;
lazy_static! {
pub static ref ITEMS: Items = Items::new();
}
/// An item in a recipe
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Item {
pub name: String,
pub raw: bool,
}
impl Item {
pub fn recipe(&self) -> Option<&Recipe> {
if !self.raw {
RECIPES.lookup(self)
} else {
None
}
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
/// The top-level Items struct, containing all supported items read from TOML.
#[derive(Debug, Deserialize)]
pub struct Items {
items: Vec<Item>,
}
impl Items {
fn new() -> Self {
Self::default()
}
/// Find an item by name
pub fn lookup(&self, name: &str) -> Option<Item> {
for i in &self.items {
if i.name == name {
return Some(i.clone());
}
}
None
}
}
impl Default for Items {
fn default() -> Self {
let input = include_str!("items.toml");
toml::from_str(input).expect("Could not read items file")
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn it_loads_all_items() {
assert_eq!(ITEMS.items.len(), 3);
}
}