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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
use crate::{
    raw,
    snbt::{self, SnbtError},
    NbtReprError,
    NbtStructureError,
};
use std::{
    borrow::{Borrow, BorrowMut, Cow},
    fmt::{self, Debug, Display, Formatter},
    hash::Hash,
    ops::{Deref, DerefMut, Index, IndexMut},
    str::FromStr,
};

#[allow(deprecated)]
use crate::NbtRepr;

/// The hash map type utilized in this crate. If the feature `preserve_order` is enabled, then this
/// will use the `IndexMap` type from the crate <https://docs.rs/indexmap/latest/indexmap/>.
/// Otherwise, this type defaults to `std`'s `HashMap`.
#[cfg(feature = "preserve_order")]
pub type Map<T> = indexmap::IndexMap<String, T>;

/// The hash map type utilized in this crate. If the feature `preserve_order` is enabled, then this
/// will use the `IndexMap` type from the crate <https://docs.rs/indexmap/latest/indexmap/>.
/// Otherwise, this type defaults to `std`'s `HashMap`.
#[cfg(not(feature = "preserve_order"))]
pub type Map<T> = std::collections::HashMap<String, T>;

/// The generic NBT tag type, containing all supported tag variants which wrap around a corresponding
/// rust type.
///
/// This type will implement both `Serialize` and `Deserialize` when the serde feature is enabled,
/// however this type should still be read and written with the utilities in the [`io`] module when
/// possible if speed is the main priority. When linking into the serde ecosystem, we ensured that all
/// tag types would have their data inlined into the resulting NBT output of our Serializer. Because of
/// this, NBT tags are only compatible with self-describing formats, and also have slower deserialization
/// implementations due to this restriction.
///
/// [`io`]: crate::io
#[derive(Clone, PartialEq)]
pub enum NbtTag {
    /// A signed, one-byte integer.
    Byte(i8),
    /// A signed, two-byte integer.
    Short(i16),
    /// A signed, four-byte integer.
    Int(i32),
    /// A signed, eight-byte integer.
    Long(i64),
    /// A 32-bit floating point value.
    Float(f32),
    /// A 64-bit floating point value.
    Double(f64),
    /// An array (vec) of one-byte integers. Minecraft treats this as an array of signed bytes.
    ByteArray(Vec<i8>),
    /// A UTF-8 string.
    String(String),
    /// An NBT tag list.
    List(NbtList),
    /// An NBT tag compound.
    Compound(NbtCompound),
    /// An array (vec) of signed, four-byte integers.
    IntArray(Vec<i32>),
    /// An array (vec) of signed, eight-byte integers.
    LongArray(Vec<i64>),
}

