Skip to main content

ghast_protocol/
nbt.rs

1//! Named Binary Tag (NBT) as used on the network.
2//!
3//! Up to 1.20.1 the protocol carries NBT as a *named root tag*: a tag-type byte, a
4//! `u16`-prefixed name and the payload ([`RawNbt`]). A single `0` byte (TAG_End) means
5//! "no compound" — vanilla's packet buffer reads both its plain and its optional NBT that
6//! way. Since 1.20.2 the root has no name: a tag-type byte and the payload ([`AnonNbt`]);
7//! the root may be any tag type (text components are often a bare string tag).
8//!
9//! Packets keep NBT as [`RawNbt`] / [`AnonNbt`]: the exact bytes of the root tag, found by *skipping*
10//! over the structure without allocating. Turning it into a tree ([`RawNbt::parse`]) is
11//! opt-in, so a client that only needs item ids and counts from `window_items` never pays
12//! for building NBT trees (on busy servers that NBT is most of the inbound bytes).
13//!
14//! Strings are Java "Modified UTF-8" (NUL as `C0 80`, supplementary characters as
15//! surrogate pairs). Raw bytes are always preserved exactly; the parsed tree decodes
16//! strings lossily (unpaired surrogates become U+FFFD).
17
18use bytes::{BufMut, Bytes, BytesMut};
19
20use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, Reader};
21use crate::error::{DecodeError, EncodeError};
22
23/// Maximum nesting depth of compounds and lists (same as vanilla).
24pub const MAX_DEPTH: usize = 512;
25
26/// NBT tag type ids.
27#[allow(missing_docs)]
28pub mod tag {
29    pub const END: u8 = 0;
30    pub const BYTE: u8 = 1;
31    pub const SHORT: u8 = 2;
32    pub const INT: u8 = 3;
33    pub const LONG: u8 = 4;
34    pub const FLOAT: u8 = 5;
35    pub const DOUBLE: u8 = 6;
36    pub const BYTE_ARRAY: u8 = 7;
37    pub const STRING: u8 = 8;
38    pub const LIST: u8 = 9;
39    pub const COMPOUND: u8 = 10;
40    pub const INT_ARRAY: u8 = 11;
41    pub const LONG_ARRAY: u8 = 12;
42}
43
44/// The undecoded bytes of one network NBT root tag (type byte, name and payload), or a
45/// single `0` byte for "no compound".
46#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub struct RawNbt(Bytes);
48
49impl RawNbt {
50    /// The "no compound" value (a single TAG_End byte).
51    pub const END: RawNbt = RawNbt(Bytes::from_static(&[0]));
52
53    /// The raw bytes, exactly as they appear on the wire.
54    #[inline]
55    pub fn as_bytes(&self) -> &Bytes {
56        &self.0
57    }
58
59    /// Whether this is the single-byte "no compound" value.
60    #[inline]
61    pub fn is_end(&self) -> bool {
62        self.0.first() == Some(&tag::END)
63    }
64
65    /// Validates `bytes` as exactly one root tag and wraps them.
66    pub fn from_bytes(bytes: Bytes) -> DecodeResult<Self> {
67        let mut r = Reader::new(&bytes);
68        let v = Self::read(&mut r)?;
69        r.finish()?;
70        Ok(v)
71    }
72
73    /// Reads a root tag (or a single TAG_End byte) by skipping over its structure.
74    pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
75        let start = r.position();
76        let ty = r.read_u8()?;
77        if ty != tag::END {
78            let name_len = r.read_u16()? as usize;
79            r.skip(name_len)?;
80            skip_payload(r, ty, 0)?;
81        }
82        Ok(RawNbt(r.bytes_since(start)))
83    }
84
85    /// Reads protodef `optionalNbt`: a `0` byte is `None`, anything else a root tag.
86    pub fn read_optional(r: &mut Reader<'_>) -> DecodeResult<Option<Self>> {
87        if r.peek_u8()? == tag::END {
88            r.skip(1)?;
89            Ok(None)
90        } else {
91            Self::read(r).map(Some)
92        }
93    }
94
95    /// Writes the raw bytes.
96    #[inline]
97    pub fn write(&self, w: &mut BytesMut) {
98        w.put_slice(&self.0);
99    }
100
101    /// Writes protodef `optionalNbt`.
102    #[inline]
103    pub fn write_optional(v: &Option<Self>, w: &mut BytesMut) {
104        match v {
105            Some(n) => n.write(w),
106            None => w.put_u8(tag::END),
107        }
108    }
109
110    /// Parses the tree. Returns `None` for the "no compound" value.
111    pub fn parse(&self) -> DecodeResult<Option<NamedTag>> {
112        let mut r = Reader::new(&self.0);
113        let ty = r.read_u8()?;
114        if ty == tag::END {
115            return Ok(None);
116        }
117        let name = read_mutf8(&mut r)?;
118        let tag = read_payload(&mut r, ty, 0)?;
119        r.finish()?;
120        Ok(Some(NamedTag { name, tag }))
121    }
122
123    /// Serialises a tree into raw network bytes.
124    pub fn from_named(t: &NamedTag) -> Result<Self, EncodeError> {
125        let mut w = BytesMut::new();
126        t.encode(&mut w)?;
127        Ok(RawNbt(w.freeze()))
128    }
129}
130
131impl Decode for RawNbt {
132    #[inline]
133    fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
134        Self::read(r)
135    }
136}
137
138impl Encode for RawNbt {
139    #[inline]
140    fn encode(&self, w: &mut BytesMut) -> EncodeResult {
141        self.write(w);
142        Ok(())
143    }
144}
145
146/// The undecoded bytes of one unnamed network NBT root (1.20.2+): the tag-type byte and
147/// the payload, or a single `0` byte (TAG_End).
148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
149pub struct AnonNbt(Bytes);
150
151impl AnonNbt {
152    /// The single TAG_End byte.
153    pub const END: AnonNbt = AnonNbt(Bytes::from_static(&[0]));
154
155    /// The raw bytes, exactly as they appear on the wire.
156    #[inline]
157    pub fn as_bytes(&self) -> &Bytes {
158        &self.0
159    }
160
161    /// Whether this is the single TAG_End byte.
162    #[inline]
163    pub fn is_end(&self) -> bool {
164        self.0.first() == Some(&tag::END)
165    }
166
167    /// Tag type of the root.
168    #[inline]
169    pub fn tag_type(&self) -> u8 {
170        self.0.first().copied().unwrap_or(tag::END)
171    }
172
173    /// Validates `bytes` as exactly one unnamed root and wraps them.
174    pub fn from_bytes(bytes: Bytes) -> DecodeResult<Self> {
175        let mut r = Reader::new(&bytes);
176        let v = Self::read(&mut r)?;
177        r.finish()?;
178        Ok(v)
179    }
180
181    /// Reads an unnamed root (or a single TAG_End byte) by skipping over its structure.
182    pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
183        let start = r.position();
184        let ty = r.read_u8()?;
185        if ty != tag::END {
186            skip_payload(r, ty, 0)?;
187        }
188        Ok(AnonNbt(r.bytes_since(start)))
189    }
190
191    /// Reads protodef `anonOptionalNbt`: a `0` byte is `None`, anything else a root.
192    pub fn read_optional(r: &mut Reader<'_>) -> DecodeResult<Option<Self>> {
193        if r.peek_u8()? == tag::END {
194            r.skip(1)?;
195            Ok(None)
196        } else {
197            Self::read(r).map(Some)
198        }
199    }
200
201    /// Writes the raw bytes.
202    #[inline]
203    pub fn write(&self, w: &mut BytesMut) {
204        w.put_slice(&self.0);
205    }
206
207    /// Writes protodef `anonOptionalNbt`.
208    #[inline]
209    pub fn write_optional(v: &Option<Self>, w: &mut BytesMut) {
210        match v {
211            Some(n) => n.write(w),
212            None => w.put_u8(tag::END),
213        }
214    }
215
216    /// Parses the tree. Returns `None` for TAG_End.
217    pub fn parse(&self) -> DecodeResult<Option<Tag>> {
218        let mut r = Reader::new(&self.0);
219        let ty = r.read_u8()?;
220        if ty == tag::END {
221            return Ok(None);
222        }
223        let tag = read_payload(&mut r, ty, 0)?;
224        r.finish()?;
225        Ok(Some(tag))
226    }
227
228    /// Serialises a tree as an unnamed root.
229    pub fn from_tag(t: &Tag) -> Result<Self, EncodeError> {
230        let mut w = BytesMut::new();
231        w.put_u8(t.type_id());
232        write_payload(&mut w, t, 0)?;
233        Ok(AnonNbt(w.freeze()))
234    }
235}
236
237impl Decode for AnonNbt {
238    #[inline]
239    fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
240        Self::read(r)
241    }
242}
243
244impl Encode for AnonNbt {
245    #[inline]
246    fn encode(&self, w: &mut BytesMut) -> EncodeResult {
247        self.write(w);
248        Ok(())
249    }
250}
251
252/// Skips the payload of a tag of type `ty`.
253fn skip_payload(r: &mut Reader<'_>, ty: u8, depth: usize) -> DecodeResult<()> {
254    match ty {
255        tag::BYTE => r.skip(1),
256        tag::SHORT => r.skip(2),
257        tag::INT | tag::FLOAT => r.skip(4),
258        tag::LONG | tag::DOUBLE => r.skip(8),
259        tag::BYTE_ARRAY => {
260            let n = read_array_len(r, 1)?;
261            r.skip(n)
262        }
263        tag::INT_ARRAY => {
264            let n = read_array_len(r, 4)?;
265            r.skip(n * 4)
266        }
267        tag::LONG_ARRAY => {
268            let n = read_array_len(r, 8)?;
269            r.skip(n * 8)
270        }
271        tag::STRING => {
272            let n = r.read_u16()? as usize;
273            r.skip(n)
274        }
275        tag::LIST => {
276            if depth >= MAX_DEPTH {
277                return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
278            }
279            let elem = r.read_u8()?;
280            let n = read_list_len(r, elem)?;
281            match elem {
282                // Fixed-size elements: skip in one step.
283                tag::BYTE => r.skip(n),
284                tag::SHORT => r.skip(n * 2),
285                tag::INT | tag::FLOAT => r.skip(n * 4),
286                tag::LONG | tag::DOUBLE => r.skip(n * 8),
287                _ => {
288                    for _ in 0..n {
289                        skip_payload(r, elem, depth + 1)?;
290                    }
291                    Ok(())
292                }
293            }
294        }
295        tag::COMPOUND => {
296            if depth >= MAX_DEPTH {
297                return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
298            }
299            loop {
300                let t = r.read_u8()?;
301                if t == tag::END {
302                    return Ok(());
303                }
304                let name_len = r.read_u16()? as usize;
305                r.skip(name_len)?;
306                skip_payload(r, t, depth + 1)?;
307            }
308        }
309        other => Err(DecodeError::InvalidNbtTag(other)),
310    }
311}
312
313/// Reads an `i32` array length and checks it against the remaining input.
314fn read_array_len(r: &mut Reader<'_>, elem_size: usize) -> DecodeResult<usize> {
315    let n = r.read_i32()?;
316    r.check_count(i64::from(n), elem_size)
317}
318
319/// Smallest encoded size of one list element of type `elem`.
320fn min_size(elem: u8) -> usize {
321    match elem {
322        tag::BYTE | tag::COMPOUND => 1,
323        tag::SHORT | tag::STRING => 2,
324        tag::INT | tag::FLOAT | tag::BYTE_ARRAY | tag::INT_ARRAY | tag::LONG_ARRAY => 4,
325        tag::LONG | tag::DOUBLE => 8,
326        tag::LIST => 5,
327        _ => 1,
328    }
329}
330
331fn read_list_len(r: &mut Reader<'_>, elem: u8) -> DecodeResult<usize> {
332    let n = r.read_i32()?;
333    if elem == tag::END {
334        return if n <= 0 {
335            Ok(0)
336        } else {
337            Err(DecodeError::NbtEndList)
338        };
339    }
340    if elem > tag::LONG_ARRAY {
341        return Err(DecodeError::InvalidNbtTag(elem));
342    }
343    r.check_count(i64::from(n), min_size(elem))
344}
345
346/// A named root tag.
347#[derive(Debug, Clone, PartialEq)]
348pub struct NamedTag {
349    /// Root name (usually empty on the network).
350    pub name: String,
351    /// The root tag (usually a compound).
352    pub tag: Tag,
353}
354
355/// An NBT tag.
356#[derive(Debug, Clone, PartialEq)]
357#[allow(missing_docs)]
358pub enum Tag {
359    Byte(i8),
360    Short(i16),
361    Int(i32),
362    Long(i64),
363    Float(f32),
364    Double(f64),
365    ByteArray(Bytes),
366    String(String),
367    List(List),
368    Compound(Compound),
369    IntArray(Vec<i32>),
370    LongArray(Vec<i64>),
371}
372
373/// An NBT list: element type id and elements (all of that type).
374#[derive(Debug, Clone, PartialEq, Default)]
375pub struct List {
376    /// Element tag type ([`tag::END`] for an empty untyped list).
377    pub elem_type: u8,
378    /// The elements; each must be of `elem_type`.
379    pub items: Vec<Tag>,
380}
381
382/// An NBT compound: named tags in wire order.
383#[derive(Debug, Clone, PartialEq, Default)]
384pub struct Compound(pub Vec<(String, Tag)>);
385
386impl Compound {
387    /// Looks up an entry by name (linear scan; compounds are small).
388    pub fn get(&self, name: &str) -> Option<&Tag> {
389        self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v)
390    }
391}
392
393impl Tag {
394    /// The tag type id.
395    pub fn type_id(&self) -> u8 {
396        match self {
397            Tag::Byte(_) => tag::BYTE,
398            Tag::Short(_) => tag::SHORT,
399            Tag::Int(_) => tag::INT,
400            Tag::Long(_) => tag::LONG,
401            Tag::Float(_) => tag::FLOAT,
402            Tag::Double(_) => tag::DOUBLE,
403            Tag::ByteArray(_) => tag::BYTE_ARRAY,
404            Tag::String(_) => tag::STRING,
405            Tag::List(_) => tag::LIST,
406            Tag::Compound(_) => tag::COMPOUND,
407            Tag::IntArray(_) => tag::INT_ARRAY,
408            Tag::LongArray(_) => tag::LONG_ARRAY,
409        }
410    }
411
412    /// The compound, if this is one.
413    pub fn as_compound(&self) -> Option<&Compound> {
414        match self {
415            Tag::Compound(c) => Some(c),
416            _ => None,
417        }
418    }
419}
420
421fn read_payload(r: &mut Reader<'_>, ty: u8, depth: usize) -> DecodeResult<Tag> {
422    Ok(match ty {
423        tag::BYTE => Tag::Byte(r.read_i8()?),
424        tag::SHORT => Tag::Short(r.read_i16()?),
425        tag::INT => Tag::Int(r.read_i32()?),
426        tag::LONG => Tag::Long(r.read_i64()?),
427        tag::FLOAT => Tag::Float(r.read_f32()?),
428        tag::DOUBLE => Tag::Double(r.read_f64()?),
429        tag::BYTE_ARRAY => {
430            let n = read_array_len(r, 1)?;
431            Tag::ByteArray(r.read_bytes(n)?)
432        }
433        tag::INT_ARRAY => {
434            let n = read_array_len(r, 4)?;
435            let s = r.take(n * 4)?;
436            Tag::IntArray(
437                s.as_chunks::<4>()
438                    .0
439                    .iter()
440                    .map(|c| i32::from_be_bytes(*c))
441                    .collect(),
442            )
443        }
444        tag::LONG_ARRAY => {
445            let n = read_array_len(r, 8)?;
446            let s = r.take(n * 8)?;
447            Tag::LongArray(
448                s.as_chunks::<8>()
449                    .0
450                    .iter()
451                    .map(|c| i64::from_be_bytes(*c))
452                    .collect(),
453            )
454        }
455        tag::STRING => Tag::String(read_mutf8(r)?),
456        tag::LIST => {
457            if depth >= MAX_DEPTH {
458                return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
459            }
460            let elem = r.read_u8()?;
461            let n = read_list_len(r, elem)?;
462            let mut items = Vec::with_capacity(n);
463            for _ in 0..n {
464                items.push(read_payload(r, elem, depth + 1)?);
465            }
466            Tag::List(List {
467                elem_type: elem,
468                items,
469            })
470        }
471        tag::COMPOUND => {
472            if depth >= MAX_DEPTH {
473                return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
474            }
475            let mut entries = Vec::new();
476            loop {
477                let t = r.read_u8()?;
478                if t == tag::END {
479                    break;
480                }
481                let name = read_mutf8(r)?;
482                entries.push((name, read_payload(r, t, depth + 1)?));
483            }
484            Tag::Compound(Compound(entries))
485        }
486        other => return Err(DecodeError::InvalidNbtTag(other)),
487    })
488}
489
490impl Encode for NamedTag {
491    fn encode(&self, w: &mut BytesMut) -> EncodeResult {
492        w.put_u8(self.tag.type_id());
493        write_mutf8(w, &self.name)?;
494        write_payload(w, &self.tag, 0)
495    }
496}
497
498fn i32_len(n: usize) -> Result<i32, EncodeError> {
499    i32::try_from(n).map_err(|_| EncodeError::LengthOverflow {
500        len: n,
501        max: i32::MAX as usize,
502    })
503}
504
505fn write_payload(w: &mut BytesMut, t: &Tag, depth: usize) -> EncodeResult {
506    if depth > MAX_DEPTH {
507        return Err(EncodeError::Invalid("NBT nesting too deep"));
508    }
509    match t {
510        Tag::Byte(v) => w.put_i8(*v),
511        Tag::Short(v) => w.put_i16(*v),
512        Tag::Int(v) => w.put_i32(*v),
513        Tag::Long(v) => w.put_i64(*v),
514        Tag::Float(v) => w.put_f32(*v),
515        Tag::Double(v) => w.put_f64(*v),
516        Tag::ByteArray(b) => {
517            w.put_i32(i32_len(b.len())?);
518            w.put_slice(b);
519        }
520        Tag::String(s) => write_mutf8(w, s)?,
521        Tag::List(l) => {
522            w.put_u8(l.elem_type);
523            w.put_i32(i32_len(l.items.len())?);
524            if l.elem_type == tag::END && !l.items.is_empty() {
525                return Err(EncodeError::Invalid("NBT list of TAG_End with elements"));
526            }
527            for item in &l.items {
528                if item.type_id() != l.elem_type {
529                    return Err(EncodeError::Invalid("NBT list element of the wrong type"));
530                }
531                write_payload(w, item, depth + 1)?;
532            }
533        }
534        Tag::Compound(c) => {
535            for (k, v) in &c.0 {
536                w.put_u8(v.type_id());
537                write_mutf8(w, k)?;
538                write_payload(w, v, depth + 1)?;
539            }
540            w.put_u8(tag::END);
541        }
542        Tag::IntArray(a) => {
543            w.put_i32(i32_len(a.len())?);
544            for v in a {
545                w.put_i32(*v);
546            }
547        }
548        Tag::LongArray(a) => {
549            w.put_i32(i32_len(a.len())?);
550            for v in a {
551                w.put_i64(*v);
552            }
553        }
554    }
555    Ok(())
556}
557
558/// Reads a `u16`-prefixed Modified UTF-8 string.
559fn read_mutf8(r: &mut Reader<'_>) -> DecodeResult<String> {
560    let n = r.read_u16()? as usize;
561    let b = r.take(n)?;
562    decode_mutf8(b)
563}
564
565/// Decodes Java Modified UTF-8.
566pub fn decode_mutf8(b: &[u8]) -> DecodeResult<String> {
567    // Fast path: plain ASCII without NUL (by far the common case) or UTF-8 that cannot
568    // contain MUTF-8 specials (`C0 80` for NUL, `ED` lead bytes for surrogates).
569    if b.iter().all(|&c| c != 0 && c < 0x80) {
570        return std::str::from_utf8(b)
571            .map(str::to_owned)
572            .map_err(|_| DecodeError::InvalidUtf8);
573    }
574    if !b.iter().any(|&c| c == 0 || c == 0xc0 || c == 0xed)
575        && let Ok(s) = std::str::from_utf8(b)
576    {
577        return Ok(s.to_owned());
578    }
579    let mut units: Vec<u16> = Vec::with_capacity(b.len());
580    let mut i = 0;
581    while i < b.len() {
582        let c = b[i];
583        if c < 0x80 {
584            units.push(u16::from(c));
585            i += 1;
586        } else if c & 0xe0 == 0xc0 {
587            let c2 = *b.get(i + 1).ok_or(DecodeError::InvalidUtf8)?;
588            if c2 & 0xc0 != 0x80 {
589                return Err(DecodeError::InvalidUtf8);
590            }
591            units.push((u16::from(c & 0x1f) << 6) | u16::from(c2 & 0x3f));
592            i += 2;
593        } else if c & 0xf0 == 0xe0 {
594            let c2 = *b.get(i + 1).ok_or(DecodeError::InvalidUtf8)?;
595            let c3 = *b.get(i + 2).ok_or(DecodeError::InvalidUtf8)?;
596            if c2 & 0xc0 != 0x80 || c3 & 0xc0 != 0x80 {
597                return Err(DecodeError::InvalidUtf8);
598            }
599            units.push(
600                (u16::from(c & 0x0f) << 12) | (u16::from(c2 & 0x3f) << 6) | u16::from(c3 & 0x3f),
601            );
602            i += 3;
603        } else {
604            return Err(DecodeError::InvalidUtf8);
605        }
606    }
607    Ok(String::from_utf16_lossy(&units))
608}
609
610/// Writes a `u16`-prefixed Modified UTF-8 string.
611fn write_mutf8(w: &mut BytesMut, s: &str) -> EncodeResult {
612    let too_long = |len| EncodeError::LengthOverflow {
613        len,
614        max: u16::MAX as usize,
615    };
616    // Fast path: no NUL and no supplementary characters means MUTF-8 == UTF-8.
617    if s.bytes().all(|b| b != 0 && b < 0xf0) {
618        let n = u16::try_from(s.len()).map_err(|_| too_long(s.len()))?;
619        w.put_u16(n);
620        w.put_slice(s.as_bytes());
621        return Ok(());
622    }
623    let mut out = Vec::with_capacity(s.len() + 8);
624    for u in s.encode_utf16() {
625        match u {
626            0x0001..=0x007f => out.push(u as u8),
627            0x0000 | 0x0080..=0x07ff => {
628                out.push(0xc0 | (u >> 6) as u8);
629                out.push(0x80 | (u & 0x3f) as u8);
630            }
631            _ => {
632                out.push(0xe0 | (u >> 12) as u8);
633                out.push(0x80 | ((u >> 6) & 0x3f) as u8);
634                out.push(0x80 | (u & 0x3f) as u8);
635            }
636        }
637    }
638    let n = u16::try_from(out.len()).map_err(|_| too_long(out.len()))?;
639    w.put_u16(n);
640    w.put_slice(&out);
641    Ok(())
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    /// The classic `hello_world.nbt` test file (uncompressed).
649    const HELLO_WORLD: &[u8] = &[
650        0x0a, 0x00, 0x0b, b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd', 0x08,
651        0x00, 0x04, b'n', b'a', b'm', b'e', 0x00, 0x09, b'B', b'a', b'n', b'a', b'n', b'r', b'a',
652        b'm', b'a', 0x00,
653    ];
654
655    #[test]
656    fn hello_world() {
657        let b = Bytes::from_static(HELLO_WORLD);
658        let raw = RawNbt::from_bytes(b.clone()).unwrap();
659        let t = raw.parse().unwrap().unwrap();
660        assert_eq!(t.name, "hello world");
661        let c = t.tag.as_compound().unwrap();
662        assert_eq!(c.get("name"), Some(&Tag::String("Bananrama".into())));
663        assert_eq!(RawNbt::from_named(&t).unwrap().as_bytes(), &b);
664    }
665
666    #[test]
667    fn optional_and_end() {
668        let b = Bytes::from_static(&[0x00, 0x01]);
669        let mut r = Reader::new(&b);
670        assert_eq!(RawNbt::read_optional(&mut r), Ok(None));
671        assert_eq!(r.remaining(), 1);
672        let b = Bytes::from_static(&[0x00]);
673        let raw = RawNbt::from_bytes(b).unwrap();
674        assert!(raw.is_end());
675        assert_eq!(raw.parse(), Ok(None));
676    }
677
678    #[test]
679    fn rejects_bad_input() {
680        // Unknown tag type inside a compound.
681        let b = Bytes::from_static(&[0x0a, 0x00, 0x00, 0x0d, 0x00, 0x00]);
682        assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::InvalidNbtTag(13)));
683        // List of TAG_End with a positive length.
684        let b = Bytes::from_static(&[0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05]);
685        assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::NbtEndList));
686        // Huge int array length is bounded by the input instead of allocating.
687        let b = Bytes::from_static(&[0x0b, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff]);
688        assert!(matches!(
689            RawNbt::from_bytes(b),
690            Err(DecodeError::LengthTooLarge { .. })
691        ));
692        // Deep nesting is limited.
693        let mut v = vec![0x09, 0x00, 0x00];
694        for _ in 0..600 {
695            v.extend_from_slice(&[0x09, 0x00, 0x00, 0x00, 0x01]);
696        }
697        let b = Bytes::from(v);
698        assert_eq!(
699            RawNbt::from_bytes(b),
700            Err(DecodeError::NbtTooDeep(MAX_DEPTH))
701        );
702    }
703
704    #[test]
705    fn modified_utf8() {
706        let s = "a\0b\u{e9}\u{1f600}";
707        let mut w = BytesMut::new();
708        write_mutf8(&mut w, s).unwrap();
709        // NUL -> C0 80, U+1F600 -> surrogate pair, each 3 bytes.
710        assert_eq!(
711            &w[..],
712            &[
713                0x00, 0x0c, b'a', 0xc0, 0x80, b'b', 0xc3, 0xa9, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80
714            ]
715        );
716        assert_eq!(decode_mutf8(&w[2..]).unwrap(), s);
717        assert_eq!(decode_mutf8(&[0xc3]), Err(DecodeError::InvalidUtf8));
718        // Standard 4-byte UTF-8 (as written by some non-Java encoders) is accepted.
719        assert_eq!(
720            decode_mutf8(&[0xf0, 0x9f, 0x98, 0x80]).unwrap(),
721            "\u{1f600}"
722        );
723        assert_eq!(decode_mutf8(&[0xf8, 0x80]), Err(DecodeError::InvalidUtf8));
724    }
725}