Skip to main content

azalea_codec/
lib.rs

1#![doc = include_str!("../README.md")]
2//! ## Example
3//!
4//! ```rust
5#![doc = include_str!("../examples/showcase.rs")]
6//! ```
7
8// used for Codec::Incomplete
9#![feature(associated_type_defaults)]
10// needed for StringLiteral
11#![allow(incomplete_features)]
12#![feature(adt_const_params, unsized_const_params)]
13// thiserror
14#![feature(error_generic_member_access)]
15// specialized lists
16#![feature(min_specialization)]
17// ConstFromStr, used for compile-time validation of `#[codec(tag_as = ...)]` tags
18#![feature(const_trait_impl)]
19
20pub use azalea_codec_macros::Codec;
21
22use crate::{
23    error::{ReadError, ReadResult, WriteError, WriteResult},
24    number::Number,
25};
26
27pub mod error;
28mod integrations;
29pub mod number;
30pub mod rust;
31pub mod types;
32
33// for macros
34#[cfg(feature = "serde_json")]
35#[doc(hidden)]
36pub use serde;
37#[cfg(feature = "serde_json")]
38#[doc(hidden)]
39pub use serde_json;
40#[cfg(feature = "simd-json")]
41#[doc(hidden)]
42pub use simd_json;
43
44/// A data structure that can be written and read.
45///
46/// When possible, you should prefer to use the
47/// [`Codec`](azalea_codec_macros::Codec) derive macro.
48#[diagnostic::on_unimplemented(message = "type `{Self}` does not implement `azalea_codec::Codec`.")]
49pub trait Codec<O: Ops>: Sized {
50    type Incomplete = ReadResult<Self>;
51
52    /// Convert from a **data format** to a **data structure**.
53    fn codec_read(ops: &O) -> ReadResult<Self>;
54    // ^ this takes in a reference for user ergonomics and performance. many
55    // implementations will be calling read on the same object many times (to
56    // try different ways of deserializing it), and being required to clone the
57    // entire thing every time would be a shame.
58
59    /// Convert from a **data structure** to a **data format**.
60    fn codec_write(&self) -> WriteResult<O>;
61}
62/// Implement [`Codec`] for a type that's `Into<T>` and `From<T>` for another
63/// type that's already a `Codec`.
64///
65/// If the type is a map, consider also using [`impl_mapcodec_from`].
66///
67/// ```ignore
68/// azalea_codec::impl_codec_from!(GameProfile, SerializableGameProfile, struct IncompleteGameProfile);
69/// azalea_codec::impl_mapcodec_from!(GameProfile, SerializableGameProfile);
70/// ```
71#[macro_export]
72macro_rules! impl_codec_from {
73    ($(<$($generic:ident$(: $constraint:ident $(+ $constraint2:ident)*  )?),*>)? $this:ident $(<$($this_generic:ident),+>)?, $other:ty, struct $incomplete:ident) => {
74        impl<O: $crate::Ops $($(, $generic: $crate::Codec<O> $(+ $constraint $(+$constraint2)*)*)*)?> $crate::Codec<O> for $this $(<$($this_generic),*>)? {
75            type Incomplete = $incomplete<O $($(, $this_generic)*)?>;
76            fn codec_read(ops: &O) -> $crate::error::ReadResult<Self> {
77                <$other>::codec_read(ops).map(Into::into)
78            }
79            fn codec_write(&self) -> $crate::error::WriteResult<O> {
80                <$other>::from(self.clone()).codec_write()
81            }
82        }
83        #[doc(hidden)]
84        #[allow(nonstandard_style)]
85        pub struct $incomplete<O: $crate::Ops $($(, $generic: $crate::Codec<O> $(+ $constraint $(+$constraint2)*)*)*)?>(
86            pub <$other as $crate::Codec<O>>::Incomplete
87        );
88        impl<O: $crate::Ops $($(, $generic: $crate::Codec<O> $(+ $constraint $(+$constraint2)*)*)*)?> $crate::Incomplete for $incomplete<O $($(, $this_generic)*)?> {
89            type Complete = $this $(<$($this_generic),*>)?;
90            fn new(name: &'static str) -> Self {
91                Self(<_>::new(name))
92            }
93            fn build(self) -> $crate::error::ReadResult<Self::Complete> {
94                self.0.build().map(Into::into)
95            }
96        }
97
98        impl<O: $crate::Ops, $($($generic: Codec<O> $(+ $constraint $(+ $constraint2)*)?),*)?> $crate::NewOk<O> for $incomplete<O $($(, $this_generic)*)?>
99            where Self: $crate::Incomplete,
100            <$other as $crate::Codec<O>>::Incomplete: $crate::NewOk<O>,
101        {
102            fn new_ok() -> Self {
103                Self($crate::NewOk::new_ok())
104            }
105        }
106    };
107}
108/// See [`impl_codec_from`].
109#[macro_export]
110macro_rules! impl_mapcodec_from {
111    ($(<$($generic:ident$(: $constraint:ident $(+ $constraint2:ident)*  )?),*>)? $this:ident $(<$($this_generic:ident),+>)?, $other:ty) => {
112        impl<O: $crate::Ops $($(, $generic: $crate::Codec<O> $(+ $constraint $(+$constraint2)*)*)*)?> $crate::MapCodec<O> for $this $(<$($this_generic),*>)? {
113            fn codec_read_map_item(
114                incomplete: &mut <Self as $crate::Codec<O>>::Incomplete,
115
116                k: &O,
117                v: &O,
118            ) {
119                <$other>::codec_read_map_item(&mut incomplete.0, k, v);
120            }
121            fn codec_write_to_map(
122                &self,
123
124                map: &mut Vec<(O, O)>,
125            ) -> $crate::error::WriteResult<()> {
126                <$other>::from(self.clone()).codec_write_to_map( map)
127            }
128            fn get_and_reset_result(
129                incomplete: &mut <Self as $crate::Codec<O>>::Incomplete,
130            ) -> $crate::error::ReadResult<()> {
131                <$other>::get_and_reset_result(&mut incomplete.0)
132            }
133        }
134    };
135}
136
137#[macro_export]
138macro_rules! impl_mapcodec {
139    ($t:ty, $incomplete:ident $(<$($generic:ident$(: $constraint:ident $(+ $constraint2:ident)*  )?),*>)?, $k:ty : $v:ty) => {
140        pub struct $incomplete $(<$($generic),*>)? {
141            result: $crate::error::ReadResult<()>,
142            map: $t,
143        }
144        impl<O: Ops, $($($generic: Codec<O> + Clone $(+ $constraint $(+ $constraint2)*)?),*)?> $crate::MapCodec<O> for $t {
145            fn codec_read_map_item(incomplete: &mut <Self as Codec<O>>::Incomplete, k: &O, v: &O) {
146                let k = match <$k>::codec_read(k) {
147                    Ok(r) => r,
148                    Err(e) => {
149                        incomplete.result = Err(e);
150                        return;
151                    }
152                };
153                let v = match <$v>::codec_read(v) {
154                    Ok(r) => r,
155                    Err(e) => {
156                        incomplete.result = Err(e);
157                        return;
158                    }
159                };
160                incomplete.map.insert(k, v);
161            }
162            fn codec_write_to_map(
163                &self,
164
165                map: &mut Vec<(O, O)>,
166            ) -> $crate::error::WriteResult<()> {
167                for (k, v) in self.iter() {
168                    map.push((k.to_owned().codec_write()?, v.codec_write()?))
169                }
170                Ok(())
171            }
172            fn get_and_reset_result(
173                incomplete: &mut <Self as Codec<O>>::Incomplete,
174            ) -> $crate::error::ReadResult<()> {
175                let mut result = Ok(());
176                ::std::mem::swap(&mut incomplete.result, &mut result);
177                result
178            }
179        }
180        impl<$($($generic $(: $constraint $(+ $constraint2)*)?),*)?> Incomplete for $incomplete $(<$($generic),*>)? {
181            type Complete = $t;
182            fn new(name: &'static str) -> Self {
183                Self {
184                    result: Err(ReadError::missing_key(name)),
185                    map: Default::default(),
186                }
187            }
188            fn build(self) -> ReadResult<Self::Complete> {
189                self.result.map(|_| self.map)
190            }
191        }
192        impl<O: Ops, $($($generic: Codec<O> $(+ $constraint $(+ $constraint2)*)?),*)?> NewOk<O> for $incomplete $(<$($generic),*>)?
193            where Self: Incomplete
194        {
195            fn new_ok() -> Self {
196                Self {
197                    result: Ok(()),
198                    map: Default::default(),
199                }
200            }
201        }
202    };
203}
204
205#[doc(hidden)]
206#[macro_export]
207macro_rules! internal_impl_serde_with {
208    ($t:ident, $value_ty:ty) => {
209        impl $crate::serde::Serialize for $t {
210            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
211            where
212                S: $crate::serde::Serializer,
213            {
214                let json: $value_ty = self
215                    .codec_write()
216                    .map_err($crate::serde::ser::Error::custom)?;
217                json.serialize(serializer)
218            }
219        }
220        impl<'de> $crate::serde::Deserialize<'de> for $t {
221            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
222            where
223                D: $crate::serde::Deserializer<'de>,
224            {
225                let json = <$value_ty>::deserialize(deserializer)?;
226                Self::codec_read(&json).map_err($crate::serde::de::Error::custom)
227            }
228        }
229    };
230}
231
232#[cfg(all(feature = "serde_json", not(feature = "simd-json")))]
233#[macro_export]
234macro_rules! impl_serde {
235    ($t:ident) => {
236        azalea_codec::internal_impl_serde_with!($t, $crate::serde_json::Value);
237    };
238}
239#[cfg(feature = "simd-json")]
240#[macro_export]
241macro_rules! impl_serde {
242    ($t:ident) => {
243        azalea_codec::internal_impl_serde_with!($t, $crate::simd_json::owned::Value);
244    };
245}
246
247#[diagnostic::on_unimplemented(message = "type `{Self}` is not a map that can be flattened.")]
248pub trait MapCodec<O: Ops>: Sized + Codec<O> {
249    // this doesn't return a ReadResult because the errors are stored in the
250    // Incomplete struct
251    fn codec_read_map_item(incomplete: &mut <Self as Codec<O>>::Incomplete, k: &O, v: &O);
252    fn codec_write_to_map(&self, map: &mut Vec<(O, O)>) -> WriteResult<()>;
253
254    /// For normal structs, this sets `incomplete.__result = Ok(())` and returns
255    /// the previous value of `__result`.
256    fn get_and_reset_result(incomplete: &mut <Self as Codec<O>>::Incomplete) -> ReadResult<()>;
257}
258
259/// A data serialization format.
260#[diagnostic::on_unimplemented(
261    message = "type `{Self}` is not a data format; did you mean to use `{Self}::codec_read` instead?"
262)]
263#[allow(unused_variables)]
264pub trait Ops: Sized + Clone + Codec<Self> + 'static {
265    // https://github.com/Mojang/DataFixerUpper/blob/master/src/main/java/com/mojang/serialization/DynamicOps.java
266
267    type List: IntoIterator<Item = Self>;
268    type Map: MapLike<Self>;
269
270    fn empty() -> WriteResult<Self> {
271        Self::empty_map()
272    }
273    fn empty_map() -> WriteResult<Self> {
274        Self::create_map(&[])
275    }
276    fn empty_list() -> WriteResult<Self> {
277        Self::create_list(&[])
278    }
279
280    fn get_number(&self) -> ReadResult<Number> {
281        Err(ReadError::unimplemented())
282    }
283    fn create_number(n: Number) -> WriteResult<Self> {
284        Err(WriteError::unimplemented())
285    }
286
287    fn get_boolean(&self) -> ReadResult<bool> {
288        Err(ReadError::unimplemented())
289    }
290    fn create_boolean(v: bool) -> WriteResult<Self> {
291        Err(WriteError::unimplemented())
292    }
293
294    fn get_list(&self) -> ReadResult<Self::List> {
295        Err(ReadError::unimplemented())
296    }
297    fn create_list(list: &[Self]) -> WriteResult<Self> {
298        Err(WriteError::unimplemented())
299    }
300
301    fn get_map(&self) -> ReadResult<Self::Map> {
302        Err(ReadError::unimplemented())
303    }
304    fn create_map(map: &[(Self, Self)]) -> WriteResult<Self> {
305        Err(WriteError::unimplemented())
306    }
307
308    fn get_string(&self) -> ReadResult<String> {
309        Err(ReadError::unimplemented())
310    }
311    fn create_string(v: &str) -> WriteResult<Self> {
312        Err(WriteError::unimplemented())
313    }
314
315    fn get_byte_buffer(&self) -> ReadResult<Box<[u8]>> {
316        fallback_get_list(self)
317    }
318    fn create_byte_list(v: &[u8]) -> WriteResult<Self> {
319        fallback_create_list(v)
320    }
321
322    fn get_int_list(&self) -> ReadResult<Box<[i32]>> {
323        fallback_get_list(self)
324    }
325    fn create_int_list(v: &[i32]) -> WriteResult<Self> {
326        fallback_create_list(v)
327    }
328
329    fn get_long_list(&self) -> ReadResult<Box<[i64]>> {
330        fallback_get_list(self)
331    }
332    fn create_long_list(v: &[i64]) -> WriteResult<Self> {
333        fallback_create_list(v)
334    }
335}
336
337fn fallback_get_list<O: Ops, N: TryFrom<Number, Error = ReadError>>(o: &O) -> ReadResult<Box<[N]>> {
338    o.get_list()?
339        .into_iter()
340        .map(|o| o.get_number().and_then(|n| n.try_into()))
341        .collect()
342}
343fn fallback_create_list<O: Ops, N: Into<Number> + Copy>(v: &[N]) -> WriteResult<O> {
344    O::create_list(
345        &v.iter()
346            .map(|&i| O::create_number(i.into()))
347            .collect::<WriteResult<Box<[O]>>>()?,
348    )
349}
350
351pub trait MapLike<T: Clone>: Sized {
352    fn for_each(&self, cb: impl FnMut(&T, &T));
353
354    fn to_values(&self) -> Box<[(T, T)]> {
355        let mut values: Vec<(T, T)> = Vec::new();
356        self.for_each(|k, v| {
357            values.push((k.clone(), v.clone()));
358        });
359        values.into_boxed_slice()
360    }
361}
362
363pub trait Incomplete: Sized {
364    type Complete;
365
366    fn new(name: &'static str) -> Self;
367    fn new_unnamed() -> Self {
368        Self::new("")
369    }
370
371    fn build(self) -> ReadResult<Self::Complete>;
372}
373impl<T> Incomplete for ReadResult<T> {
374    type Complete = T;
375
376    fn new(name: &'static str) -> Self {
377        Err(ReadError::missing_key(name))
378    }
379    fn build(self) -> ReadResult<T> {
380        self
381    }
382}
383
384pub trait NewOk<T>: Incomplete {
385    fn new_ok() -> Self;
386}
387impl<T: Default> NewOk<T> for ReadResult<T> {
388    fn new_ok() -> ReadResult<T> {
389        Ok(T::default())
390    }
391}
392
393/// A trait that represents a subset of types with `Default`.
394///
395/// This is required for a `#[codec(optional)]` to work on a type. Also see
396/// [`impl_defaultable`].
397#[diagnostic::on_unimplemented(
398    message = "type `{Self}` does not support `#[codec(optional)]`.",
399    note = "consider using `azalea_codec::impl_defaultable!({Self})`."
400)]
401pub trait Defaultable<O: Ops>: Codec<O> {
402    fn is_default(&self) -> bool;
403}
404/// Automatically implements [`Defaultable`] on the given type, allowing it to
405/// be supported by `#[codec(optional)]` fields.
406#[macro_export]
407macro_rules! impl_defaultable {
408    (<$($generic_name:ident$(: $generic_constraint:path)?)*> for $t:ty, $self:ident, $($check:tt)*) => {
409        impl<O: $crate::Ops, $($generic_name$(: $generic_constraint)?)*> $crate::Defaultable<O> for $t {
410            fn is_default(&$self) -> bool {
411                $($check)*
412            }
413        }
414    };
415
416    ($t:ty) => {
417        $crate::impl_defaultable!($t, self, self == &Self::default());
418    };
419    ($t:ty, $self:ident, $($check:tt)*) => {
420        impl<O: $crate::Ops> $crate::Defaultable<O> for $t {
421            fn is_default(&$self) -> bool {
422                $($check)*
423            }
424        }
425    };
426}
427
428pub trait ResolvableItem<O: Ops> {
429    fn name(&self) -> &'static str;
430    fn to_resolvable_id(&self) -> u32;
431}
432pub trait IntoResolvableItem<O: Ops>: ResolvableItem<O> + 'static {
433    type Resolvable: Codec<O> + ResolvableItem<O>;
434    fn codec_read_resolvable_item(ops: &O) -> ReadResult<Self::Resolvable>;
435    fn from_resolvable_id(id: u32) -> Self;
436}
437
438// this trait exists because often Rust won't let us impl `From<T> + Into<T>`
439// for certain wrapper types.
440pub trait Interchangeable<T> {
441    fn interchangeable_into(self) -> T;
442    fn interchangeable_from(other: T) -> Self;
443}
444impl<A, B> Interchangeable<A> for B
445where
446    A: From<B>,
447    B: From<A>,
448{
449    fn interchangeable_into(self) -> A {
450        self.into()
451    }
452    fn interchangeable_from(other: A) -> Self {
453        other.into()
454    }
455}