impl NbtTag {
    /// Returns the single character denoting this tag's type, or `None` if this tag has no type
    /// specifier.
    ///
    /// # Examples
    ///
    /// ```
    /// # use quartz_nbt::NbtTag;
    /// assert_eq!(NbtTag::Long(10).type_specifier(), Some("L"));
    /// assert_eq!(NbtTag::IntArray(Vec::new()).type_specifier(), Some("I"));
    /// assert_eq!(NbtTag::String(String::new()).type_specifier(), None);
    /// ```
    pub fn type_specifier(&self) -> Option<&'static str> {
        match self {
            NbtTag::Byte(_) => Some("B"),
            NbtTag::Short(_) => Some("S"),
            NbtTag::Long(_) => Some("L"),
            NbtTag::Float(_) => Some("F"),
            NbtTag::Double(_) => Some("D"),
            NbtTag::ByteArray(_) => Some("B"),
            NbtTag::IntArray(_) => Some("I"),
            NbtTag::LongArray(_) => Some("L"),
            _ => None,
        }
    }

    pub(crate) fn tag_name(&self) -> &'static str {
        match self {
            NbtTag::Byte(_) => "Byte",
            NbtTag::Short(_) => "Short",
            NbtTag::Int(_) => "Int",
            NbtTag::Long(_) => "Long",
            NbtTag::Float(_) => "Float",
            NbtTag::Double(_) => "Double",
            NbtTag::String(_) => "String",
            NbtTag::ByteArray(_) => "ByteArray",
            NbtTag::IntArray(_) => "IntArray",
            NbtTag::LongArray(_) => "LongArray",
            NbtTag::Compound(_) => "Compound",
            NbtTag::List(_) => "List",
        }
    }

    /// Converts this NBT tag into a valid, parsable SNBT string with no extraneous spacing. This
    /// method should not be used to generate user-facing text, rather [`to_pretty_snbt`] should
    /// be used instead. If finer control over the output is desired, then the tag can be formatted
    /// via the standard library's [`format!`] macro to pass additional formatting parameters.
    ///
    /// # Examples
    ///
    /// Simple primitive conversion:
    ///
    /// ```
    /// # use quartz_nbt::NbtTag;
    /// assert_eq!(NbtTag::Byte(5).to_snbt(), "5B");
    /// assert_eq!(NbtTag::String("\"Quoted text\"".to_owned()).to_snbt(), "'\"Quoted text\"'");
    /// ```
    ///
    /// More complex tag conversion:
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("foo", vec![-1_i64, -3_i64, -5_i64]);
    /// assert_eq!(NbtTag::Compound(compound).to_snbt(), "{foo:[L;-1,-3,-5]}");
    /// ```
    ///
    /// [`to_pretty_snbt`]: crate::NbtTag::to_pretty_snbt
    /// [`format!`]: std::format
    pub fn to_snbt(&self) -> String {
        format!("{:?}", self)
    }

    /// Converts this NBT tag into a valid, parsable SNBT string with extra spacing for
    /// readability. If a more compact SNBT representation is desired, then use [`to_snbt`]. If
    /// finer control over the output is desired, then the tag can be formatted via the standard
    /// library's [`format!`] macro to pass additional formatting parameters.
    ///
    /// # Examples
    ///
    /// Simple primitive conversion:
    ///
    /// ```
    /// # use quartz_nbt::NbtTag;
    /// assert_eq!(NbtTag::Byte(5).to_pretty_snbt(), "5B");
    /// assert_eq!(
    ///     NbtTag::String("\"Quoted text\"".to_owned()).to_pretty_snbt(),
    ///     "'\"Quoted text\"'"
    /// );
    /// ```
    ///
    /// More complex tag conversion:
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("foo", vec![-1_i64, -3_i64, -5_i64]);
    /// let repr =
    /// r#"{
    ///     foo: [
    ///         L;
    ///         -1,
    ///         -3,
    ///         -5
    ///     ]
    /// }"#;
    /// assert_eq!(NbtTag::Compound(compound).to_pretty_snbt(), repr);
    /// ```
    ///
    /// [`to_snbt`]: crate::NbtTag::to_snbt
    /// [`format!`]: std::format
    pub fn to_pretty_snbt(&self) -> String {
        format!("{:#?}", self)
    }

    /// Returns whether or not the given string needs to be quoted due to non-alphanumeric or otherwise
    /// non-standard characters.
    #[inline]
    pub fn should_quote(string: &str) -> bool {
        if string.is_empty() {
            return true;
        }

        if let Some(first) = string.chars().next() {
            if first.is_whitespace() || first.is_ascii_digit() || first == '-' {
                return true;
            }
        }

        if let Some(last) = string.chars().next_back() {
            if last.is_whitespace() {
                return true;
            }
        }

        for ch in string.chars() {
            if ch == ':'
                || ch == ','
                || ch == '"'
                || ch == '\''
                || ch == '{'
                || ch == '}'
                || ch == '['
                || ch == ']'
                || ch == '\\'
                || ch == '\n'
                || ch == '\r'
                || ch == '\t'
            {
                return true;
            }
        }

        false
    }

    /// Wraps the given string in quotes and escapes any quotes contained in the original string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use quartz_nbt::NbtTag;
    /// use std::borrow::Cow;
    ///
    /// assert_eq!(NbtTag::string_to_snbt("string"), Cow::Borrowed("string"));
    /// assert_eq!(
    ///     NbtTag::string_to_snbt("\\\n\r\t'\""),
    ///     Cow::<str>::Owned(String::from(r#"'\\\n\r\t\'"'"#))
    /// );
    /// ```
    pub fn string_to_snbt(string: &str) -> Cow<'_, str> {
        if !Self::should_quote(string) {
            return Cow::Borrowed(string);
        }

        // Determine the best option for the surrounding quotes to minimize escape sequences
        let surrounding: char;
        if string.contains('"') {
            surrounding = '\'';
        } else {
            surrounding = '"';
        }

        let mut snbt_string = String::with_capacity(2 + string.len());
        snbt_string.push(surrounding);

        // Construct the string accounting for escape sequences
        for ch in string.chars() {
            match ch {
                '\n' => {
                    snbt_string.push_str("\\n");
                    continue;
                }
                '\r' => {
                    snbt_string.push_str("\\r");
                    continue;
                }
                '\t' => {
                    snbt_string.push_str("\\t");
                    continue;
                }
                _ =>
                    if ch == surrounding || ch == '\\' {
                        snbt_string.push('\\');
                    },
            }
            snbt_string.push(ch);
        }

        snbt_string.push(surrounding);
        Cow::Owned(snbt_string)
    }

    #[allow(clippy::write_with_newline)]
    fn to_formatted_snbt(&self, indent: &mut String, f: &mut Formatter<'_>) -> fmt::Result {
        fn write_list(
            list: &[impl Display],
            indent: &mut String,
            ts: &str,
            f: &mut Formatter<'_>,
        ) -> fmt::Result {
            if list.is_empty() {
                return write!(f, "[{};]", ts);
            }

            if f.alternate() {
                indent.push_str("    ");
                write!(f, "[\n{}{};\n", indent, ts)?;
            } else {
                write!(f, "[{};", ts)?;
            }

            let last_index = list.len() - 1;
            for (index, element) in list.iter().enumerate() {
                if f.alternate() {
                    write!(f, "{}", indent)?;
                }
                Display::fmt(element, f)?;
                if index != last_index {
                    if f.alternate() {
                        write!(f, ",\n")?;
                    } else {
                        write!(f, ",")?;
                    }
                }
            }

            if f.alternate() {
                indent.truncate(indent.len() - 4);
                write!(f, "\n{}]", &indent)
            } else {
                write!(f, "]")
            }
        }

        #[inline]
        fn write(value: &impl Display, ts: Option<&str>, f: &mut Formatter<'_>) -> fmt::Result {
            match ts {
                Some(ts) => {
                    Display::fmt(value, f)?;
                    write!(f, "{}", ts)
                }
                None => Display::fmt(value, f),
            }
        }

        let ts = self.type_specifier();

        match self {
            NbtTag::Byte(value) => write(value, ts, f),
            NbtTag::Short(value) => write(value, ts, f),
            NbtTag::Int(value) => write(value, ts, f),
            NbtTag::Long(value) => write(value, ts, f),
            NbtTag::Float(value) => write(value, ts, f),
            NbtTag::Double(value) => write(value, ts, f),
            NbtTag::ByteArray(value) => write_list(&**value, indent, ts.unwrap(), f),
            NbtTag::String(value) => write!(f, "{}", Self::string_to_snbt(value)),
            NbtTag::List(value) => value.to_formatted_snbt(indent, f),
            NbtTag::Compound(value) => value.to_formatted_snbt(indent, f),
            NbtTag::IntArray(value) => write_list(&**value, indent, ts.unwrap(), f),
            NbtTag::LongArray(value) => write_list(&**value, indent, ts.unwrap(), f),
        }
    }
}

