simdnbt 0.10.0

an unnecessarily fast nbt decoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! The owned variant of NBT. This is useful if you're writing NBT or if you
//! can't keep a reference to the original data.

mod compound;
mod list;
#[cfg(feature = "serde")]
mod serde_impl;

use std::{io::Cursor, ops::Deref};

pub use self::{compound::NbtCompound, list::NbtList};
use crate::{
    Error, Mutf8Str,
    common::{
        BYTE_ARRAY_ID, BYTE_ID, COMPOUND_ID, DOUBLE_ID, END_ID, FLOAT_ID, INT_ARRAY_ID, INT_ID,
        LIST_ID, LONG_ARRAY_ID, LONG_ID, MAX_DEPTH, SHORT_ID, STRING_ID, read_int_array,
        read_long_array, read_string, read_with_u32_length, slice_into_u8_big_endian, write_string,
    },
    error::NonRootError,
    fastvec::{FastVec, FastVecFromVec},
    mutf8::Mutf8String,
    reader::{Reader, ReaderFromCursor},
};

/// Read a normal root NBT compound. This is either empty or has a name and
/// compound tag.
///
/// Returns `Ok(Nbt::None)` if there is no data.
pub fn read(data: &mut Cursor<&[u8]>) -> Result<Nbt, Error> {
    let mut reader = ReaderFromCursor::new(data);
    Nbt::read(&mut reader)
}
/// Read a root NBT compound, but without reading the name. This is used in
/// Minecraft when reading NBT over the network.
///
/// This is similar to [`read_tag`], but returns an [`Nbt`] instead
/// (guaranteeing it'll be either empty or a compound).
pub fn read_unnamed(data: &mut Cursor<&[u8]>) -> Result<Nbt, Error> {
    let mut reader = ReaderFromCursor::new(data);
    Nbt::read_unnamed(&mut reader)
}
/// Read a compound tag. This may have any number of items.
pub fn read_compound(data: &mut Cursor<&[u8]>) -> Result<NbtCompound, NonRootError> {
    let mut reader = ReaderFromCursor::new(data);
    NbtCompound::read(&mut reader)
}
/// Read an NBT tag, without reading its name. This may be any type of tag
/// except for an end tag. If you need to be able to handle end tags, use
/// [`read_optional_tag`].
pub fn read_tag(data: &mut Cursor<&[u8]>) -> Result<NbtTag, NonRootError> {
    let mut reader = ReaderFromCursor::new(data);
    NbtTag::read(&mut reader)
}
/// Read any NBT tag, without reading its name. This may be any type of tag,
/// including an end tag.
///
/// Returns `Ok(None)` if there is no data.
pub fn read_optional_tag(data: &mut Cursor<&[u8]>) -> Result<Option<NbtTag>, NonRootError> {
    let mut reader = ReaderFromCursor::new(data);
    NbtTag::read_optional(&mut reader)
}

/// A complete NBT container. This contains a name and a compound tag.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BaseNbt {
    name: Mutf8String,
    tag: NbtCompound,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub enum Nbt {
    Some(BaseNbt),
    #[default]
    None,
}

impl Nbt {
    pub fn new(name: Mutf8String, tag: NbtCompound) -> Self {
        Self::Some(BaseNbt { name, tag })
    }

    /// Reads NBT from the given data. Returns `Ok(Nbt::None)` if there is no
    /// data.
    fn read(data: &mut Reader<'_>) -> Result<Nbt, Error> {
        let root_type = data.read_u8().map_err(|_| Error::UnexpectedEof)?;
        if root_type == END_ID {
            return Ok(Nbt::None);
        }
        if root_type != COMPOUND_ID {
            return Err(Error::InvalidRootType(root_type));
        }
        let name = read_string(data)?.to_owned();
        let tag = NbtCompound::read(data)?;

        Ok(Nbt::Some(BaseNbt { name, tag }))
    }

    fn read_unnamed(data: &mut Reader<'_>) -> Result<Nbt, Error> {
        let root_type = data.read_u8().map_err(|_| Error::UnexpectedEof)?;
        if root_type == END_ID {
            return Ok(Nbt::None);
        }
        if root_type != COMPOUND_ID {
            return Err(Error::InvalidRootType(root_type));
        }
        let tag = NbtCompound::read(data)?;

        Ok(Nbt::Some(BaseNbt {
            name: Mutf8String::from(""),
            tag,
        }))
    }

