azalea_core/
codec_utils.rs

1//! Some functions that are useful to have when implementing
2//! `Serialize`/`Deserialize`, which Azalea uses to imitate Minecraft codecs.
3
4use azalea_buf::SerializableUuid;
5use serde::{Serialize, Serializer, ser::SerializeTupleStruct};
6use uuid::Uuid;
7
8/// Intended to be used for skipping serialization if the value is the default.
9///
10/// ```no_run
11/// #[serde(skip_serializing_if = "is_default")]
12/// ```
13pub fn is_default<T: Default + PartialEq>(t: &T) -> bool {
14    *t == Default::default()
15}
16
17/// Intended to be used for skipping serialization if the value is `true`.
18///
19/// ```no_run
20/// #[serde(skip_serializing_if = "is_true")]
21/// ```
22pub fn is_true(t: &bool) -> bool {
23    *t
24}
25
26/// If the array has a single item, don't serialize as an array
27///
28/// ```no_run
29/// #[serde(serialize_with = "flatten_array")]
30/// ```
31pub fn flatten_array<S: Serializer, T: Serialize>(x: &Vec<T>, s: S) -> Result<S::Ok, S::Error> {
32    if x.len() == 1 {
33        x[0].serialize(s)
34    } else {
35        x.serialize(s)
36    }
37}
38
39/// Minecraft writes UUIDs as an IntArray<4>
40pub fn uuid<'a, S: Serializer>(
41    uuid: impl Into<&'a Option<Uuid>>,
42    serializer: S,
43) -> Result<S::Ok, S::Error> {
44    if let Some(uuid) = uuid.into() {
45        let arr: [u32; 4] = uuid.to_int_array();
46        let arr: [i32; 4] = [arr[0] as i32, arr[1] as i32, arr[2] as i32, arr[3] as i32];
47        IntArray(arr).serialize(serializer)
48    } else {
49        serializer.serialize_unit()
50    }
51}
52
53/// An internal type that makes the i32 array be serialized differently.
54///
55/// Azalea currently only uses this when writing checksums, but Minecraft also
56/// uses this internally when converting types to NBT.
57pub struct IntArray<const N: usize>(pub [i32; N]);
58/// An internal type that makes the i64 array be serialized differently.
59///
60/// Azalea currently only uses this when writing checksums, but Minecraft also
61/// uses this internally when converting types to NBT.
62pub struct LongArray<const N: usize>(pub [i64; N]);
63
64impl<const N: usize> Serialize for IntArray<N> {
65    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
66        // see checksum::serialize_tuple_struct
67        let mut seq = serializer.serialize_tuple_struct("azalea:int_array", N)?;
68        for &item in &self.0 {
69            seq.serialize_field(&item)?;
70        }
71        seq.end()
72    }
73}
74impl<const N: usize> Serialize for LongArray<N> {
75    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
76        // see checksum::serialize_tuple_struct
77        let mut seq = serializer.serialize_tuple_struct("azalea:long_array", N)?;
78        for &item in &self.0 {
79            seq.serialize_field(&item)?;
80        }
81        seq.end()
82    }
83}