impl Display for NbtTag {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

impl Debug for NbtTag {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

// Implement the from trait for all the tag's internal types
macro_rules! tag_from {
    ($($type:ty, $tag:ident);*) => {
        $(
            impl From<$type> for NbtTag {
                #[inline]
                fn from(value: $type) -> NbtTag {
                    NbtTag::$tag(value)
                }
            }
        )*
    };
}

tag_from!(
    i8, Byte;
    i16, Short;
    i32, Int;
    i64, Long;
    f32, Float;
    f64, Double;
    Vec<i8>, ByteArray;
    String, String;
    NbtList, List;
    NbtCompound, Compound;
    Vec<i32>, IntArray;
    Vec<i64>, LongArray
);

impl From<&str> for NbtTag {
    #[inline]
    fn from(value: &str) -> NbtTag {
        NbtTag::String(value.to_owned())
    }
}

impl From<&String> for NbtTag {
    #[inline]
    fn from(value: &String) -> NbtTag {
        NbtTag::String(value.clone())
    }
}

impl From<bool> for NbtTag {
    #[inline]
    fn from(value: bool) -> NbtTag {
        NbtTag::Byte(if value { 1 } else { 0 })
    }
}

impl From<u8> for NbtTag {
    #[inline]
    fn from(value: u8) -> Self {
        NbtTag::Byte(value as i8)
    }
}

impl From<Vec<u8>> for NbtTag {
    #[inline]
    fn from(value: Vec<u8>) -> Self {
        NbtTag::ByteArray(raw::cast_byte_buf_to_signed(value))
    }
}

#[allow(deprecated)]
impl<T: NbtRepr> From<T> for NbtTag {
    #[inline]
    fn from(x: T) -> Self {
        NbtTag::Compound(x.to_nbt())
    }
}

macro_rules! prim_from_tag {
    ($($type:ty, $tag:ident);*) => {
        $(
            impl TryFrom<&NbtTag> for $type {
                type Error = NbtStructureError;

                #[inline]
                fn try_from(tag: &NbtTag) -> Result<Self, Self::Error> {
                    if let NbtTag::$tag(value) = tag {
                        Ok(*value)
                    } else {
                        Err(NbtStructureError::type_mismatch(stringify!($tag), tag.tag_name()))
                    }
                }
            }
        )*
    };
}

prim_from_tag!(
    i8, Byte;
    i16, Short;
    i32, Int;
    i64, Long;
    f32, Float;
    f64, Double
);

impl TryFrom<&NbtTag> for bool {
    type Error = NbtStructureError;

    fn try_from(tag: &NbtTag) -> Result<Self, Self::Error> {
        match *tag {
            NbtTag::Byte(value) => Ok(value != 0),
            NbtTag::Short(value) => Ok(value != 0),
            NbtTag::Int(value) => Ok(value != 0),
            NbtTag::Long(value) => Ok(value != 0),
            _ => Err(NbtStructureError::type_mismatch(
                "Byte, Short, Int, or Long",
                tag.tag_name(),
            )),
        }
    }
}

impl TryFrom<&NbtTag> for u8 {
    type Error = NbtStructureError;

    #[inline]
    fn try_from(tag: &NbtTag) -> Result<Self, Self::Error> {
        match *tag {
            NbtTag::Byte(value) => Ok(value as u8),
            _ => Err(NbtStructureError::type_mismatch("Byte", tag.tag_name())),
        }
    }
}

macro_rules! ref_from_tag {
    ($($type:ty, $tag:ident);*) => {
        $(
            impl<'a> TryFrom<&'a NbtTag> for &'a $type {
                type Error = NbtStructureError;

                #[inline]
                fn try_from(tag: &'a NbtTag) -> Result<Self, Self::Error> {
                    if let NbtTag::$tag(value) = tag {
                        Ok(value)
                    } else {
                        Err(NbtStructureError::type_mismatch(stringify!($tag), tag.tag_name()))
                    }
                }
            }

            impl<'a> TryFrom<&'a mut NbtTag> for &'a mut $type {
                type Error = NbtStructureError;

                #[inline]
                fn try_from(tag: &'a mut NbtTag) -> Result<Self, Self::Error> {
                    if let NbtTag::$tag(value) = tag {
                        Ok(value)
                    } else {
                        Err(NbtStructureError::type_mismatch(stringify!($tag), tag.tag_name()))
                    }
                }
            }
        )*
    };
}

ref_from_tag!(
    i8, Byte;
    i16, Short;
    i32, Int;
    i64, Long;
    f32, Float;
    f64, Double;
    Vec<i8>, ByteArray;
    [i8], ByteArray;
    String, String;
    str, String;
    NbtList, List;
    NbtCompound, Compound;
    Vec<i32>, IntArray;
    [i32], IntArray;
    Vec<i64>, LongArray;
    [i64], LongArray
);

impl<'a> TryFrom<&'a NbtTag> for &'a u8 {
    type Error = NbtStructureError;

    #[inline]
    fn try_from(tag: &'a NbtTag) -> Result<Self, Self::Error> {
        if let NbtTag::Byte(value) = tag {
            Ok(unsafe { &*(value as *const i8 as *const u8) })
        } else {
            Err(NbtStructureError::type_mismatch("Byte", tag.tag_name()))
        }
    }
}

impl<'a> TryFrom<&'a NbtTag> for &'a [u8] {
    type Error = NbtStructureError;

    #[inline]
    fn try_from(tag: &'a NbtTag) -> Result<Self, Self::Error> {
        if let NbtTag::ByteArray(value) = tag {
            Ok(raw::cast_bytes_to_unsigned(value.as_slice()))
        } else {
            Err(NbtStructureError::type_mismatch(
                "ByteArray",
                tag.tag_name(),
            ))
        }
    }
}