    pub fn write(&self, data: &mut Vec<u8>) {
        match self {
            Nbt::Some(nbt) => nbt.write(data),
            Nbt::None => {
                data.push(END_ID);
            }
        }
    }

    pub fn write_unnamed(&self, data: &mut Vec<u8>) {
        match self {
            Nbt::Some(nbt) => nbt.write_unnamed(data),
            Nbt::None => {
                data.push(END_ID);
            }
        }
    }

    pub fn unwrap(self) -> BaseNbt {
        match self {
            Nbt::Some(nbt) => nbt,
            Nbt::None => panic!("called `OptionalNbt::unwrap()` on a `None` value"),
        }
    }

    pub fn unwrap_or<'a>(&'a self, default: &'a BaseNbt) -> &'a BaseNbt {
        match self {
            Nbt::Some(nbt) => nbt,
            Nbt::None => default,
        }
    }

    pub fn is_some(&self) -> bool {
        match self {
            Nbt::Some(_) => true,
            Nbt::None => false,
        }
    }

    pub fn is_none(&self) -> bool {
        !self.is_some()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&Mutf8Str, &NbtTag)> {
        const EMPTY: &NbtCompound = &NbtCompound { values: Vec::new() };

        if let Nbt::Some(nbt) = self {
            nbt.iter()
        } else {
            EMPTY.iter()
        }
    }
}
impl Deref for Nbt {
    type Target = BaseNbt;

    fn deref(&self) -> &Self::Target {
        const EMPTY: &BaseNbt = &BaseNbt {
            name: Mutf8String { vec: Vec::new() },
            tag: NbtCompound { values: Vec::new() },
        };

        match self {
            Nbt::Some(nbt) => nbt,
            Nbt::None => EMPTY,
        }
    }
}

impl IntoIterator for Nbt {
    type Item = (Mutf8String, NbtTag);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        const EMPTY: NbtCompound = NbtCompound { values: Vec::new() };

        match self {
            Nbt::Some(nbt) => nbt.tag.into_iter(),
            Nbt::None => EMPTY.into_iter(),
        }
    }
}

impl BaseNbt {
    pub fn new(name: impl Into<Mutf8String>, tag: NbtCompound) -> Self {
        let name = name.into();
        Self { name, tag }
    }

    /// Get the name of the NBT compound. This is often an empty string.
    pub fn name(&self) -> &Mutf8Str {
        &self.name
    }

    /// Writes the NBT to the given buffer.
    pub fn write(&self, data: &mut Vec<u8>) {
        self.write_fastvec(&mut FastVecFromVec::new(data));
    }

    /// Writes the NBT to the given buffer.
    fn write_fastvec(&self, data: &mut FastVec<u8>) {
        data.push(COMPOUND_ID);
        write_string(data, &self.name);
        self.tag.write_fastvec(data);
    }

    pub fn write_unnamed(&self, data: &mut Vec<u8>) {
        data.push(COMPOUND_ID);
        self.tag.write(data);
    }

    pub fn as_compound(self) -> NbtCompound {
        self.tag
    }
}

impl IntoIterator for BaseNbt {
    type Item = (Mutf8String, NbtTag);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.tag.into_iter()
    }
}

impl Deref for BaseNbt {
    type Target = NbtCompound;

    fn deref(&self) -> &Self::Target {
        &self.tag
    }
}

