1use bytes::{BufMut, Bytes, BytesMut};
19
20use crate::codec::{Decode, DecodeResult, Encode, EncodeResult, Reader};
21use crate::error::{DecodeError, EncodeError};
22
23pub const MAX_DEPTH: usize = 512;
25
26#[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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub struct RawNbt(Bytes);
48
49impl RawNbt {
50 pub const END: RawNbt = RawNbt(Bytes::from_static(&[0]));
52
53 #[inline]
55 pub fn as_bytes(&self) -> &Bytes {
56 &self.0
57 }
58
59 #[inline]
61 pub fn is_end(&self) -> bool {
62 self.0.first() == Some(&tag::END)
63 }
64
65 pub fn detach(&mut self) {
69 if self.0.len() > 1 {
70 self.0 = Bytes::copy_from_slice(&self.0);
71 }
72 }
73
74 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 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 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 #[inline]
106 pub fn write(&self, w: &mut BytesMut) {
107 w.put_slice(&self.0);
108 }
109
110 #[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 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
158pub struct AnonNbt(Bytes);
159
160impl AnonNbt {
161 pub const END: AnonNbt = AnonNbt(Bytes::from_static(&[0]));
163
164 #[inline]
166 pub fn as_bytes(&self) -> &Bytes {
167 &self.0
168 }
169
170 #[inline]
172 pub fn is_end(&self) -> bool {
173 self.0.first() == Some(&tag::END)
174 }
175
176 #[inline]
178 pub fn tag_type(&self) -> u8 {
179 self.0.first().copied().unwrap_or(tag::END)
180 }
181
182 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 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 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 #[inline]
212 pub fn write(&self, w: &mut BytesMut) {
213 w.put_slice(&self.0);
214 }
215
216 #[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 pub fn parse(&self) -> DecodeResult<Option<Tag>> {
227 let mut r = Reader::new(&self.0);
228 let ty = r.read_u8()?;
229 if ty == tag::END {
230 return Ok(None);
231 }
232 let tag = read_payload(&mut r, ty, 0)?;
233 r.finish()?;
234 Ok(Some(tag))
235 }
236
237 pub fn from_tag(t: &Tag) -> Result<Self, EncodeError> {
239 let mut w = BytesMut::new();
240 w.put_u8(t.type_id());
241 write_payload(&mut w, t, 0)?;
242 Ok(AnonNbt(w.freeze()))
243 }
244}
245
246impl Decode for AnonNbt {
247 #[inline]
248 fn decode(r: &mut Reader<'_>) -> DecodeResult<Self> {
249 Self::read(r)
250 }
251}
252
253impl Encode for AnonNbt {
254 #[inline]
255 fn encode(&self, w: &mut BytesMut) -> EncodeResult {
256 self.write(w);
257 Ok(())
258 }
259}
260
261fn skip_payload(r: &mut Reader<'_>, ty: u8, depth: usize) -> DecodeResult<()> {
263 match ty {
264 tag::BYTE => r.skip(1),
265 tag::SHORT => r.skip(2),
266 tag::INT | tag::FLOAT => r.skip(4),
267 tag::LONG | tag::DOUBLE => r.skip(8),
268 tag::BYTE_ARRAY => {
269 let n = read_array_len(r, 1)?;
270 r.skip(n)
271 }
272 tag::INT_ARRAY => {
273 let n = read_array_len(r, 4)?;
274 r.skip(n * 4)
275 }
276 tag::LONG_ARRAY => {
277 let n = read_array_len(r, 8)?;
278 r.skip(n * 8)
279 }
280 tag::STRING => {
281 let n = r.read_u16()? as usize;
282 r.skip(n)
283 }
284 tag::LIST => {
285 if depth >= MAX_DEPTH {
286 return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
287 }
288 let elem = r.read_u8()?;
289 let n = read_list_len(r, elem)?;
290 match elem {
291 tag::BYTE => r.skip(n),
293 tag::SHORT => r.skip(n * 2),
294 tag::INT | tag::FLOAT => r.skip(n * 4),
295 tag::LONG | tag::DOUBLE => r.skip(n * 8),
296 _ => {
297 for _ in 0..n {
298 skip_payload(r, elem, depth + 1)?;
299 }
300 Ok(())
301 }
302 }
303 }
304 tag::COMPOUND => {
305 if depth >= MAX_DEPTH {
306 return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
307 }
308 loop {
309 let t = r.read_u8()?;
310 if t == tag::END {
311 return Ok(());
312 }
313 let name_len = r.read_u16()? as usize;
314 r.skip(name_len)?;
315 skip_payload(r, t, depth + 1)?;
316 }
317 }
318 other => Err(DecodeError::InvalidNbtTag(other)),
319 }
320}
321
322fn read_array_len(r: &mut Reader<'_>, elem_size: usize) -> DecodeResult<usize> {
324 let n = r.read_i32()?;
325 r.check_count(i64::from(n), elem_size)
326}
327
328fn min_size(elem: u8) -> usize {
330 match elem {
331 tag::BYTE | tag::COMPOUND => 1,
332 tag::SHORT | tag::STRING => 2,
333 tag::INT | tag::FLOAT | tag::BYTE_ARRAY | tag::INT_ARRAY | tag::LONG_ARRAY => 4,
334 tag::LONG | tag::DOUBLE => 8,
335 tag::LIST => 5,
336 _ => 1,
337 }
338}
339
340fn read_list_len(r: &mut Reader<'_>, elem: u8) -> DecodeResult<usize> {
341 let n = r.read_i32()?;
342 if elem == tag::END {
343 return if n <= 0 {
344 Ok(0)
345 } else {
346 Err(DecodeError::NbtEndList)
347 };
348 }
349 if elem > tag::LONG_ARRAY {
350 return Err(DecodeError::InvalidNbtTag(elem));
351 }
352 r.check_count(i64::from(n), min_size(elem))
353}
354
355#[derive(Debug, Clone, PartialEq)]
357pub struct NamedTag {
358 pub name: String,
360 pub tag: Tag,
362}
363
364#[derive(Debug, Clone, PartialEq)]
366#[allow(missing_docs)]
367pub enum Tag {
368 Byte(i8),
369 Short(i16),
370 Int(i32),
371 Long(i64),
372 Float(f32),
373 Double(f64),
374 ByteArray(Bytes),
375 String(String),
376 List(List),
377 Compound(Compound),
378 IntArray(Vec<i32>),
379 LongArray(Vec<i64>),
380}
381
382#[derive(Debug, Clone, PartialEq, Default)]
384pub struct List {
385 pub elem_type: u8,
387 pub items: Vec<Tag>,
389}
390
391#[derive(Debug, Clone, PartialEq, Default)]
393pub struct Compound(pub Vec<(String, Tag)>);
394
395impl Compound {
396 pub fn get(&self, name: &str) -> Option<&Tag> {
398 self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v)
399 }
400}
401
402impl Tag {
403 pub fn type_id(&self) -> u8 {
405 match self {
406 Tag::Byte(_) => tag::BYTE,
407 Tag::Short(_) => tag::SHORT,
408 Tag::Int(_) => tag::INT,
409 Tag::Long(_) => tag::LONG,
410 Tag::Float(_) => tag::FLOAT,
411 Tag::Double(_) => tag::DOUBLE,
412 Tag::ByteArray(_) => tag::BYTE_ARRAY,
413 Tag::String(_) => tag::STRING,
414 Tag::List(_) => tag::LIST,
415 Tag::Compound(_) => tag::COMPOUND,
416 Tag::IntArray(_) => tag::INT_ARRAY,
417 Tag::LongArray(_) => tag::LONG_ARRAY,
418 }
419 }
420
421 pub fn as_compound(&self) -> Option<&Compound> {
423 match self {
424 Tag::Compound(c) => Some(c),
425 _ => None,
426 }
427 }
428}
429
430fn read_payload(r: &mut Reader<'_>, ty: u8, depth: usize) -> DecodeResult<Tag> {
431 Ok(match ty {
432 tag::BYTE => Tag::Byte(r.read_i8()?),
433 tag::SHORT => Tag::Short(r.read_i16()?),
434 tag::INT => Tag::Int(r.read_i32()?),
435 tag::LONG => Tag::Long(r.read_i64()?),
436 tag::FLOAT => Tag::Float(r.read_f32()?),
437 tag::DOUBLE => Tag::Double(r.read_f64()?),
438 tag::BYTE_ARRAY => {
439 let n = read_array_len(r, 1)?;
440 Tag::ByteArray(r.read_bytes(n)?)
441 }
442 tag::INT_ARRAY => {
443 let n = read_array_len(r, 4)?;
444 let s = r.take(n * 4)?;
445 Tag::IntArray(
446 s.as_chunks::<4>()
447 .0
448 .iter()
449 .map(|c| i32::from_be_bytes(*c))
450 .collect(),
451 )
452 }
453 tag::LONG_ARRAY => {
454 let n = read_array_len(r, 8)?;
455 let s = r.take(n * 8)?;
456 Tag::LongArray(
457 s.as_chunks::<8>()
458 .0
459 .iter()
460 .map(|c| i64::from_be_bytes(*c))
461 .collect(),
462 )
463 }
464 tag::STRING => Tag::String(read_mutf8(r)?),
465 tag::LIST => {
466 if depth >= MAX_DEPTH {
467 return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
468 }
469 let elem = r.read_u8()?;
470 let n = read_list_len(r, elem)?;
471 let mut items = Vec::with_capacity(n);
472 for _ in 0..n {
473 items.push(read_payload(r, elem, depth + 1)?);
474 }
475 Tag::List(List {
476 elem_type: elem,
477 items,
478 })
479 }
480 tag::COMPOUND => {
481 if depth >= MAX_DEPTH {
482 return Err(DecodeError::NbtTooDeep(MAX_DEPTH));
483 }
484 let mut entries = Vec::new();
485 loop {
486 let t = r.read_u8()?;
487 if t == tag::END {
488 break;
489 }
490 let name = read_mutf8(r)?;
491 entries.push((name, read_payload(r, t, depth + 1)?));
492 }
493 Tag::Compound(Compound(entries))
494 }
495 other => return Err(DecodeError::InvalidNbtTag(other)),
496 })
497}
498
499impl Encode for NamedTag {
500 fn encode(&self, w: &mut BytesMut) -> EncodeResult {
501 w.put_u8(self.tag.type_id());
502 write_mutf8(w, &self.name)?;
503 write_payload(w, &self.tag, 0)
504 }
505}
506
507fn i32_len(n: usize) -> Result<i32, EncodeError> {
508 i32::try_from(n).map_err(|_| EncodeError::LengthOverflow {
509 len: n,
510 max: i32::MAX as usize,
511 })
512}
513
514fn write_payload(w: &mut BytesMut, t: &Tag, depth: usize) -> EncodeResult {
515 if depth > MAX_DEPTH {
516 return Err(EncodeError::Invalid("NBT nesting too deep"));
517 }
518 match t {
519 Tag::Byte(v) => w.put_i8(*v),
520 Tag::Short(v) => w.put_i16(*v),
521 Tag::Int(v) => w.put_i32(*v),
522 Tag::Long(v) => w.put_i64(*v),
523 Tag::Float(v) => w.put_f32(*v),
524 Tag::Double(v) => w.put_f64(*v),
525 Tag::ByteArray(b) => {
526 w.put_i32(i32_len(b.len())?);
527 w.put_slice(b);
528 }
529 Tag::String(s) => write_mutf8(w, s)?,
530 Tag::List(l) => {
531 w.put_u8(l.elem_type);
532 w.put_i32(i32_len(l.items.len())?);
533 if l.elem_type == tag::END && !l.items.is_empty() {
534 return Err(EncodeError::Invalid("NBT list of TAG_End with elements"));
535 }
536 for item in &l.items {
537 if item.type_id() != l.elem_type {
538 return Err(EncodeError::Invalid("NBT list element of the wrong type"));
539 }
540 write_payload(w, item, depth + 1)?;
541 }
542 }
543 Tag::Compound(c) => {
544 for (k, v) in &c.0 {
545 w.put_u8(v.type_id());
546 write_mutf8(w, k)?;
547 write_payload(w, v, depth + 1)?;
548 }
549 w.put_u8(tag::END);
550 }
551 Tag::IntArray(a) => {
552 w.put_i32(i32_len(a.len())?);
553 for v in a {
554 w.put_i32(*v);
555 }
556 }
557 Tag::LongArray(a) => {
558 w.put_i32(i32_len(a.len())?);
559 for v in a {
560 w.put_i64(*v);
561 }
562 }
563 }
564 Ok(())
565}
566
567fn read_mutf8(r: &mut Reader<'_>) -> DecodeResult<String> {
569 let n = r.read_u16()? as usize;
570 let b = r.take(n)?;
571 decode_mutf8(b)
572}
573
574pub fn decode_mutf8(b: &[u8]) -> DecodeResult<String> {
576 if b.iter().all(|&c| c != 0 && c < 0x80) {
579 return std::str::from_utf8(b)
580 .map(str::to_owned)
581 .map_err(|_| DecodeError::InvalidUtf8);
582 }
583 if !b.iter().any(|&c| c == 0 || c == 0xc0 || c == 0xed)
584 && let Ok(s) = std::str::from_utf8(b)
585 {
586 return Ok(s.to_owned());
587 }
588 let mut units: Vec<u16> = Vec::with_capacity(b.len());
589 let mut i = 0;
590 while i < b.len() {
591 let c = b[i];
592 if c < 0x80 {
593 units.push(u16::from(c));
594 i += 1;
595 } else if c & 0xe0 == 0xc0 {
596 let c2 = *b.get(i + 1).ok_or(DecodeError::InvalidUtf8)?;
597 if c2 & 0xc0 != 0x80 {
598 return Err(DecodeError::InvalidUtf8);
599 }
600 units.push((u16::from(c & 0x1f) << 6) | u16::from(c2 & 0x3f));
601 i += 2;
602 } else if c & 0xf0 == 0xe0 {
603 let c2 = *b.get(i + 1).ok_or(DecodeError::InvalidUtf8)?;
604 let c3 = *b.get(i + 2).ok_or(DecodeError::InvalidUtf8)?;
605 if c2 & 0xc0 != 0x80 || c3 & 0xc0 != 0x80 {
606 return Err(DecodeError::InvalidUtf8);
607 }
608 units.push(
609 (u16::from(c & 0x0f) << 12) | (u16::from(c2 & 0x3f) << 6) | u16::from(c3 & 0x3f),
610 );
611 i += 3;
612 } else {
613 return Err(DecodeError::InvalidUtf8);
614 }
615 }
616 Ok(String::from_utf16_lossy(&units))
617}
618
619fn write_mutf8(w: &mut BytesMut, s: &str) -> EncodeResult {
621 let too_long = |len| EncodeError::LengthOverflow {
622 len,
623 max: u16::MAX as usize,
624 };
625 if s.bytes().all(|b| b != 0 && b < 0xf0) {
627 let n = u16::try_from(s.len()).map_err(|_| too_long(s.len()))?;
628 w.put_u16(n);
629 w.put_slice(s.as_bytes());
630 return Ok(());
631 }
632 let mut out = Vec::with_capacity(s.len() + 8);
633 for u in s.encode_utf16() {
634 match u {
635 0x0001..=0x007f => out.push(u as u8),
636 0x0000 | 0x0080..=0x07ff => {
637 out.push(0xc0 | (u >> 6) as u8);
638 out.push(0x80 | (u & 0x3f) as u8);
639 }
640 _ => {
641 out.push(0xe0 | (u >> 12) as u8);
642 out.push(0x80 | ((u >> 6) & 0x3f) as u8);
643 out.push(0x80 | (u & 0x3f) as u8);
644 }
645 }
646 }
647 let n = u16::try_from(out.len()).map_err(|_| too_long(out.len()))?;
648 w.put_u16(n);
649 w.put_slice(&out);
650 Ok(())
651}
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656
657 const HELLO_WORLD: &[u8] = &[
659 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,
660 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',
661 b'm', b'a', 0x00,
662 ];
663
664 #[test]
665 fn hello_world() {
666 let b = Bytes::from_static(HELLO_WORLD);
667 let raw = RawNbt::from_bytes(b.clone()).unwrap();
668 let t = raw.parse().unwrap().unwrap();
669 assert_eq!(t.name, "hello world");
670 let c = t.tag.as_compound().unwrap();
671 assert_eq!(c.get("name"), Some(&Tag::String("Bananrama".into())));
672 assert_eq!(RawNbt::from_named(&t).unwrap().as_bytes(), &b);
673 }
674
675 #[test]
676 fn optional_and_end() {
677 let b = Bytes::from_static(&[0x00, 0x01]);
678 let mut r = Reader::new(&b);
679 assert_eq!(RawNbt::read_optional(&mut r), Ok(None));
680 assert_eq!(r.remaining(), 1);
681 let b = Bytes::from_static(&[0x00]);
682 let raw = RawNbt::from_bytes(b).unwrap();
683 assert!(raw.is_end());
684 assert_eq!(raw.parse(), Ok(None));
685 }
686
687 #[test]
688 fn rejects_bad_input() {
689 let b = Bytes::from_static(&[0x0a, 0x00, 0x00, 0x0d, 0x00, 0x00]);
691 assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::InvalidNbtTag(13)));
692 let b = Bytes::from_static(&[0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05]);
694 assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::NbtEndList));
695 let b = Bytes::from_static(&[0x0b, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff]);
697 assert!(matches!(
698 RawNbt::from_bytes(b),
699 Err(DecodeError::LengthTooLarge { .. })
700 ));
701 let mut v = vec![0x09, 0x00, 0x00];
703 for _ in 0..600 {
704 v.extend_from_slice(&[0x09, 0x00, 0x00, 0x00, 0x01]);
705 }
706 let b = Bytes::from(v);
707 assert_eq!(
708 RawNbt::from_bytes(b),
709 Err(DecodeError::NbtTooDeep(MAX_DEPTH))
710 );
711 }
712
713 #[test]
714 fn modified_utf8() {
715 let s = "a\0b\u{e9}\u{1f600}";
716 let mut w = BytesMut::new();
717 write_mutf8(&mut w, s).unwrap();
718 assert_eq!(
720 &w[..],
721 &[
722 0x00, 0x0c, b'a', 0xc0, 0x80, b'b', 0xc3, 0xa9, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80
723 ]
724 );
725 assert_eq!(decode_mutf8(&w[2..]).unwrap(), s);
726 assert_eq!(decode_mutf8(&[0xc3]), Err(DecodeError::InvalidUtf8));
727 assert_eq!(
729 decode_mutf8(&[0xf0, 0x9f, 0x98, 0x80]).unwrap(),
730 "\u{1f600}"
731 );
732 assert_eq!(decode_mutf8(&[0xf8, 0x80]), Err(DecodeError::InvalidUtf8));
733 }
734}