macro_rules! from_tag {
    ($($type:ty, $tag:ident);*) => {
        $(
            impl TryFrom<NbtTag> for $type {
                type Error = NbtStructureError;

                #[inline]
                fn try_from(tag: NbtTag) -> Result<Self, Self::Error> {
                    if let NbtTag::$tag(value) = tag {
                        Ok(value)
                    } else {
                        Err(NbtStructureError::type_mismatch(stringify!($tag), tag.tag_name()))
                    }
                }
            }
        )*
    };
}

from_tag!(
    i8, Byte;
    i16, Short;
    i32, Int;
    i64, Long;
    f32, Float;
    f64, Double;
    Vec<i8>, ByteArray;
    String, String;
    NbtList, List;
    NbtCompound, Compound;
    Vec<i32>, IntArray;
    Vec<i64>, LongArray
);

impl TryFrom<NbtTag> for Vec<u8> {
    type Error = NbtStructureError;

    #[inline]
    fn try_from(tag: NbtTag) -> Result<Self, Self::Error> {
        if let NbtTag::ByteArray(value) = tag {
            Ok(raw::cast_byte_buf_to_unsigned(value))
        } else {
            Err(NbtStructureError::type_mismatch(
                "ByteArray",
                tag.tag_name(),
            ))
        }
    }
}

/// The NBT tag list type which is essentially just a wrapper for a vec of NBT tags.
///
/// This type will implement both `Serialize` and `Deserialize` when the serde feature is enabled,
/// however this type should still be read and written with the utilities in the [`io`] module when
/// possible if speed is the main priority. See [`NbtTag`] for more details.
///
/// [`io`]: crate::io
/// [`NbtTag`]: crate::NbtTag
#[repr(transparent)]
#[derive(Clone, PartialEq)]
pub struct NbtList(pub(crate) Vec<NbtTag>);

impl NbtList {
    /// Returns a new NBT tag list with an empty internal vec.
    #[inline]
    pub const fn new() -> Self {
        NbtList(Vec::new())
    }

    /// Returns a mutable reference to the internal vector of this NBT list.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut Vec<NbtTag> {
        &mut self.0
    }

    /// Returns the internal vector of this NBT list.
    #[inline]
    pub fn into_inner(self) -> Vec<NbtTag> {
        self.0
    }

    /// Returns a new NBT tag list with the given initial capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        NbtList(Vec::with_capacity(capacity))
    }

    /// Clones the data in the given list and converts it into an [`NbtList`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use quartz_nbt::NbtList;
    /// let list: Vec<i32> = vec![1, 2, 3];
    /// let nbt_list = NbtList::clone_from(&list);
    /// assert_eq!(nbt_list.iter_map::<i32>().flatten().collect::<Vec<i32>>(), list);
    /// ```
    ///
    /// [`NbtList`]: crate::tag::NbtList
    #[inline]
    pub fn clone_from<'a, T, L>(list: L) -> Self
    where
        T: Clone + Into<NbtTag> + 'a,
        L: IntoIterator<Item = &'a T>,
    {
        NbtList(list.into_iter().map(|x| x.clone().into()).collect())
    }

    /// Creates an [`NbtList`] of [`NbtCompound`]s by mapping each element in the given list to its
    /// NBT representation.
    ///
    /// [`NbtCompound`]: crate::tag::NbtCompound
    /// [`NbtList`]: crate::tag::NbtList
    #[inline]
    #[deprecated(
        since = "0.2.3",
        note = "This method will eventually be made obsolete with serde compatibility"
    )]
    #[allow(deprecated)]
    pub fn clone_repr_from<'a, T, L>(list: L) -> Self
    where
        T: NbtRepr + 'a,
        L: IntoIterator<Item = &'a T>,
    {
        NbtList(list.into_iter().map(|x| x.to_nbt().into()).collect())
    }

    /// Iterates over this tag list, converting each tag reference into the specified type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use quartz_nbt::{NbtList, NbtStructureError};
    /// let mut list = NbtList::new();
    /// list.push(0i32);
    /// list.push(1i32);
    /// list.push(2.0f64);
    ///
    /// let mut iter = list.iter_map::<i32>();
    /// assert!(matches!(iter.next(), Some(Ok(0i32))));
    /// assert!(matches!(iter.next(), Some(Ok(1i32))));
    /// assert!(matches!(iter.next(), Some(Err(..)))); // Type mismatch
    /// assert!(iter.next().is_none());
    /// ```
    #[inline]
    pub fn iter_map<'a, T: TryFrom<&'a NbtTag>>(
        &'a self,
    ) -> impl Iterator<Item = Result<T, <T as TryFrom<&'a NbtTag>>::Error>> + 'a {
        self.0.iter().map(|tag| T::try_from(tag))
    }

    /// Iterates over mutable references to the tags in this list, converting each tag reference into
    /// the specified type. See [`iter_map`](crate::tag::NbtList::iter_map) for usage details.
    #[inline]
    pub fn iter_mut_map<'a, T: TryFrom<&'a mut NbtTag>>(
        &'a mut self,
    ) -> impl Iterator<Item = Result<T, <T as TryFrom<&'a mut NbtTag>>::Error>> + 'a {
        self.0.iter_mut().map(|tag| T::try_from(tag))
    }

    /// Converts this tag list into a valid SNBT string. See `NbtTag::`[`to_snbt`] for details.
    ///
    /// [`to_snbt`]: crate::NbtTag::to_snbt
    pub fn to_snbt(&self) -> String {
        format!("{:?}", self)
    }

    /// Converts this tag list into a valid SNBT string with extra spacing for readability.
    /// See `NbtTag::`[`to_pretty_snbt`] for details.
    ///
    /// [`to_pretty_snbt`]: crate::NbtTag::to_pretty_snbt
    pub fn to_pretty_snbt(&self) -> String {
        format!("{:#?}", self)
    }

    /// Returns the length of this list.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if this tag list has a length of zero, false otherwise.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the value of the tag at the given index, or an error if the index is out of bounds or the
    /// the tag type does not match the type specified. This method should be used for obtaining primitives
    /// and shared references to lists and compounds.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut list = NbtList::clone_from(&vec![1i32, 2, 3]);
    ///
    /// assert!(matches!(list.get::<i32>(0), Ok(1)));
    /// assert!(list.get::<f64>(0).is_err()); // Type mismatch
    /// assert!(list.get::<i32>(10).is_err()); // Invalid index
    /// ```
    #[inline]
    pub fn get<'a, T>(&'a self, index: usize) -> Result<T, NbtReprError>
    where
        T: TryFrom<&'a NbtTag>,
        T::Error: Into<anyhow::Error>,
    {
        T::try_from(
            self.0
                .get(index)
                .ok_or_else(|| NbtStructureError::invalid_index(index, self.len()))?,
        )
        .map_err(NbtReprError::from_any)
    }

    /// Returns a mutable reference to the tag at the given index, or an error if the index is out of bounds or
    /// tag type does not match the type specified. This method should be used for obtaining mutable references
    /// to elements.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut list = NbtList::clone_from(&vec![1i32, 2, 3]);
    ///
    /// *list.get_mut::<&mut i32>(0).unwrap() += 1;
    ///
    /// assert!(matches!(list.get::<i32>(0), Ok(2)));
    /// assert!(list.get::<f64>(0).is_err()); // Type mismatch
    /// assert!(list.get::<i32>(10).is_err()); // Invalid index
    /// ```
    #[inline]
    pub fn get_mut<'a, T>(&'a mut self, index: usize) -> Result<T, NbtReprError>
    where
        T: TryFrom<&'a mut NbtTag>,
        T::Error: Into<anyhow::Error>,
    {
        let len = self.len();
        T::try_from(
            self.0
                .get_mut(index)
                .ok_or_else(|| NbtStructureError::invalid_index(index, len))?,
        )
        .map_err(NbtReprError::from_any)
    }

    /// Pushes the given value to the back of the list after wrapping it in an `NbtTag`.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut list = NbtList::new();
    ///
    /// list.push(10i32);
    ///
    /// assert!(matches!(list.get::<i32>(0), Ok(10)));
    /// assert!(list.get::<f64>(0).is_err()); // Type mismatch
    /// assert!(list.get::<i32>(10).is_err()); // Invalid index
    /// ```
    #[inline]
    pub fn push<T: Into<NbtTag>>(&mut self, value: T) {
        self.0.push(value.into());
    }

    #[allow(clippy::write_with_newline)]
    fn to_formatted_snbt(&self, indent: &mut String, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            return write!(f, "[]");
        }

        if f.alternate() {
            indent.push_str("    ");
            write!(f, "[\n")?;
        } else {
            write!(f, "[")?;
        }

        let last_index = self.len() - 1;
        for (index, element) in self.0.iter().enumerate() {
            if f.alternate() {
                write!(f, "{}", indent)?;
            }

            element.to_formatted_snbt(indent, f)?;

            if index != last_index {
                if f.alternate() {
                    write!(f, ",\n")?;
                } else {
                    write!(f, ",")?;
                }
            }
        }

        if f.alternate() {
            indent.truncate(indent.len() - 4);
            write!(f, "\n{}]", indent)
        } else {
            write!(f, "]")
        }
    }
}