/// A single NBT tag.
#[repr(u8)]
#[derive(Debug, Clone, PartialEq)]
pub enum NbtTag {
    Byte(i8) = BYTE_ID,
    Short(i16) = SHORT_ID,
    Int(i32) = INT_ID,
    Long(i64) = LONG_ID,
    Float(f32) = FLOAT_ID,
    Double(f64) = DOUBLE_ID,
    ByteArray(Vec<u8>) = BYTE_ARRAY_ID,
    String(Mutf8String) = STRING_ID,
    List(NbtList) = LIST_ID,
    Compound(NbtCompound) = COMPOUND_ID,
    IntArray(Vec<i32>) = INT_ARRAY_ID,
    LongArray(Vec<i64>) = LONG_ARRAY_ID,
}
impl NbtTag {
    /// Get the numerical ID of the tag type.
    #[inline]
    pub fn id(&self) -> u8 {
        // SAFETY: Because `Self` is marked `repr(u8)`, its layout is a `repr(C)`
        // `union` between `repr(C)` structs, each of which has the `u8`
        // discriminant as its first field, so we can read the discriminant
        // without offsetting the pointer.
        unsafe { *<*const _>::from(self).cast::<u8>() }
    }

    #[inline(always)]
    fn read_with_type(
        data: &mut Reader<'_>,
        tag_type: u8,
        depth: usize,
    ) -> Result<Self, NonRootError> {
        match tag_type {
            BYTE_ID => Ok(NbtTag::Byte(
                data.read_i8().map_err(|_| NonRootError::unexpected_eof())?,
            )),
            SHORT_ID => Ok(NbtTag::Short(
                data.read_i16()
                    .map_err(|_| NonRootError::unexpected_eof())?,
            )),
            INT_ID => Ok(NbtTag::Int(
                data.read_i32()
                    .map_err(|_| NonRootError::unexpected_eof())?,
            )),
            LONG_ID => Ok(NbtTag::Long(
                data.read_i64()
                    .map_err(|_| NonRootError::unexpected_eof())?,
            )),
            FLOAT_ID => Ok(NbtTag::Float(
                data.read_f32()
                    .map_err(|_| NonRootError::unexpected_eof())?,
            )),
            DOUBLE_ID => Ok(NbtTag::Double(
                data.read_f64()
                    .map_err(|_| NonRootError::unexpected_eof())?,
            )),
            BYTE_ARRAY_ID => Ok(NbtTag::ByteArray(read_with_u32_length(data, 1)?.to_owned())),
            STRING_ID => Ok(NbtTag::String(read_string(data)?.to_owned())),
            LIST_ID => Ok(NbtTag::List(NbtList::read(data, depth + 1)?)),
            COMPOUND_ID => Ok(NbtTag::Compound(NbtCompound::read_with_depth(
                data,
                depth + 1,
            )?)),
            INT_ARRAY_ID => Ok(NbtTag::IntArray(read_int_array(data)?.to_vec())),
            LONG_ARRAY_ID => Ok(NbtTag::LongArray(read_long_array(data)?.to_vec())),
            _ => Err(NonRootError::unknown_tag_id(tag_type)),
        }
    }

    fn read(data: &mut Reader<'_>) -> Result<Self, NonRootError> {
        let tag_type = data.read_u8().map_err(|_| NonRootError::unexpected_eof())?;
        Self::read_with_type(data, tag_type, 0)
    }

    fn read_optional(data: &mut Reader<'_>) -> Result<Option<Self>, NonRootError> {
        let tag_type = data.read_u8().map_err(|_| NonRootError::unexpected_eof())?;
        if tag_type == END_ID {
            return Ok(None);
        }
        Ok(Some(Self::read_with_type(data, tag_type, 0)?))
    }

    /// Write to the data without checking that there's enough space in it.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it doesn't check that there's enough
    /// space in the data. 4 bytes MUST be reserved before calling this
    /// function.
    #[inline]
    unsafe fn write_without_tag_type_unchecked(&self, data: &mut FastVec<u8>) {
        match self {
            NbtTag::Byte(byte) => unsafe {
                data.push_unchecked(*byte as u8);
            },
            NbtTag::Short(short) => unsafe {
                data.extend_from_slice_unchecked(&short.to_be_bytes());
            },
            NbtTag::Int(int) => unsafe {
                data.extend_from_slice_unchecked(&int.to_be_bytes());
            },
            NbtTag::Long(long) => {
                data.extend_from_slice(&long.to_be_bytes());
            }
            NbtTag::Float(float) => unsafe {
                data.extend_from_slice_unchecked(&float.to_be_bytes());
            },
            NbtTag::Double(double) => {
                data.extend_from_slice(&double.to_be_bytes());
            }
            NbtTag::ByteArray(byte_array) => {
                unsafe {
                    data.extend_from_slice_unchecked(&(byte_array.len() as u32).to_be_bytes());
                }
                data.extend_from_slice(byte_array);
            }
            NbtTag::String(string) => {
                write_string(data, string);
            }
            NbtTag::List(list) => {
                list.write_fastvec(data);
            }
            NbtTag::Compound(compound) => {
                compound.write_fastvec(data);
            }
            NbtTag::IntArray(int_array) => {
                unsafe {
                    data.extend_from_slice_unchecked(&(int_array.len() as u32).to_be_bytes());
                }
                data.extend_from_slice(&slice_into_u8_big_endian(int_array));
            }
            NbtTag::LongArray(long_array) => {
                unsafe {
                    data.extend_from_slice_unchecked(&(long_array.len() as u32).to_be_bytes());
                }
                data.extend_from_slice(&slice_into_u8_big_endian(long_array));
            }
        }
    }

