Skip to main content

azalea_buf/impls/
extra.rs

1use std::{
2    collections::HashMap,
3    hash::Hash,
4    io::{self, Cursor, Write},
5    sync::Arc,
6};
7
8use indexmap::IndexMap;
9
10use crate::{
11    AzBuf, AzBufLimited, AzBufVar, BufReadError, BufReadErrorRepr, MAX_STRING_LENGTH,
12    UnsizedByteArray, read_bytes, read_utf8_with_len, write_utf_with_len,
13};
14
15impl AzBuf for UnsizedByteArray {
16    fn azalea_read(_ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
17        // read to end of the buffer
18        let data = buf.get_ref()[buf.position() as usize..].to_vec();
19        buf.set_position((buf.position()) + data.len() as u64);
20        Ok(UnsizedByteArray(data))
21    }
22    fn azalea_write(&self, _ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
23        buf.write_all(self)
24    }
25}
26
27macro_rules! impl_for_map_type {
28    ($ty: ident) => {
29        impl<K: AzBuf + Eq + Hash, V: AzBuf> AzBuf for $ty<K, V> {
30            fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
31                let length = i32::azalea_read_var(ctx, buf)? as usize;
32                let mut contents = Self::with_capacity(usize::min(length, 65536));
33                for _ in 0..length {
34                    contents.insert(K::azalea_read(ctx, buf)?, V::azalea_read(ctx, buf)?);
35                }
36                Ok(contents)
37            }
38            fn azalea_write(&self, ctx: $crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
39                (self.len() as u32).azalea_write_var(ctx, buf)?;
40                for (key, value) in self {
41                    key.azalea_write(ctx, buf)?;
42                    value.azalea_write(ctx, buf)?;
43                }
44
45                Ok(())
46            }
47        }
48        impl<K: AzBuf + Eq + Hash, V: AzBufVar> AzBufVar for $ty<K, V> {
49            fn azalea_read_var(
50                ctx: crate::Ctx,
51                buf: &mut Cursor<&[u8]>,
52            ) -> Result<Self, BufReadError> {
53                let length = i32::azalea_read_var(ctx, buf)? as usize;
54                let mut contents = Self::with_capacity(usize::min(length, 65536));
55                for _ in 0..length {
56                    contents.insert(K::azalea_read(ctx, buf)?, V::azalea_read_var(ctx, buf)?);
57                }
58                Ok(contents)
59            }
60            fn azalea_write_var(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
61                u32::azalea_write_var(&(self.len() as u32), ctx, buf)?;
62                for (key, value) in self {
63                    key.azalea_write(ctx, buf)?;
64                    value.azalea_write_var(ctx, buf)?;
65                }
66
67                Ok(())
68            }
69        }
70    };
71}
72
73impl_for_map_type!(HashMap);
74impl_for_map_type!(IndexMap);
75
76macro_rules! impl_for_list_type {
77    ($ty: ty) => {
78        impl<T: AzBuf> AzBuf for $ty {
79            default fn azalea_read(
80                ctx: crate::Ctx,
81                buf: &mut Cursor<&[u8]>,
82            ) -> Result<Self, BufReadError> {
83                let length = u32::azalea_read_var(ctx, buf)? as usize;
84                // we limit the capacity to not get exploited into allocating a bunch
85                let mut contents = Vec::with_capacity(usize::min(length, 65536));
86                for _ in 0..length {
87                    contents.push(T::azalea_read(ctx, buf)?);
88                }
89                Ok(contents.into())
90            }
91            default fn azalea_write(
92                &self,
93                ctx: $crate::Ctx,
94                buf: &mut impl Write,
95            ) -> io::Result<()> {
96                (self.len() as u32).azalea_write_var(ctx, buf)?;
97                for item in self.iter() {
98                    T::azalea_write(item, ctx, buf)?;
99                }
100                Ok(())
101            }
102        }
103        impl<T: AzBufVar> AzBufVar for $ty {
104            fn azalea_read_var(
105                ctx: $crate::Ctx,
106                buf: &mut Cursor<&[u8]>,
107            ) -> Result<Self, BufReadError> {
108                let length = i32::azalea_read_var(ctx, buf)? as usize;
109                let mut contents = Vec::with_capacity(usize::min(length, 65536));
110                for _ in 0..length {
111                    contents.push(T::azalea_read_var(ctx, buf)?);
112                }
113                Ok(contents.into())
114            }
115            fn azalea_write_var(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
116                (self.len() as u32).azalea_write_var(ctx, buf)?;
117                for item in self.iter() {
118                    T::azalea_write_var(item, ctx, buf)?;
119                }
120                Ok(())
121            }
122        }
123        impl<T: AzBuf> AzBufLimited for $ty {
124            fn azalea_read_limited(
125                ctx: $crate::Ctx,
126                buf: &mut Cursor<&[u8]>,
127                limit: u32,
128            ) -> Result<Self, BufReadError> {
129                let length = u32::azalea_read_var(ctx, buf)?;
130                if length > limit {
131                    return Err(BufReadErrorRepr::VecLengthTooLong {
132                        length: length as u32,
133                        max_length: limit as u32,
134                    }
135                    .into());
136                }
137
138                let mut contents = Vec::with_capacity(u32::min(length, 65536) as usize);
139                for _ in 0..length {
140                    contents.push(T::azalea_read(ctx, buf)?);
141                }
142                Ok(contents.into())
143            }
144        }
145    };
146}
147
148impl_for_list_type!(Vec<T>);
149impl_for_list_type!(Box<[T]>);
150// `Arc<[T]>` is deliberately not implemented here, because converting a
151// `Vec<T>` to `Arc<[T]>` results in allocations (since `Arc` stores the
152// counters on the heap) and we'd like to avoid that. for us it's typically
153// better to do `Arc<Box<[T]>>`.
154
155impl AzBuf for Vec<u8> {
156    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
157        let length = i32::azalea_read_var(ctx, buf)? as usize;
158        read_bytes(buf, length).map(|b| b.to_vec())
159    }
160    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
161        (self.len() as u32).azalea_write_var(ctx, buf)?;
162        buf.write_all(self)
163    }
164}
165
166impl AzBuf for Box<[u8]> {
167    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
168        let length = i32::azalea_read_var(ctx, buf)? as usize;
169        read_bytes(buf, length).map(Box::from)
170    }
171    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
172        (self.len() as u32).azalea_write_var(ctx, buf)?;
173        buf.write_all(self)
174    }
175}
176
177impl AzBuf for String {
178    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
179        read_utf8_with_len(ctx, buf, MAX_STRING_LENGTH).map(Into::into)
180    }
181    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
182        write_utf_with_len(ctx, buf, self, MAX_STRING_LENGTH)
183    }
184}
185impl AzBufLimited for String {
186    fn azalea_read_limited(
187        ctx: crate::Ctx,
188        buf: &mut Cursor<&[u8]>,
189        limit: u32,
190    ) -> Result<Self, BufReadError> {
191        read_utf8_with_len(ctx, buf, limit).map(Into::into)
192    }
193}
194
195impl AzBuf for Box<str> {
196    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
197        read_utf8_with_len(ctx, buf, MAX_STRING_LENGTH).map(Into::into)
198    }
199    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
200        write_utf_with_len(ctx, buf, self, MAX_STRING_LENGTH)
201    }
202}
203
204impl AzBufLimited for Box<str> {
205    fn azalea_read_limited(
206        ctx: crate::Ctx,
207        buf: &mut Cursor<&[u8]>,
208        limit: u32,
209    ) -> Result<Self, BufReadError> {
210        String::azalea_read_limited(ctx, buf, limit).map(Into::into)
211    }
212}
213
214impl<T: AzBuf> AzBuf for Option<T> {
215    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
216        let present = bool::azalea_read(ctx, buf)?;
217        Ok(if present {
218            Some(T::azalea_read(ctx, buf)?)
219        } else {
220            None
221        })
222    }
223    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
224        if let Some(s) = self {
225            true.azalea_write(ctx, buf)?;
226            s.azalea_write(ctx, buf)?;
227        } else {
228            false.azalea_write(ctx, buf)?;
229        };
230        Ok(())
231    }
232}
233
234impl<T: AzBufVar> AzBufVar for Option<T> {
235    fn azalea_read_var(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
236        let present = bool::azalea_read(ctx, buf)?;
237        Ok(if present {
238            Some(T::azalea_read_var(ctx, buf)?)
239        } else {
240            None
241        })
242    }
243    fn azalea_write_var(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
244        if let Some(s) = self {
245            true.azalea_write(ctx, buf)?;
246            s.azalea_write_var(ctx, buf)?;
247        } else {
248            false.azalea_write(ctx, buf)?;
249        };
250        Ok(())
251    }
252}
253impl<T: AzBufLimited> AzBufLimited for Option<T> {
254    fn azalea_read_limited(
255        ctx: crate::Ctx,
256        buf: &mut Cursor<&[u8]>,
257        limit: u32,
258    ) -> Result<Self, BufReadError> {
259        let present = bool::azalea_read(ctx, buf)?;
260        Ok(if present {
261            Some(T::azalea_read_limited(ctx, buf, limit)?)
262        } else {
263            None
264        })
265    }
266}
267
268impl<T: AzBuf, const N: usize> AzBuf for [T; N] {
269    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
270        let mut contents = Vec::with_capacity(N);
271        for _ in 0..N {
272            contents.push(T::azalea_read(ctx, buf)?);
273        }
274        Ok(contents
275            .try_into()
276            .unwrap_or_else(|_| unreachable!("The vec is the same size as the array")))
277    }
278    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
279        for i in self {
280            i.azalea_write(ctx, buf)?;
281        }
282        Ok(())
283    }
284}
285
286impl AzBuf for simdnbt::owned::NbtTag {
287    fn azalea_read(_ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
288        Ok(simdnbt::owned::read_tag(buf).map_err(simdnbt::Error::from)?)
289    }
290    fn azalea_write(&self, _ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
291        let mut data = Vec::new();
292        self.write(&mut data);
293        buf.write_all(&data)
294    }
295}
296
297impl AzBuf for simdnbt::owned::NbtCompound {
298    fn azalea_read(_ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
299        match simdnbt::owned::read_tag(buf).map_err(simdnbt::Error::from)? {
300            simdnbt::owned::NbtTag::Compound(compound) => Ok(compound),
301            _ => Err(BufReadError::custom("Expected compound tag")),
302        }
303    }
304    fn azalea_write(&self, _ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
305        let mut data = Vec::new();
306        simdnbt::owned::NbtTag::Compound(self.clone()).write(&mut data);
307        buf.write_all(&data)
308    }
309}
310
311impl AzBuf for simdnbt::owned::Nbt {
312    fn azalea_read(_ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
313        Ok(simdnbt::owned::read_unnamed(buf)?)
314    }
315    fn azalea_write(&self, _ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
316        let mut data = Vec::new();
317        self.write_unnamed(&mut data);
318        buf.write_all(&data)
319    }
320}
321
322impl<T> AzBuf for Box<T>
323where
324    T: AzBuf,
325{
326    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
327        T::azalea_read(ctx, buf).map(Box::new)
328    }
329    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
330        T::azalea_write(&**self, ctx, buf)
331    }
332}
333
334impl<A: AzBuf, B: AzBuf> AzBuf for (A, B) {
335    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
336        let a = A::azalea_read(ctx, buf)?;
337        let b = B::azalea_read(ctx, buf)?;
338        Ok((a, b))
339    }
340    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
341        self.0.azalea_write(ctx, buf)?;
342        self.1.azalea_write(ctx, buf)
343    }
344}
345
346impl<T: AzBuf> AzBuf for Arc<T> {
347    fn azalea_read(ctx: crate::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
348        Ok(Arc::new(T::azalea_read(ctx, buf)?))
349    }
350    fn azalea_write(&self, ctx: crate::Ctx, buf: &mut impl Write) -> io::Result<()> {
351        T::azalea_write(&**self, ctx, buf)
352    }
353}