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