    pub fn write(&self, data: &mut Vec<u8>) {
        self.write_fastvec(&mut FastVecFromVec::new(data));
    }

    fn write_fastvec(&self, data: &mut FastVec<u8>) {
        data.reserve(1 + 4);
        // SAFETY: We just reserved enough space for the tag ID and 4 bytes of tag data.
        unsafe {
            data.push_unchecked(self.id());
            self.write_without_tag_type_unchecked(data);
        }
    }

    pub fn byte(&self) -> Option<i8> {
        match self {
            NbtTag::Byte(byte) => Some(*byte),
            _ => None,
        }
    }
    pub fn byte_mut(&mut self) -> Option<&mut i8> {
        match self {
            NbtTag::Byte(byte) => Some(byte),
            _ => None,
        }
    }
    pub fn into_byte(self) -> Option<i8> {
        match self {
            NbtTag::Byte(byte) => Some(byte),
            _ => None,
        }
    }

    pub fn short(&self) -> Option<i16> {
        match self {
            NbtTag::Short(short) => Some(*short),
            _ => None,
        }
    }
    pub fn short_mut(&mut self) -> Option<&mut i16> {
        match self {
            NbtTag::Short(short) => Some(short),
            _ => None,
        }
    }
    pub fn into_short(self) -> Option<i16> {
        match self {
            NbtTag::Short(short) => Some(short),
            _ => None,
        }
    }

    pub fn int(&self) -> Option<i32> {
        match self {
            NbtTag::Int(int) => Some(*int),
            _ => None,
        }
    }
    pub fn int_mut(&mut self) -> Option<&mut i32> {
        match self {
            NbtTag::Int(int) => Some(int),
            _ => None,
        }
    }
    pub fn into_int(self) -> Option<i32> {
        match self {
            NbtTag::Int(int) => Some(int),
            _ => None,
        }
    }

    pub fn long(&self) -> Option<i64> {
        match self {
            NbtTag::Long(long) => Some(*long),
            _ => None,
        }
    }
    pub fn long_mut(&mut self) -> Option<&mut i64> {
        match self {
            NbtTag::Long(long) => Some(long),
            _ => None,
        }
    }
    pub fn into_long(self) -> Option<i64> {
        match self {
            NbtTag::Long(long) => Some(long),
            _ => None,
        }
    }

    pub fn float(&self) -> Option<f32> {
        match self {
            NbtTag::Float(float) => Some(*float),
            _ => None,
        }
    }
    pub fn float_mut(&mut self) -> Option<&mut f32> {
        match self {
            NbtTag::Float(float) => Some(float),
            _ => None,
        }
    }
    pub fn into_float(self) -> Option<f32> {
        match self {
            NbtTag::Float(float) => Some(float),
            _ => None,
        }
    }

    pub fn double(&self) -> Option<f64> {
        match self {
            NbtTag::Double(double) => Some(*double),
            _ => None,
        }
    }
    pub fn double_mut(&mut self) -> Option<&mut f64> {
        match self {
            NbtTag::Double(double) => Some(double),
            _ => None,
        }
    }
    pub fn into_double(self) -> Option<f64> {
        match self {
            NbtTag::Double(double) => Some(double),
            _ => None,
        }
    }

