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
use super::{items, Item, ITEMS};
use basin2_lib::result::*;
use basin2_lib::Nbt;
use std::convert::TryFrom;

#[derive(PartialEq, Clone, Debug)]
pub struct ItemStack {
    pub count: i32,
    pub item: Item,
    pub nbt: Option<Nbt>,
}

impl From<Item> for ItemStack {
    fn from(item: Item) -> ItemStack {
        ItemStack {
            count: 1,
            item,
            nbt: None,
        }
    }
}

impl From<&str> for ItemStack {
    fn from(item: &str) -> ItemStack {
        ItemStack {
            count: 1,
            item: ITEMS.get_str(item).unwrap_or(items::AIR.clone()),
            nbt: None,
        }
    }
}

impl TryFrom<&Nbt> for ItemStack {
    type Error = Error;

    fn try_from(item: &Nbt) -> Result<ItemStack> {
        Ok(ItemStack {
            count: item
                .child("Count")
                .and_then(|count| count.unwrap_i8())
                .unwrap_or(1) as i32,
            item: ITEMS
                .get_str(
                    item.child("id")
                        .and_then(|id| id.unwrap_str())
                        .unwrap_or("minecraft:stone"),
                )
                .unwrap_or(items::STONE.clone()),
            nbt: item.child("tag").ok().cloned(),
        })
    }
}

impl ItemStack {
    pub fn new(item: Item, count: i32, nbt: Option<Nbt>) -> ItemStack {
        ItemStack { item, count, nbt }
    }

    pub fn is_empty(&self) -> bool {
        return self.count <= 0 || *self.item.registry_name == "minecraft:air";
    }

    pub fn empty() -> ItemStack {
        ItemStack {
            item: ITEMS.get_str("minecraft:air").unwrap(),
            count: 0,
            nbt: None,
        }
    }
}