azalea_buf/ctx.rs
1use std::any::Any;
2
3use crate::{BufReadError, BufReadErrorRepr};
4
5/// Some context that's maintained when reading and writing packets.
6///
7/// For packets that involve registries, you are required to pass a
8/// `RegistryHolder`, otherwise reading and writing them will fail. For other
9/// packets, it's OK to pass `Ctx::default()`.
10#[derive(Clone, Copy)]
11pub struct Ctx<'a> {
12 depth: u32,
13 pub resolver: &'a dyn ResolverTrait,
14}
15impl<'a> Ctx<'a> {
16 pub fn new(resolver: &'a dyn ResolverTrait) -> Self {
17 Self { depth: 0, resolver }
18 }
19 /// Increment the depth counter, or error if it exceeds the limit.
20 ///
21 /// This exists to prevent exploits that make us crash by exhausting our
22 /// stack space. The `AzBuf` macro adds this whenever [`Ctx`] is used,
23 /// though if you know that recursion isn't possible with a type then it's
24 /// not strictly necessary.
25 pub fn inc_depth(mut self) -> Result<Self, BufReadError> {
26 if self.depth > 255 {
27 return Err(BufReadErrorRepr::DepthLimitExceeded.into());
28 }
29 self.depth += 1;
30 Ok(self)
31 }
32}
33impl<'a> Default for Ctx<'a> {
34 fn default() -> Self {
35 Self {
36 depth: 0,
37 resolver: &(),
38 }
39 }
40}
41
42/// A marker trait for types that can be passed to [`Ctx`].
43pub trait ResolverTrait: Any + Send + Sync {}
44impl ResolverTrait for () {}