    pub fn byte_array(&self) -> Option<&[u8]> {
        match self {
            NbtTag::ByteArray(byte_array) => Some(byte_array),
            _ => None,
        }
    }
    pub fn byte_array_mut(&mut self) -> Option<&mut Vec<u8>> {
        match self {
            NbtTag::ByteArray(byte_array) => Some(byte_array),
            _ => None,
        }
    }
    pub fn into_byte_array(self) -> Option<Vec<u8>> {
        match self {
            NbtTag::ByteArray(byte_array) => Some(byte_array),
            _ => None,
        }
    }

    pub fn string(&self) -> Option<&Mutf8Str> {
        match self {
            NbtTag::String(string) => Some(string),
            _ => None,
        }
    }
    pub fn string_mut(&mut self) -> Option<&mut Mutf8String> {
        match self {
            NbtTag::String(string) => Some(string),
            _ => None,
        }
    }
    pub fn into_string(self) -> Option<Mutf8String> {
        match self {
            NbtTag::String(string) => Some(string),
            _ => None,
        }
    }

    pub fn list(&self) -> Option<&NbtList> {
        match self {
            NbtTag::List(list) => Some(list),
            _ => None,
        }
    }
    pub fn list_mut(&mut self) -> Option<&mut NbtList> {
        match self {
            NbtTag::List(list) => Some(list),
            _ => None,
        }
    }
    pub fn into_list(self) -> Option<NbtList> {
        match self {
            NbtTag::List(list) => Some(list),
            _ => None,
        }
    }

    pub fn compound(&self) -> Option<&NbtCompound> {
        match self {
            NbtTag::Compound(compound) => Some(compound),
            _ => None,
        }
    }
    pub fn compound_mut(&mut self) -> Option<&mut NbtCompound> {
        match self {
            NbtTag::Compound(compound) => Some(compound),
            _ => None,
        }
    }
    pub fn into_compound(self) -> Option<NbtCompound> {
        match self {
            NbtTag::Compound(compound) => Some(compound),
            _ => None,
        }
    }

    pub fn int_array(&self) -> Option<&[i32]> {
        match self {
            NbtTag::IntArray(int_array) => Some(int_array),
            _ => None,
        }
    }
    pub fn int_array_mut(&mut self) -> Option<&mut Vec<i32>> {
        match self {
            NbtTag::IntArray(int_array) => Some(int_array),
            _ => None,
        }
    }
    pub fn into_int_array(self) -> Option<Vec<i32>> {
        match self {
            NbtTag::IntArray(int_array) => Some(int_array),
            _ => None,
        }
    }

    pub fn long_array(&self) -> Option<&[i64]> {
        match self {
            NbtTag::LongArray(long_array) => Some(long_array),
            _ => None,
        }
    }
    pub fn long_array_mut(&mut self) -> Option<&mut Vec<i64>> {
        match self {
            NbtTag::LongArray(long_array) => Some(long_array),
            _ => None,
        }
    }
    pub fn into_long_array(self) -> Option<Vec<i64>> {
        match self {
            NbtTag::LongArray(long_array) => Some(long_array),
            _ => None,
        }
    }
}