impl Default for NbtList {
    #[inline]
    fn default() -> Self {
        NbtList::new()
    }
}

impl<T: Into<NbtTag>> From<Vec<T>> for NbtList {
    #[inline]
    fn from(list: Vec<T>) -> Self {
        NbtList(list.into_iter().map(|x| x.into()).collect())
    }
}

impl IntoIterator for NbtList {
    type IntoIter = <Vec<NbtTag> as IntoIterator>::IntoIter;
    type Item = NbtTag;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a NbtList {
    type IntoIter = <&'a Vec<NbtTag> as IntoIterator>::IntoIter;
    type Item = &'a NbtTag;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a mut NbtList {
    type IntoIter = <&'a mut Vec<NbtTag> as IntoIterator>::IntoIter;
    type Item = &'a mut NbtTag;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

impl FromIterator<NbtTag> for NbtList {
    #[inline]
    fn from_iter<T: IntoIterator<Item = NbtTag>>(iter: T) -> Self {
        NbtList(Vec::from_iter(iter))
    }
}

impl AsRef<[NbtTag]> for NbtList {
    #[inline]
    fn as_ref(&self) -> &[NbtTag] {
        &self.0
    }
}

impl AsMut<[NbtTag]> for NbtList {
    #[inline]
    fn as_mut(&mut self) -> &mut [NbtTag] {
        &mut self.0
    }
}

impl Borrow<[NbtTag]> for NbtList {
    #[inline]
    fn borrow(&self) -> &[NbtTag] {
        &self.0
    }
}

impl BorrowMut<[NbtTag]> for NbtList {
    #[inline]
    fn borrow_mut(&mut self) -> &mut [NbtTag] {
        &mut self.0
    }
}

impl Deref for NbtList {
    type Target = [NbtTag];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl DerefMut for NbtList {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self.0
    }
}

impl Display for NbtList {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

impl Debug for NbtList {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

impl Extend<NbtTag> for NbtList {
    #[inline]
    fn extend<T: IntoIterator<Item = NbtTag>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

impl Index<usize> for NbtList {
    type Output = NbtTag;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl IndexMut<usize> for NbtList {
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

/// The NBT tag compound type which is essentially just a wrapper for a hash map of string keys
/// to tag values.
///
/// This type will implement both `Serialize` and `Deserialize` when the serde feature is enabled,
/// however this type should still be read and written with the utilities in the [`io`] module when
/// possible if speed is the main priority. See [`NbtTag`] for more details.
///
/// [`NbtTag`]: crate::NbtTag
/// [`io`]: crate::io
#[repr(transparent)]
#[derive(Clone, PartialEq)]
pub struct NbtCompound(pub(crate) Map<NbtTag>);

impl NbtCompound {
    /// Returns a new NBT tag compound with an empty internal hash map.
    #[inline]
    pub fn new() -> Self {
        NbtCompound(Map::new())
    }

    /// Returns a reference to the internal hash map of this compound.
    #[inline]
    pub fn inner(&self) -> &Map<NbtTag> {
        &self.0
    }

    /// Returns a mutable reference to the internal hash map of this compound.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut Map<NbtTag> {
        &mut self.0
    }

    /// Returns the internal hash map of this NBT compound.
    #[inline]
    pub fn into_inner(self) -> Map<NbtTag> {
        self.0
    }

    /// Returns a new NBT tag compound with the given initial capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        NbtCompound(Map::with_capacity(capacity))
    }

    /// Clones the data in the given map and converts it into an [`NbtCompound`](crate::tag::NbtCompound).
    ///
    /// # Examples
    ///
    /// ```
    /// # use quartz_nbt::NbtCompound;
    /// # use std::collections::HashMap;
    /// let mut map = HashMap::new();
    /// map.insert("foo", 10i32);
    /// map.insert("bar", -5i32);
    ///
    /// let compound = NbtCompound::clone_from(&map);
    /// assert_eq!(
    ///     compound.get::<_, i32>("foo").unwrap() + compound.get::<_, i32>("bar").unwrap(),
    ///     5i32
    /// );
    /// ```
    #[inline]
    pub fn clone_from<'a, K, V, M>(map: &'a M) -> Self
    where
        K: Clone + Into<String> + 'a,
        V: Clone + Into<NbtTag> + 'a,
        &'a M: IntoIterator<Item = (&'a K, &'a V)>,
    {
        NbtCompound(
            map.into_iter()
                .map(|(key, value)| (key.clone().into(), value.clone().into()))
                .collect(),
        )
    }

    /// Creates an [`NbtCompound`] of [`NbtCompound`]s by mapping each element in the given map to its
    /// NBT representation.
    ///
    /// [`NbtCompound`]: crate::tag::NbtCompound
    #[inline]
    #[deprecated(
        since = "0.2.3",
        note = "This method will eventually be made obsolete with serde compatibility"
    )]
    #[allow(deprecated)]
    pub fn clone_repr_from<'a, K, V, M>(map: &'a M) -> Self
    where
        K: Clone + Into<String> + 'a,
        V: NbtRepr + 'a,
        &'a M: IntoIterator<Item = (&'a K, &'a V)>,
    {
        NbtCompound(
            map.into_iter()
                .map(|(key, value)| (key.clone().into(), value.to_nbt().into()))
                .collect(),
        )
    }

    /// Iterates over this tag compound, converting each tag reference into the specified type. Each key is
    /// paired with the result of the attempted conversion into the specified type. The iterator will not
    /// terminate even if some conversions fail.
    #[inline]
    pub fn iter_map<'a, T: TryFrom<&'a NbtTag>>(
        &'a self,
    ) -> impl Iterator<Item = (&'a str, Result<T, <T as TryFrom<&'a NbtTag>>::Error>)> + 'a {
        self.0
            .iter()
            .map(|(key, tag)| (key.as_str(), T::try_from(tag)))
    }

