Skip to main content

ghast_protocol/types/
holder.rs

1//! Registry references that may carry their value inline (1.20.5+).
2
3use bytes::BytesMut;
4use bytestring::ByteString;
5
6use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, McWrite, Reader};
7use crate::error::EncodeError;
8
9/// A registry entry: either a reference by registry id or the value itself
10/// (protodef `registryEntryHolder`).
11///
12/// On the wire a VarInt: `0` means the value follows inline, any other value is the
13/// registry id plus one. `Id(-1)` therefore cannot be encoded.
14#[derive(Debug, Clone, PartialEq)]
15pub enum Holder<T> {
16    /// Registry id (already shifted back, i.e. the wire value minus one).
17    Id(i32),
18    /// The value, sent inline.
19    Inline(T),
20}
21
22impl<T> Holder<T> {
23    /// The registry id, if this is a reference.
24    #[inline]
25    pub fn id(&self) -> Option<i32> {
26        match *self {
27            Holder::Id(id) => Some(id),
28            Holder::Inline(_) => None,
29        }
30    }
31}
32
33/// A set of registry entries: a tag or an explicit list of registry ids
34/// (protodef `registryEntryHolderSet`).
35///
36/// On the wire a VarInt `n`: `0` means a tag name (identifier string) follows, any other
37/// value is followed by `n - 1` VarInt registry ids.
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub enum HolderSet {
40    /// A tag, e.g. `minecraft:logs`.
41    Tag(ByteString),
42    /// Explicit registry ids.
43    Ids(Vec<i32>),
44}
45
46impl Decode for HolderSet {
47    fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
48        let n = r.read_varint()?;
49        if n == 0 {
50            return Ok(HolderSet::Tag(r.read_string()?));
51        }
52        let count = r.check_count(i64::from(n) - 1, 1)?;
53        let mut ids = Vec::with_capacity(count.min(crate::codec::PREALLOC_LIMIT));
54        for _ in 0..count {
55            ids.push(r.read_varint()?);
56        }
57        Ok(HolderSet::Ids(ids))
58    }
59}
60
61impl HolderSet {
62    /// Skips one encoded holder set without building it.
63    pub fn skip(r: &mut Reader<'_>) -> DecodeResult<()> {
64        let n = r.read_varint()?;
65        if n == 0 {
66            r.read_string()?;
67            return Ok(());
68        }
69        let count = r.check_count(i64::from(n) - 1, 1)?;
70        for _ in 0..count {
71            r.read_varint()?;
72        }
73        Ok(())
74    }
75}
76
77impl Encode for HolderSet {
78    fn encode(&self, w: &mut BytesMut) -> EncodeResult {
79        match self {
80            HolderSet::Tag(t) => {
81                w.put_varint(0);
82                w.put_string(t)
83            }
84            HolderSet::Ids(ids) => {
85                let n = i32::try_from(ids.len())
86                    .ok()
87                    .and_then(|n| n.checked_add(1))
88                    .ok_or(EncodeError::OutOfRange("holder set length"))?;
89                w.put_varint(n);
90                for &id in ids {
91                    w.put_varint(id);
92                }
93                Ok(())
94            }
95        }
96    }
97}
98
99#[cfg(feature = "testgen")]
100impl crate::testgen::Generate for HolderSet {
101    fn generate(g: &mut crate::testgen::Gen) -> Self {
102        if g.bool() {
103            HolderSet::Tag(g.string())
104        } else {
105            HolderSet::Ids(
106                (0..g.count())
107                    .map(|_| g.int_in(i64::from(i32::MIN), i64::from(i32::MAX), &[0, 1]) as i32)
108                    .collect(),
109            )
110        }
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use crate::codec::decode_exact;
118
119    #[test]
120    fn holder_set_wire() {
121        let tag = HolderSet::Tag("minecraft:logs".into());
122        let mut w = BytesMut::new();
123        tag.encode(&mut w).unwrap();
124        assert_eq!(w[0], 0);
125        assert_eq!(decode_exact::<HolderSet>(&w.freeze()).unwrap(), tag);
126        let ids = HolderSet::Ids(vec![3, 300]);
127        let mut w = BytesMut::new();
128        ids.encode(&mut w).unwrap();
129        assert_eq!(&w[..], &[3, 3, 0xac, 0x02]);
130        assert_eq!(decode_exact::<HolderSet>(&w.freeze()).unwrap(), ids);
131    }
132}