Skip to main content

azalea_codec/integrations/
simdnbt.rs

1use simdnbt::{
2    Mutf8String,
3    owned::{NbtCompound, NbtList, NbtTag},
4};
5
6use crate::{
7    Codec, Incomplete, MapLike, NewOk, Number, Ops,
8    error::{ReadError, ReadResult, WriteError, WriteResult},
9    impl_mapcodec,
10};
11
12// NbtOps.java
13impl Ops for NbtTag {
14    type Map = NbtCompound;
15    type List = std::vec::IntoIter<NbtTag>;
16
17    fn get_number(&self) -> ReadResult<Number> {
18        Ok(match *self {
19            NbtTag::Byte(v) => Number::Byte(v),
20            NbtTag::Short(v) => Number::Short(v),
21            NbtTag::Int(v) => Number::Int(v),
22            NbtTag::Long(v) => Number::Long(v),
23            NbtTag::Float(v) => Number::Float(v),
24            NbtTag::Double(v) => Number::Double(v),
25            _ => return Err(ReadError::custom("not a number")),
26        })
27    }
28    fn create_number(n: Number) -> WriteResult<Self> {
29        Ok(n.into())
30    }
31
32    fn get_boolean(&self) -> ReadResult<bool> {
33        Ok(f64::from(self.get_number()?) != 0.0)
34    }
35    fn create_boolean(v: bool) -> WriteResult<Self> {
36        Ok(NbtTag::Byte(v as i8))
37    }
38
39    fn get_list(&self) -> ReadResult<<NbtTag as Ops>::List> {
40        let items: Vec<NbtTag> = match self {
41            NbtTag::ByteArray(items) => items.iter().map(|&i| NbtTag::Byte(i as i8)).collect(),
42            NbtTag::List(list) => list_as_tags(list),
43            NbtTag::IntArray(items) => items.iter().map(|&i| NbtTag::Int(i)).collect(),
44            NbtTag::LongArray(items) => items.iter().map(|&i| NbtTag::Long(i)).collect(),
45            _ => return Err(ReadError::custom("not a list")),
46        };
47        Ok(items.into_iter())
48    }
49    fn create_list(list: &[Self]) -> WriteResult<Self> {
50        // this does the homogenizing for us
51        Ok(NbtTag::List(NbtList::from(list.to_owned())))
52    }
53    fn get_map(&self) -> ReadResult<NbtCompound> {
54        self.compound()
55            .cloned()
56            .ok_or_else(|| ReadError::custom("not a map"))
57    }
58    fn create_map(map: &[(Self, Self)]) -> WriteResult<Self> {
59        let mut items = Vec::with_capacity(map.len());
60        for (k, v) in map {
61            let Some(k) = k.string() else {
62                return Err(WriteError::custom(
63                    "cannot create a map with non-string keys",
64                ));
65            };
66
67            items.push((k.to_owned(), v.to_owned()));
68        }
69
70        Ok(NbtTag::Compound(NbtCompound::from_values(items)))
71    }
72    fn get_string(&self) -> ReadResult<String> {
73        if let Some(s) = self.string() {
74            Ok(s.to_string())
75        } else {
76            Err(ReadError::custom("not a string"))
77        }
78    }
79    fn create_string(v: &str) -> WriteResult<Self> {
80        Ok(NbtTag::String(v.into()))
81    }
82    fn get_byte_buffer(&self) -> ReadResult<Box<[u8]>> {
83        self.get_list()?
84            .map(|o| o.get_number().and_then(|n| n.try_into()))
85            .collect()
86    }
87    fn create_byte_list(v: &[u8]) -> WriteResult<Self> {
88        Ok(NbtTag::ByteArray(v.to_owned()))
89    }
90    fn get_int_list(&self) -> ReadResult<Box<[i32]>> {
91        self.get_list()?
92            .map(|o| o.get_number().and_then(|n| n.try_into()))
93            .collect()
94    }
95    fn create_int_list(v: &[i32]) -> WriteResult<Self> {
96        Ok(NbtTag::IntArray(v.to_owned()))
97    }
98    fn get_long_list(&self) -> ReadResult<Box<[i64]>> {
99        self.get_list()?
100            .map(|o| o.get_number().and_then(|n| n.try_into()))
101            .collect()
102    }
103
104    fn create_long_list(v: &[i64]) -> WriteResult<Self> {
105        Ok(NbtTag::LongArray(v.to_owned()))
106    }
107}
108
109impl From<Number> for NbtTag {
110    fn from(n: Number) -> Self {
111        match n {
112            Number::Byte(n) => NbtTag::Byte(n),
113            Number::Short(n) => NbtTag::Short(n),
114            Number::Int(n) => NbtTag::Int(n),
115            Number::Long(n) => NbtTag::Long(n),
116            Number::Float(n) => NbtTag::Float(n),
117            Number::Double(n) => NbtTag::Double(n),
118        }
119    }
120}
121
122impl MapLike<NbtTag> for NbtCompound {
123    fn for_each(&self, mut cb: impl FnMut(&NbtTag, &NbtTag)) {
124        for (k, v) in self.iter() {
125            cb(&NbtTag::String(k.into()), v);
126        }
127    }
128}
129
130// impl Codec<NbtTag> for NbtTag {
131//     default fn codec_read(ops: &NbtTag) -> ReadResult<Self> {
132//         Ok(ops.clone())
133//     }
134//     default fn codec_write(self, _: &NbtTag) -> WriteResult<NbtTag> {
135//         Ok(self)
136//     }
137// }
138
139// equivalent to convertTo in mojang codecs
140impl<O: Ops> Codec<O> for NbtTag {
141    fn codec_read(ops: &O) -> ReadResult<Self> {
142        if let Ok(v) = Mutf8String::codec_read(ops) {
143            return Ok(NbtTag::String(v));
144        }
145        if let Ok(v) = Number::codec_read(ops) {
146            return Ok(NbtTag::from(v));
147        }
148        if let Ok(v) = bool::codec_read(ops) {
149            return Ok(NbtTag::Byte(v as i8));
150        }
151        if let Ok(v) = NbtCompound::codec_read(ops) {
152            return Ok(NbtTag::Compound(v));
153        }
154        if let Ok(v) = NbtList::codec_read(ops) {
155            return Ok(NbtTag::List(v));
156        }
157
158        Err(ReadError::custom("unknown type"))
159    }
160    fn codec_write(&self) -> WriteResult<O> {
161        match self {
162            NbtTag::Byte(v) => v.codec_write(),
163            NbtTag::Short(v) => v.codec_write(),
164            NbtTag::Int(v) => v.codec_write(),
165            NbtTag::Long(v) => v.codec_write(),
166            NbtTag::Float(v) => v.codec_write(),
167            NbtTag::Double(v) => v.codec_write(),
168            NbtTag::ByteArray(v) => v.codec_write(),
169            NbtTag::String(v) => v.codec_write(),
170            NbtTag::List(v) => v.codec_write(),
171            NbtTag::Compound(v) => v.codec_write(),
172            NbtTag::IntArray(v) => v.codec_write(),
173            NbtTag::LongArray(v) => v.codec_write(),
174        }
175    }
176}
177
178impl<O: Ops> Codec<O> for Mutf8String {
179    fn codec_read(ops: &O) -> ReadResult<Self> {
180        Ok(String::codec_read(ops)?.into())
181    }
182    fn codec_write(&self) -> WriteResult<O> {
183        self.to_string().codec_write()
184    }
185}
186impl<O: Ops> Codec<O> for NbtList {
187    fn codec_read(ops: &O) -> ReadResult<Self> {
188        Ok(Vec::<NbtTag>::codec_read(ops)?.into())
189    }
190    fn codec_write(&self) -> WriteResult<O> {
191        list_as_tags(self).codec_write()
192    }
193}
194
195fn list_as_tags(list: &NbtList) -> Vec<NbtTag> {
196    if let Some(compounds) = list.compounds() {
197        // dehomogenize lists of compounds
198        let mut tags = Vec::new();
199        for c in compounds {
200            if c.len() == 1
201                && let Some(item) = c.get("")
202            {
203                tags.push(item.clone());
204            } else {
205                tags.push(NbtTag::Compound(c.clone()));
206            }
207        }
208        tags
209    } else {
210        list.as_nbt_tags()
211    }
212}
213
214impl<O: Ops> Codec<O> for NbtCompound {
215    type Incomplete = IncompleteNbtCompound;
216    fn codec_read(ops: &O) -> ReadResult<Self> {
217        let map = ops.get_map()?;
218
219        let mut values = Vec::new();
220        map.for_each(|k, v| {
221            let k = Mutf8String::codec_read(k);
222            let v = NbtTag::codec_read(v);
223            let r = k.and_then(|k| v.map(|v| (k, v)));
224            values.push(r);
225        });
226        let values = values.into_iter().collect::<ReadResult<Vec<_>>>()?;
227
228        Ok(NbtCompound::from_values(values))
229    }
230    fn codec_write(&self) -> WriteResult<O> {
231        let mut map = Vec::new();
232        for (k, v) in self.iter() {
233            map.push((k.to_owned().codec_write()?, v.codec_write()?))
234        }
235        O::create_map(&map)
236    }
237}
238impl_mapcodec!(NbtCompound, IncompleteNbtCompound, Mutf8String: NbtTag);
239
240crate::impl_defaultable!(NbtCompound);