    /// Iterates over this tag compound, converting each mutable tag reference into the specified type. See
    /// [`iter_map`](crate::tag::NbtCompound::iter_map) for details.
    #[inline]
    pub fn iter_mut_map<'a, T: TryFrom<&'a mut NbtTag>>(
        &'a mut self,
    ) -> impl Iterator<Item = (&'a str, Result<T, <T as TryFrom<&'a mut NbtTag>>::Error>)> + 'a
    {
        self.0
            .iter_mut()
            .map(|(key, tag)| (key.as_str(), T::try_from(tag)))
    }

    /// Converts this tag compound into a valid SNBT string. See `NbtTag::`[`to_snbt`] for details.
    ///
    /// [`to_snbt`]: crate::NbtTag::to_snbt
    pub fn to_snbt(&self) -> String {
        format!("{:?}", self)
    }

    /// Converts this tag compound into a valid SNBT string with extra spacing for readability.
    /// See `NbtTag::`[`to_pretty_snbt`] for details.
    ///
    /// [`to_pretty_snbt`]: crate::NbtTag::to_pretty_snbt
    pub fn to_pretty_snbt(&self) -> String {
        format!("{:#?}", self)
    }

    /// Returns the number of tags in this compound.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if the length of this compound is zero, false otherwise.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the value of the tag with the given name, or an error if no tag exists with the given name
    /// or specified type. This method should be used to obtain primitives as well as shared references to
    /// lists and compounds.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("test", 1.0f64);
    ///
    /// assert!((compound.get::<_, f64>("test").unwrap() - 1.0f64).abs() < 1e-5);
    /// assert!(compound.get::<_, i32>("test").is_err()); // Type mismatch
    /// assert!(compound.get::<_, f64>("foo").is_err()); // Missing tag
    /// ```
    #[inline]
    pub fn get<'a, 'b, K, T>(&'a self, name: &'b K) -> Result<T, NbtReprError>
    where
        String: Borrow<K>,
        K: Hash + Eq + ?Sized,
        &'b K: Into<String>,
        T: TryFrom<&'a NbtTag>,
        T::Error: Into<anyhow::Error>,
    {
        T::try_from(
            self.0
                .get(name)
                .ok_or_else(|| NbtStructureError::missing_tag(name))?,
        )
        .map_err(NbtReprError::from_any)
    }