impl From<NbtCompound> for BaseNbt {
    fn from(tag: NbtCompound) -> Self {
        Self {
            name: Mutf8String::from(""),
            tag,
        }
    }
}
impl From<Nbt> for NbtTag {
    fn from(value: Nbt) -> Self {
        match value {
            Nbt::Some(nbt) => NbtTag::Compound(nbt.tag),
            Nbt::None => NbtTag::Compound(NbtCompound::new()),
        }
    }
}
impl From<NbtTag> for NbtCompound {
    /// Convert `NbtTag` to `NbtCompound`.
    ///
    /// Non-compound tags and compounds tags with only one empty string key are
    /// wrapped in a compound with an empty string key
    fn from(tag: NbtTag) -> Self {
        match tag {
            NbtTag::Compound(compound) if !(compound.len() == 1 && compound.contains("")) => {
                compound
            }
            tag => NbtCompound {
                values: vec![(Mutf8String::from(""), tag)],
            },
        }
    }
}
impl From<NbtList> for NbtTag {
    fn from(l: NbtList) -> Self {
        Self::List(l)
    }
}
impl From<NbtCompound> for NbtTag {
    fn from(c: NbtCompound) -> Self {
        Self::Compound(c)
    }
}
impl<const N: usize, T: Into<NbtTag>> From<[T; N]> for NbtTag {
    fn from(value: [T; N]) -> Self {
        NbtList::from(value).into()
    }
}
impl From<&str> for NbtTag {
    fn from(s: &str) -> Self {
        Self::String(Mutf8String::from(s))
    }
}
impl From<i32> for NbtTag {
    fn from(i: i32) -> Self {
        Self::Int(i)
    }
}
impl From<i64> for NbtTag {
    fn from(i: i64) -> Self {
        Self::Long(i)
    }
}
impl From<f32> for NbtTag {
    fn from(f: f32) -> Self {
        Self::Float(f)
    }
}
impl From<f64> for NbtTag {
    fn from(f: f64) -> Self {
        Self::Double(f)
    }
}

impl<const N: usize, K: Into<Mutf8String>> From<[(K, NbtTag); N]> for NbtTag {
    fn from(a: [(K, NbtTag); N]) -> Self {
        NbtCompound::from(a).into()
    }
}

#[cfg(test)]
mod tests {
    use std::io::Read;

    use byteorder::{BE, WriteBytesExt};
    use flate2::read::GzDecoder;

    use super::*;
    use crate::ToNbtTag;

    #[test]
    fn hello_world() {
        let nbt = super::read(&mut Cursor::new(include_bytes!(
            "../../tests/hello_world.nbt"
        )))
        .unwrap()
        .unwrap();

        assert_eq!(
            nbt.string("name"),
            Some(Mutf8Str::from_str("Bananrama").as_ref())
        );
        assert_eq!(nbt.name().to_str(), "hello world");
    }

    #[test]
    fn simple_player() {
        let src = include_bytes!("../../tests/simple_player.dat").to_vec();
        let mut src_slice = src.as_slice();
        let mut decoded_src_decoder = GzDecoder::new(&mut src_slice);
        let mut decoded_src = Vec::new();
        decoded_src_decoder.read_to_end(&mut decoded_src).unwrap();
        let nbt = super::read(&mut Cursor::new(&decoded_src))
            .unwrap()
            .unwrap();

        assert_eq!(nbt.int("PersistentId"), Some(1946940766));
        assert_eq!(nbt.list("Rotation").unwrap().floats().unwrap().len(), 2);
    }

    #[test]
    fn complex_player() {
        let src = include_bytes!("../../tests/complex_player.dat").to_vec();
        let mut src_slice = src.as_slice();
        let mut decoded_src_decoder = GzDecoder::new(&mut src_slice);
        let mut decoded_src = Vec::new();
        decoded_src_decoder.read_to_end(&mut decoded_src).unwrap();
        let nbt = super::read(&mut Cursor::new(&decoded_src))
            .unwrap()
            .unwrap();

        assert_eq!(nbt.float("foodExhaustionLevel").unwrap() as u32, 2);
        assert_eq!(nbt.list("Rotation").unwrap().floats().unwrap().len(), 2);
    }

    #[test]
    fn read_write_complex_player() {
        let src = include_bytes!("../../tests/complex_player.dat").to_vec();
        let mut src_slice = src.as_slice();
        let mut decoded_src_decoder = GzDecoder::new(&mut src_slice);
        let mut decoded_src = Vec::new();
        decoded_src_decoder.read_to_end(&mut decoded_src).unwrap();
        let nbt = super::read(&mut Cursor::new(&decoded_src))
            .unwrap()
            .unwrap();

        let mut out = Vec::new();
        nbt.write(&mut out);
        let nbt = super::read(&mut Cursor::new(&out)).unwrap().unwrap();

        assert_eq!(nbt.float("foodExhaustionLevel").unwrap() as u32, 2);
        assert_eq!(nbt.list("Rotation").unwrap().floats().unwrap().len(), 2);
    }

