Skip to main content

azalea_registry/item/components/
patch.rs

1use std::{
2    fmt::Debug,
3    io::{self, Cursor, Write},
4    sync::LazyLock,
5};
6
7use azalea_buf::{AzBuf, AzBufVar, BufReadError};
8use azalea_codec::{Codec, MapLike};
9use azalea_core::identifier::Identifier;
10use indexmap::IndexMap;
11
12use crate::{
13    builtin::DataComponentKind,
14    item::components::{self, DataComponent},
15};
16
17/// An update to an item's data components.
18///
19/// Note that in vanilla items come with their own set of default components,
20/// and Azalea does not implement that yet.
21#[derive(Default, Clone, Debug, PartialEq)]
22pub struct DataComponentPatch(Box<IndexMap<DataComponentKind, Option<DataComponent>>>);
23
24pub static EMPTY_DATA_COMPONENT_PATCH: LazyLock<DataComponentPatch> =
25    LazyLock::new(DataComponentPatch::default);
26
27impl DataComponentPatch {
28    pub fn new() -> Self {
29        Self::default()
30    }
31    pub fn is_empty(&self) -> bool {
32        self.0.is_empty()
33    }
34
35    /// Returns the value of the component in the generic argument for this
36    /// item.
37    ///
38    /// ```
39    /// # use azalea_registry::{
40    /// #     builtin::ItemKind,
41    /// #     item::{ItemStackData, components, components::patch::DataComponentPatch},
42    /// # };
43    /// # fn example(item: &ItemStackData) -> Option<()> {
44    /// let item_nutrition = item.component_patch.get::<components::Food>()?.nutrition;
45    /// # Some(())
46    /// # }
47    /// ```
48    pub fn get<T: components::DataComponentTrait>(&self) -> Option<&T> {
49        let component = self.get_kind(T::KIND)?;
50        Some(T::try_from_data_component(component).expect("mismatching component kind"))
51    }
52
53    pub fn get_kind(&self, kind: DataComponentKind) -> Option<&DataComponent> {
54        if let Some(Some(r)) = self.0.get(&kind) {
55            assert_eq!(r.kind(), kind);
56            Some(r)
57        } else {
58            None
59        }
60    }
61    /// Returns whether the component in the generic argument is present for
62    /// this item.
63    ///
64    /// ```
65    /// # use azalea_registry::{
66    /// #     builtin::ItemKind,
67    /// #     item::{ItemStackData, components, components::patch::DataComponentPatch},
68    /// # };
69    /// # let item = ItemStackData::from(ItemKind::Stone);
70    /// let is_edible = item.component_patch.has::<components::Food>();
71    /// # assert!(!is_edible);
72    /// ```
73    pub fn has<T: components::DataComponentTrait>(&self) -> bool {
74        self.has_kind(T::KIND)
75    }
76
77    pub fn has_kind(&self, kind: DataComponentKind) -> bool {
78        self.get_kind(kind).is_some()
79    }
80
81    pub fn iter<'a>(
82        &'a self,
83    ) -> impl Iterator<Item = (&'a DataComponentKind, &'a Option<DataComponent>)> + 'a {
84        self.0.iter()
85    }
86    /// Insert a new component into this patch, or mark a component as removed.
87    ///
88    /// # Panics
89    ///
90    /// The [`DataComponent`] must be of the correct kind.
91    pub fn insert_component(&mut self, kind: DataComponentKind, value: Option<DataComponent>) {
92        if let Some(value) = &value {
93            assert_eq!(kind, value.kind());
94        }
95        self.0.insert(kind, value);
96    }
97}
98
99impl AzBuf for DataComponentPatch {
100    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
101        let components_with_data_count = u32::azalea_read_var(ctx, buf)?;
102        let components_without_data_count = u32::azalea_read_var(ctx, buf)?;
103
104        if components_without_data_count == 0 && components_with_data_count == 0 {
105            return Ok(DataComponentPatch::default());
106        }
107
108        let mut components = DataComponentPatch::new();
109        for _ in 0..components_with_data_count {
110            let component_kind = DataComponentKind::azalea_read(ctx, buf)?;
111            let component_data = DataComponent::azalea_read_as(component_kind, ctx, buf)?;
112            components.insert_component(component_kind, Some(component_data));
113        }
114
115        for _ in 0..components_without_data_count {
116            let component_kind = DataComponentKind::azalea_read(ctx, buf)?;
117            components.insert_component(component_kind, None);
118        }
119
120        Ok(components)
121    }
122    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
123        let mut components_with_data_count: u32 = 0;
124        let mut components_without_data_count: u32 = 0;
125        for component in self.0.values() {
126            if component.is_some() {
127                components_with_data_count += 1;
128            } else {
129                components_without_data_count += 1;
130            }
131        }
132
133        components_with_data_count.azalea_write_var(ctx, buf)?;
134        components_without_data_count.azalea_write_var(ctx, buf)?;
135
136        let mut component_buf = Vec::new();
137        for (&kind, component) in self.0.iter() {
138            if let Some(component) = component {
139                kind.azalea_write(ctx, buf)?;
140
141                component_buf.clear();
142                assert_eq!(component.kind(), kind);
143                component.azalea_write_value(ctx, &mut component_buf)?;
144                buf.write_all(&component_buf)?;
145            }
146        }
147
148        for (kind, component) in self.0.iter() {
149            if component.is_none() {
150                kind.azalea_write(ctx, buf)?;
151            }
152        }
153
154        Ok(())
155    }
156}
157
158impl<O: azalea_codec::Ops> Codec<O> for DataComponentPatch {
159    fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
160        let map = ops.get_map()?;
161        let mut patch = DataComponentPatch::new();
162
163        for (kind, value) in map.to_values() {
164            let kind = InvertableDataComponentKind::codec_read(&kind)?;
165            match kind {
166                InvertableDataComponentKind::Present(kind) => {
167                    let value = DataComponent::codec_read_as(kind, &value)
168                        .map_err(|e| e.while_reading_key(kind.to_str()))?;
169                    patch.insert_component(kind, Some(value));
170                }
171                InvertableDataComponentKind::Removed(kind) => patch.insert_component(kind, None),
172            }
173        }
174
175        Ok(patch)
176    }
177    fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
178        let mut entries = Vec::<(O, O)>::with_capacity(self.0.len());
179        for (&kind, component) in self.0.iter() {
180            if let Some(component) = component {
181                assert_eq!(component.kind(), kind);
182                let k = InvertableDataComponentKind::Present(kind).codec_write()?;
183                let v = component.codec_write_value::<O>()?;
184                entries.push((k, v));
185            } else {
186                let k = InvertableDataComponentKind::Removed(kind).codec_write()?;
187                let v = ().codec_write()?;
188                entries.push((k, v))
189            }
190        }
191        O::create_map(&entries)
192    }
193}
194azalea_codec::impl_defaultable!(DataComponentPatch, self, self.0.is_empty());
195
196enum InvertableDataComponentKind {
197    Present(DataComponentKind),
198    Removed(DataComponentKind),
199}
200impl<O: azalea_codec::Ops> Codec<O> for InvertableDataComponentKind {
201    fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
202        let ident = Identifier::codec_read(ops)?;
203        if ident.namespace().starts_with('!') {
204            let ident = Identifier::new(&ident.to_string()[1..]);
205            DataComponentKind::try_from(&ident)
206                .map_err(|_| azalea_codec::error::ReadError::custom("not a DataComponentKind"))
207                .map(Self::Removed)
208        } else {
209            DataComponentKind::codec_read(ops).map(Self::Present)
210        }
211    }
212    fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
213        match self {
214            InvertableDataComponentKind::Present(k) => k.codec_write(),
215            InvertableDataComponentKind::Removed(k) => format!("!{k}").codec_write(),
216        }
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use azalea_registry_builtin::builtin::ItemKind;
223
224    use crate::item::{ItemStack, components::MapId};
225
226    #[test]
227    fn test_get_component() {
228        let item = ItemStack::from(ItemKind::Map).with_component(MapId { id: 1 });
229        let map_id = item.get_component::<MapId>().unwrap();
230        assert_eq!(map_id.id, 1);
231    }
232}