    /// Returns the value of the tag with the given name, or an error if no tag exists with the given name
    /// or specified type. This method should be used to obtain mutable references to lists and compounds.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("test", 1.0f64);
    ///
    /// *compound.get_mut::<_, &mut f64>("test").unwrap() *= 2.0;
    ///
    /// assert!((compound.get::<_, f64>("test").unwrap() - 2.0f64).abs() < 1e-5);
    /// assert!(compound.get::<_, i32>("test").is_err()); // Type mismatch
    /// assert!(compound.get::<_, f64>("foo").is_err()); // Missing tag
    /// ```
    #[inline]
    pub fn get_mut<'a, 'b, K, T>(&'a mut self, name: &'b K) -> Result<T, NbtReprError>
    where
        String: Borrow<K>,
        K: Hash + Eq + ?Sized,
        &'b K: Into<String>,
        T: TryFrom<&'a mut NbtTag>,
        T::Error: Into<anyhow::Error>,
    {
        T::try_from(
            self.0
                .get_mut(name)
                .ok_or_else(|| NbtStructureError::missing_tag(name))?,
        )
        .map_err(NbtReprError::from_any)
    }

    /// Returns whether or not this compound has a tag with the given name.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("test", 1.0f64);
    ///
    /// assert!(compound.contains_key("test"));
    /// assert!(!compound.contains_key("foo"));
    /// ```
    #[inline]
    pub fn contains_key<K>(&self, key: &K) -> bool
    where
        String: Borrow<K>,
        K: Hash + Eq + ?Sized,
    {
        self.0.contains_key(key)
    }

    /// Adds the given value to this compound with the given name after wrapping that value in an `NbtTag`.
    ///
    /// ```
    /// # use quartz_nbt::*;
    /// let mut compound = NbtCompound::new();
    /// compound.insert("test", 1.0f64);
    ///
    /// assert!((compound.get::<_, f64>("test").unwrap() - 1.0f64).abs() < 1e-5);
    /// ```
    #[inline]
    pub fn insert<K: Into<String>, T: Into<NbtTag>>(&mut self, name: K, value: T) {
        self.0.insert(name.into(), value.into());
    }

    /// Parses a nbt compound from snbt
    ///
    /// # Example
    ///
    /// ```
    /// # use quartz_nbt::NbtCompound;
    /// let tag = NbtCompound::from_snbt(r#"{string:Stuff, list:[I;1,2,3,4,5]}"#).unwrap();
    /// assert!(matches!(tag.get::<_, &str>("string"), Ok("Stuff")));
    /// assert_eq!(tag.get::<_, &[i32]>("list").unwrap(), vec![1,2,3,4,5].as_slice());
    /// ```
    #[inline]
    pub fn from_snbt(input: &str) -> Result<Self, SnbtError> {
        snbt::parse(input)
    }

    #[allow(clippy::write_with_newline)]
    fn to_formatted_snbt(&self, indent: &mut String, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            return write!(f, "{{}}");
        }

        if f.alternate() {
            indent.push_str("    ");
            write!(f, "{{\n")?;
        } else {
            write!(f, "{{")?;
        }

        let last_index = self.len() - 1;
        for (index, (key, value)) in self.0.iter().enumerate() {
            let key = NbtTag::string_to_snbt(key);

            if f.alternate() {
                write!(f, "{}{}: ", indent, key)?;
            } else {
                write!(f, "{}:", key)?;
            }

            value.to_formatted_snbt(indent, f)?;

            if index != last_index {
                if f.alternate() {
                    write!(f, ",\n")?;
                } else {
                    write!(f, ",")?;
                }
            }
        }

        if f.alternate() {
            indent.truncate(indent.len() - 4);
            write!(f, "\n{}}}", indent)
        } else {
            write!(f, "}}")
        }
    }
}

impl Default for NbtCompound {
    #[inline]
    fn default() -> Self {
        NbtCompound::new()
    }
}

impl IntoIterator for NbtCompound {
    type IntoIter = <Map<NbtTag> as IntoIterator>::IntoIter;
    type Item = <Map<NbtTag> as IntoIterator>::Item;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a NbtCompound {
    type IntoIter = <&'a Map<NbtTag> as IntoIterator>::IntoIter;
    type Item = <&'a Map<NbtTag> as IntoIterator>::Item;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a mut NbtCompound {
    type IntoIter = <&'a mut Map<NbtTag> as IntoIterator>::IntoIter;
    type Item = (&'a String, &'a mut NbtTag);

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

impl FromIterator<(String, NbtTag)> for NbtCompound {
    #[inline]
    fn from_iter<T: IntoIterator<Item = (String, NbtTag)>>(iter: T) -> Self {
        NbtCompound(Map::from_iter(iter))
    }
}

impl<Q: ?Sized> Index<&Q> for NbtCompound
where
    String: Borrow<Q>,
    Q: Eq + Hash,
{
    type Output = NbtTag;

    #[inline]
    fn index(&self, key: &Q) -> &NbtTag {
        &self.0[key]
    }
}

impl FromStr for NbtCompound {
    type Err = SnbtError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_snbt(s)
    }
}

impl Display for NbtCompound {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

impl Debug for NbtCompound {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.to_formatted_snbt(&mut String::new(), f)
    }
}

impl Extend<(String, NbtTag)> for NbtCompound {
    #[inline]
    fn extend<T: IntoIterator<Item = (String, NbtTag)>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::*;
    use crate::serde::{Array, TypeHint};
    use serde::{
        de::{self, MapAccess, Visitor},
        Deserialize,
        Deserializer,
        Serialize,
        Serializer,
    };