    #[test]
    fn inttest_1023() {
        let nbt = super::read(&mut Cursor::new(include_bytes!(
            "../../tests/inttest1023.nbt"
        )))
        .unwrap()
        .unwrap();

        let ints = nbt.list("").unwrap().ints().unwrap();

        for (i, &item) in ints.iter().enumerate() {
            assert_eq!(i as i32, item);
        }
        assert_eq!(ints.len(), 1023);
    }

    #[test]
    fn inttest_1024() {
        let mut data = Vec::new();
        data.write_u8(COMPOUND_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(LIST_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(INT_ID).unwrap();
        data.write_i32::<BE>(1024).unwrap();
        for i in 0..1024 {
            data.write_i32::<BE>(i).unwrap();
        }
        data.write_u8(END_ID).unwrap();

        let nbt = super::read(&mut Cursor::new(&data)).unwrap().unwrap();
        let ints = nbt.list("").unwrap().ints().unwrap();
        for (i, &item) in ints.iter().enumerate() {
            assert_eq!(i as i32, item);
        }
        assert_eq!(ints.len(), 1024);
    }

    #[test]
    fn inttest_1021() {
        let mut data = Vec::new();
        data.write_u8(COMPOUND_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(LIST_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(INT_ID).unwrap();
        data.write_i32::<BE>(1021).unwrap();
        for i in 0..1021 {
            data.write_i32::<BE>(i).unwrap();
        }
        data.write_u8(END_ID).unwrap();

        let nbt = super::read(&mut Cursor::new(&data)).unwrap().unwrap();
        let ints = nbt.list("").unwrap().ints().unwrap();
        for (i, &item) in ints.iter().enumerate() {
            assert_eq!(i as i32, item);
        }
        assert_eq!(ints.len(), 1021);
    }

    #[test]
    fn longtest_1023() {
        let mut data = Vec::new();
        data.write_u8(COMPOUND_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(LIST_ID).unwrap();
        data.write_u16::<BE>(0).unwrap();
        data.write_u8(LONG_ID).unwrap();
        data.write_i32::<BE>(1023).unwrap();
        for i in 0..1023 {
            data.write_i64::<BE>(i).unwrap();
        }
        data.write_u8(END_ID).unwrap();

        let nbt = super::read(&mut Cursor::new(&data)).unwrap().unwrap();
        let ints = nbt.list("").unwrap().longs().unwrap();
        for (i, &item) in ints.iter().enumerate() {
            assert_eq!(i as i64, item);
        }
        assert_eq!(ints.len(), 1023);
    }

    #[test]
    fn equals_can_fail() {
        let src = include_bytes!("../../tests/complex_player.dat").to_vec();
        let mut src_slice = src.as_slice();
        let mut decoded_src_decoder = GzDecoder::new(&mut src_slice);
        let mut decoded_src = Vec::new();
        decoded_src_decoder.read_to_end(&mut decoded_src).unwrap();
        let nbt = super::read(&mut Cursor::new(&decoded_src))
            .unwrap()
            .unwrap()
            .as_compound();
        let mut modified_nbt = nbt.clone();
        modified_nbt.insert("foodExhaustionLevel", 2.0f32);

        assert_ne!(nbt, modified_nbt);
    }

    #[test]
    fn write_compound() {
        let nbt = BaseNbt {
            name: "".into(),
            tag: NbtCompound { values: vec![] },
        };
        BaseNbt::write_unnamed(&nbt, &mut Vec::new());
    }

    #[test]
    fn test_convert_tag_to_compound() {
        assert_eq!(
            NbtCompound::from(1i32.to_nbt_tag()),
            NbtCompound::from_values(vec![(Mutf8String::from(""), 1i32.to_nbt_tag())])
        );

        let compound =
            NbtCompound::from_values(vec![(Mutf8String::from("key"), 1i32.to_nbt_tag())]);
        assert_eq!(NbtCompound::from(compound.clone().to_nbt_tag()), compound);

        let compound = NbtCompound::from_values(vec![(Mutf8String::from(""), 1i32.to_nbt_tag())]);
        assert_eq!(
            NbtCompound::from(compound.clone().to_nbt_tag()),
            NbtCompound::from_values(vec![(Mutf8String::from(""), compound.to_nbt_tag())])
        )
    }
}