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 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 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 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 #[inline]
97 pub fn write(&self, w: &mut BytesMut) {
98 w.put_slice(&self.0);
99 }
100
101 #[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 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
149pub struct AnonNbt(Bytes);
150
151impl AnonNbt {
152 pub const END: AnonNbt = AnonNbt(Bytes::from_static(&[0]));
154
155 #[inline]
157 pub fn as_bytes(&self) -> &Bytes {
158 &self.0
159 }
160
161 #[inline]
163 pub fn is_end(&self) -> bool {
164 self.0.first() == Some(&tag::END)
165 }
166
167 #[inline]
169 pub fn tag_type(&self) -> u8 {
170 self.0.first().copied().unwrap_or(tag::END)
171 }
172
173 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 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 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 #[inline]
203 pub fn write(&self, w: &mut BytesMut) {
204 w.put_slice(&self.0);
205 }
206
207 #[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 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 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
252fn 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 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
313fn 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
319fn 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#[derive(Debug, Clone, PartialEq)]
348pub struct NamedTag {
349 pub name: String,
351 pub tag: Tag,
353}
354
355#[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#[derive(Debug, Clone, PartialEq, Default)]
375pub struct List {
376 pub elem_type: u8,
378 pub items: Vec<Tag>,
380}
381
382#[derive(Debug, Clone, PartialEq, Default)]
384pub struct Compound(pub Vec<(String, Tag)>);
385
386impl Compound {
387 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 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 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
558fn 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
565pub fn decode_mutf8(b: &[u8]) -> DecodeResult<String> {
567 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
610fn 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 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 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 let b = Bytes::from_static(&[0x0a, 0x00, 0x00, 0x0d, 0x00, 0x00]);
682 assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::InvalidNbtTag(13)));
683 let b = Bytes::from_static(&[0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05]);
685 assert_eq!(RawNbt::from_bytes(b), Err(DecodeError::NbtEndList));
686 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 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 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 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}