~deciduously/fcalc

ref: ab5f3ffdbc8c819466fedac28c8317b6af8bd799 fcalc/src/item.rs -rw-r--r-- 1.5 KiB
ab5f3ffdBen Lovy ItemQuantity a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! 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);
    }
}