Skip to main content

azalea_registry/
lib.rs

1#![doc = include_str!("../README.md")]
2// used by default_for_item in components
3#![feature(min_specialization)]
4// used by the `registry!` macro
5#![feature(const_trait_impl, const_cmp)]
6
7pub use azalea_registry_builtin::*;
8pub mod data;
9pub mod data_registry;
10pub mod item;
11pub mod registry_holder;
12pub mod tags;
13
14use std::{
15    fmt::{self, Debug},
16    hash::Hash,
17    io::{self, Cursor, Write},
18};
19
20use azalea_buf::{AzBuf, AzBufVar, BufReadError, BufReadErrorRepr};
21use azalea_codec::Codec;
22use azalea_core::identifier::Identifier;
23pub use azalea_registry_macros as macros;
24
25pub trait Registry: AzBuf + Ord + Clone + Hash + Into<Identifier> + TryFrom<Identifier>
26where
27    Self: Sized,
28{
29    const NAME: &'static str;
30
31    fn from_id(ctx: azalea_buf::Ctx, id: u32) -> Result<Self, BufReadError>;
32    fn to_id(&self, ctx: azalea_buf::Ctx) -> io::Result<u32>;
33}
34
35impl<T: BuiltinRegistry> Registry for T {
36    const NAME: &'static str = T::NAME;
37    fn from_id(_ctx: azalea_buf::Ctx, id: u32) -> Result<Self, BufReadError> {
38        T::builtin_from_id(id)
39            .ok_or_else(|| BufReadErrorRepr::UnexpectedEnumVariant { id: id as i32 }.into())
40    }
41    fn to_id(&self, _ctx: azalea_buf::Ctx) -> io::Result<u32> {
42        Ok(self.builtin_into_id())
43    }
44}
45
46/// A registry that might not be present.
47///
48/// This is transmitted as a single varint in the protocol.
49#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
50pub struct OptionalRegistry<T: Registry>(pub Option<T>);
51
52impl<T: Registry> AzBuf for OptionalRegistry<T> {
53    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
54        Ok(OptionalRegistry(match u32::azalea_read_var(ctx, buf)? {
55            0 => None,
56            value => Some(T::from_id(ctx, value - 1)?),
57        }))
58    }
59    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
60        match &self.0 {
61            None => 0u32.azalea_write_var(ctx, buf),
62            Some(value) => (value.to_id(ctx)? + 1).azalea_write_var(ctx, buf),
63        }
64    }
65}
66
67/// A registry that will either take an ID or a resource location.
68#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
69pub enum CustomRegistry<D: Registry, C: AzBuf> {
70    Direct(D),
71    Custom(C),
72}
73
74impl<D: Registry, C: AzBuf> AzBuf for CustomRegistry<D, C> {
75    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
76        let direct_registry = OptionalRegistry::<D>::azalea_read(ctx, buf)?;
77        if let Some(direct_registry) = direct_registry.0 {
78            return Ok(CustomRegistry::Direct(direct_registry));
79        }
80        Ok(CustomRegistry::Custom(C::azalea_read(ctx, buf)?))
81    }
82    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
83        match self {
84            CustomRegistry::Direct(direct_registry) => {
85                // write the id + 1
86                (direct_registry.to_id(ctx)? + 1).azalea_write_var(ctx, buf)
87            }
88            CustomRegistry::Custom(custom_registry) => {
89                // write 0, then the custom registry
90                0u32.azalea_write_var(ctx, buf)?;
91                custom_registry.azalea_write(ctx, buf)
92            }
93        }
94    }
95}
96
97#[derive(Clone, PartialEq)]
98pub enum HolderSet<D> {
99    Direct {
100        contents: Vec<D>,
101    },
102    Named {
103        key: Identifier,
104        contents: Vec<Identifier>,
105    },
106}
107impl<D: AzBuf> AzBuf for HolderSet<D> {
108    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
109        let size = i32::azalea_read_var(ctx, buf)?.wrapping_sub(1);
110        if size == -1 {
111            let key = Identifier::azalea_read(ctx, buf)?;
112            Ok(Self::Named {
113                key,
114                contents: Vec::new(),
115            })
116        } else {
117            let mut contents = Vec::new();
118            for _ in 0..size {
119                contents.push(D::azalea_read(ctx, buf)?);
120            }
121            Ok(Self::Direct { contents })
122        }
123    }
124    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
125        match self {
126            Self::Direct { contents } => {
127                (contents.len() as i32 + 1).azalea_write_var(ctx, buf)?;
128                for item in contents {
129                    item.azalea_write(ctx, buf)?;
130                }
131            }
132            Self::Named { key, contents: _ } => {
133                0i32.azalea_write_var(ctx, buf)?;
134                key.azalea_write(ctx, buf)?;
135            }
136        }
137        Ok(())
138    }
139}
140impl<D: Debug> Debug for HolderSet<D> {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            Self::Direct { contents } => f.debug_list().entries(contents).finish(),
144            Self::Named { key, contents } => f
145                .debug_struct("Named")
146                .field("key", key)
147                .field("contents", contents)
148                .finish(),
149        }
150    }
151}
152impl<D> From<Vec<D>> for HolderSet<D> {
153    fn from(contents: Vec<D>) -> Self {
154        Self::Direct { contents }
155    }
156}
157impl<D: Codec<O>, O: azalea_codec::Ops> Codec<O> for HolderSet<D> {
158    fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
159        if let Ok(key) = Identifier::codec_read(ops) {
160            return Ok(Self::Named {
161                key,
162                contents: vec![],
163            });
164        }
165        if let Ok(d) = D::codec_read(ops) {
166            return Ok(Self::Direct { contents: vec![d] });
167        }
168        if let Ok(contents) = Vec::<D>::codec_read(ops) {
169            return Ok(Self::Direct { contents });
170        }
171
172        Err(azalea_codec::error::ReadError::custom("invalid holderset"))
173    }
174    fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
175        match self {
176            Self::Direct { contents } => {
177                if contents.len() == 1 {
178                    contents[0].codec_write()
179                } else {
180                    contents.codec_write()
181                }
182            }
183            Self::Named { key, contents: _ } => key.codec_write(),
184        }
185    }
186}
187
188impl<D: Registry> Default for HolderSet<D> {
189    fn default() -> Self {
190        Self::Direct {
191            contents: Vec::new(),
192        }
193    }
194}
195
196impl<O: azalea_codec::Ops, D: Registry + Codec<O>> azalea_codec::Defaultable<O> for HolderSet<D> {
197    fn is_default(&self) -> bool {
198        match self {
199            Self::Direct { contents } => contents.is_empty(),
200            _ => false,
201        }
202    }
203}
204
205impl<D: Registry> HolderSet<D>
206where
207    Identifier: From<D>,
208{
209    pub fn contains(&self, value: D) -> bool {
210        match self {
211            HolderSet::Direct { contents } => contents.contains(&value),
212            HolderSet::Named { key: _, contents } => contents.contains(&Identifier::from(value)),
213        }
214    }
215}
216
217/// A reference to either a registry or a custom value (usually something with
218/// an `Identifier`).
219#[derive(Codec)]
220pub enum Holder<R: Registry, Direct: AzBuf> {
221    Reference(R),
222    Direct(Direct),
223}
224impl<R: Registry, Direct: AzBuf> AzBuf for Holder<R, Direct> {
225    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
226        let id = u32::azalea_read_var(ctx, buf)?;
227        if id == 0 {
228            Ok(Self::Direct(Direct::azalea_read(ctx, buf)?))
229        } else {
230            let id = id - 1;
231            let value = Registry::from_id(ctx, id)?;
232            Ok(Self::Reference(value))
233        }
234    }
235    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
236        match self {
237            Self::Reference(value) => (value.to_id(ctx)? + 1).azalea_write_var(ctx, buf),
238            Self::Direct(value) => {
239                0u32.azalea_write_var(ctx, buf)?;
240                value.azalea_write(ctx, buf)
241            }
242        }
243    }
244}
245impl<R: Registry + Debug, Direct: AzBuf + Debug> Debug for Holder<R, Direct> {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        match self {
248            Self::Reference(value) => f.debug_tuple("Reference").field(value).finish(),
249            Self::Direct(value) => f.debug_tuple("Direct").field(value).finish(),
250        }
251    }
252}
253impl<R: Registry + Clone, Direct: AzBuf + Clone> Clone for Holder<R, Direct> {
254    fn clone(&self) -> Self {
255        match self {
256            Self::Reference(value) => Self::Reference(value.clone()),
257            Self::Direct(value) => Self::Direct(value.clone()),
258        }
259    }
260}
261impl<R: Registry + PartialEq, Direct: AzBuf + PartialEq> PartialEq for Holder<R, Direct> {
262    fn eq(&self, other: &Self) -> bool {
263        match (self, other) {
264            (Self::Reference(a), Self::Reference(b)) => a == b,
265            (Self::Direct(a), Self::Direct(b)) => a == b,
266            _ => false,
267        }
268    }
269}
270impl<R: Registry + Default, Direct: AzBuf> Default for Holder<R, Direct> {
271    fn default() -> Self {
272        Self::Reference(R::default())
273    }
274}