    impl Serialize for NbtTag {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
            match self {
                &NbtTag::Byte(value) => serializer.serialize_i8(value),
                &NbtTag::Short(value) => serializer.serialize_i16(value),
                &NbtTag::Int(value) => serializer.serialize_i32(value),
                &NbtTag::Long(value) => serializer.serialize_i64(value),
                &NbtTag::Float(value) => serializer.serialize_f32(value),
                &NbtTag::Double(value) => serializer.serialize_f64(value),
                NbtTag::ByteArray(array) => Array::from(array).serialize(serializer),
                NbtTag::String(value) => serializer.serialize_str(value),
                NbtTag::List(list) => list.serialize(serializer),
                NbtTag::Compound(compound) => compound.serialize(serializer),
                NbtTag::IntArray(array) => Array::from(array).serialize(serializer),
                NbtTag::LongArray(array) => Array::from(array).serialize(serializer),
            }
        }
    }

    impl<'de> Deserialize<'de> for NbtTag {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de> {
            deserializer.deserialize_any(NbtTagVisitor)
        }
    }

    struct NbtTagVisitor;

    impl<'de> Visitor<'de> for NbtTagVisitor {
        type Value = NbtTag;

        fn expecting(&self, f: &mut Formatter<'_>) -> fmt::Result {
            write!(f, "a valid NBT type")
        }

        #[inline]
        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Byte(if v { 1 } else { 0 }))
        }

        #[inline]
        fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Byte(v))
        }

        #[inline]
        fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Byte(v as i8))
        }

        #[inline]
        fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Short(v))
        }

        #[inline]
        fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Int(v))
        }

        #[inline]
        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Long(v))
        }

        #[inline]
        fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Float(v))
        }

        #[inline]
        fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::Double(v))
        }

        #[inline]
        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
        where E: de::Error {
            self.visit_byte_buf(v.to_owned())
        }

        #[inline]
        fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::ByteArray(raw::cast_byte_buf_to_signed(v)))
        }

        #[inline]
        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::String(v.to_owned()))
        }

        #[inline]
        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where E: de::Error {
            Ok(NbtTag::String(v))
        }

        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
        where A: MapAccess<'de> {
            let mut dest = match map.size_hint() {
                Some(hint) => Map::with_capacity(hint),
                None => Map::new(),
            };
            while let Some((key, tag)) = map.next_entry::<String, NbtTag>()? {
                dest.insert(key, tag);
            }
            Ok(NbtTag::Compound(NbtCompound(dest)))
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where A: de::SeqAccess<'de> {
            enum ArbitraryList {
                Byte(Vec<i8>),
                Int(Vec<i32>),
                Long(Vec<i64>),
                Tag(Vec<NbtTag>),
                Indeterminate,
            }

            impl ArbitraryList {
                fn into_tag(self) -> NbtTag {
                    match self {
                        ArbitraryList::Byte(list) => NbtTag::ByteArray(list),
                        ArbitraryList::Int(list) => NbtTag::IntArray(list),
                        ArbitraryList::Long(list) => NbtTag::LongArray(list),
                        ArbitraryList::Tag(list) => NbtTag::List(NbtList(list)),
                        ArbitraryList::Indeterminate => NbtTag::List(NbtList::new()),
                    }
                }
            }

            let mut list = ArbitraryList::Indeterminate;

            fn init_vec<T>(element: T, size: Option<usize>) -> Vec<T> {
                match size {
                    Some(size) => {
                        // Add one because the size hint returns the remaining amount
                        let mut vec = Vec::with_capacity(1 + size);
                        vec.push(element);
                        vec
                    }
                    None => vec![element],
                }
            }

            while let Some(tag) = seq.next_element::<NbtTag>()? {
                match (tag, &mut list) {
                    (NbtTag::Byte(value), ArbitraryList::Byte(list)) => list.push(value),
                    (NbtTag::Int(value), ArbitraryList::Int(list)) => list.push(value),
                    (NbtTag::Long(value), ArbitraryList::Long(list)) => list.push(value),
                    (tag, ArbitraryList::Tag(list)) => list.push(tag),
                    (tag, list @ ArbitraryList::Indeterminate) => {
                        let size = seq.size_hint();
                        match tag {
                            NbtTag::Byte(value) =>
                                *list = ArbitraryList::Byte(init_vec(value, size)),
                            NbtTag::Int(value) => *list = ArbitraryList::Int(init_vec(value, size)),
                            NbtTag::Long(value) =>
                                *list = ArbitraryList::Long(init_vec(value, size)),
                            tag => *list = ArbitraryList::Tag(init_vec(tag, size)),
                        }
                    }
                    _ =>
                        return Err(de::Error::custom(
                            "tag type mismatch when deserializing array",
                        )),
                }
            }

            match seq.next_element::<TypeHint>() {
                Ok(Some(TypeHint { hint: Some(tag_id) })) => match (list, tag_id) {
                    (ArbitraryList::Byte(list), 0x9) => Ok(NbtTag::List(NbtList(
                        list.into_iter().map(Into::into).collect(),
                    ))),
                    (ArbitraryList::Int(list), 0x9) => Ok(NbtTag::List(NbtList(
                        list.into_iter().map(Into::into).collect(),
                    ))),
                    (ArbitraryList::Long(list), 0x9) => Ok(NbtTag::List(NbtList(
                        list.into_iter().map(Into::into).collect(),
                    ))),
                    (ArbitraryList::Indeterminate, 0x7) => Ok(NbtTag::ByteArray(Vec::new())),
                    (ArbitraryList::Indeterminate, 0xB) => Ok(NbtTag::IntArray(Vec::new())),
                    (ArbitraryList::Indeterminate, 0xC) => Ok(NbtTag::LongArray(Vec::new())),
                    (list, _) => Ok(list.into_tag()),
                },
                _ => Ok(list.into_tag()),
            }
        }
    }

    impl Serialize for NbtList {
        #[inline]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
            self.0.serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for NbtList {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de> {
            Ok(NbtList(Deserialize::deserialize(deserializer)?))
        }
    }

    impl Serialize for NbtCompound {
        #[inline]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
            self.0.serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for NbtCompound {
        #[inline]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de> {
            Ok(NbtCompound(Deserialize::deserialize(deserializer)?))
        }
    }
}