azalea_registry/
data_registry.rs1use std::io;
2
3use azalea_buf::BufReadError;
4use simdnbt::owned::NbtCompound;
5
6use crate::{
7 Registry,
8 data::{self},
9 registry_holder::{RegistryDeserializesTo, RegistryHolder},
10};
11
12pub(crate) fn protocol_id_to_registry<R: Registry>(
13 ctx: azalea_buf::Ctx,
14 id: u32,
15) -> Result<R, BufReadError> {
16 let registry_holder = <&RegistryHolder>::from(ctx);
17 let ident = registry_holder
18 .protocol_id_to_identifier(R::NAME.into(), id)
19 .ok_or_else(|| {
20 BufReadError::custom(format!(
21 "got a resolvable {} with id {id}, which isn't in our registry",
22 R::NAME
23 ))
24 })?;
25 let ident = ident.clone();
26 R::try_from(ident).map_err(|_| panic!("identifier returned by `protocol_id_to_identifier` should always be valid for this registry"))
27}
28pub(crate) fn registry_to_protocol_id<R: Registry>(
29 registry: &R,
30 ctx: azalea_buf::Ctx,
31) -> io::Result<u32> {
32 let registry_holder = <&RegistryHolder>::from(ctx);
33 let ident = registry.clone().into();
34 let id = registry_holder
35 .identifier_to_protocol_id(R::NAME, ident.clone())
36 .ok_or_else(|| {
37 io::Error::other(format!(
38 "got a resolvable {} with value {ident}, which isn't in our registry",
39 R::NAME
40 ))
41 })?;
42 Ok(id)
43}
44
45pub trait DeserializableDataRegistry: Registry {
46 type DeserializesTo: RegistryDeserializesTo;
47
48 fn resolve<'a>(&self, registries: &'a RegistryHolder) -> Option<&'a Self::DeserializesTo> {
49 let protocol_id = registry_to_protocol_id(self, azalea_buf::Ctx::new(registries)).ok()?;
50 Self::DeserializesTo::get_for_registry(registries, Self::NAME, protocol_id)
51 }
52}
53
54macro_rules! define_deserializes_to {
55 ($($t:ty => $deserializes_to:ty),* $(,)?) => {
56 $(
57 impl DeserializableDataRegistry for $t {
58 type DeserializesTo = $deserializes_to;
59 }
60 )*
61 };
62}
63macro_rules! define_default_deserializes_to {
64 ($($t:ty),* $(,)?) => {
65 $(
66 impl DeserializableDataRegistry for $t {
67 type DeserializesTo = NbtCompound;
68 }
69 )*
70 };
71}
72
73define_deserializes_to! {
74 data::DimensionKind => crate::registry_holder::dimension_type::DimensionKindElement,
75 data::Enchantment => crate::registry_holder::enchantment::EnchantmentData,
76}
77
78define_default_deserializes_to! {
79 data::DamageKind,
80 data::Dialog,
81 data::WolfSoundVariant,
82 data::CowVariant,
83 data::ChickenVariant,
84 data::FrogVariant,
85 data::CatVariant,
86 data::PigVariant,
87 data::PaintingVariant,
88 data::WolfVariant,
89 data::Biome,
90}