nbt/
de.rs

1//! Deserialize Named Binary Tag data to a Rust data structure.
2
3use std::io;
4
5use flate2::read;
6use serde::de;
7
8use raw;
9
10use error::{Error, Result};
11
12/// Decode an object from Named Binary Tag (NBT) format.
13///
14/// Note that only maps and structs can be decoded, because the NBT format does
15/// not support bare types. Other types will return `Error::NoRootCompound`.
16pub fn from_reader<R, T>(src: R) -> Result<T>
17where
18    R: io::Read,
19    T: de::DeserializeOwned,
20{
21    let mut decoder = Decoder::new(src);
22    de::Deserialize::deserialize(&mut decoder)
23}
24
25/// Decode an object from Named Binary Tag (NBT) format.
26///
27/// Note that only maps and structs can be decoded, because the NBT format does
28/// not support bare types. Other types will return `Error::NoRootCompound`.
29pub fn from_gzip_reader<R, T>(src: R) -> Result<T>
30where
31    R: io::Read,
32    T: de::DeserializeOwned,
33{
34    let gzip = read::GzDecoder::new(src);
35    from_reader(gzip)
36}
37
38/// Decode an object from Named Binary Tag (NBT) format.
39///
40/// Note that only maps and structs can be decoded, because the NBT format does
41/// not support bare types. Other types will return `Error::NoRootCompound`.
42pub fn from_zlib_reader<R, T>(src: R) -> Result<T>
43where
44    R: io::Read,
45    T: de::DeserializeOwned,
46{
47    let zlib = read::ZlibDecoder::new(src);
48    from_reader(zlib)
49}
50
51/// Decode objects from Named Binary Tag (NBT) format.
52///
53/// Note that only maps and structs can be decoded, because the NBT format does
54/// not support bare types. Other types will return `Error::NoRootCompound`.
55pub struct Decoder<R> {
56    reader: R,
57}
58
59impl<R> Decoder<R>
60where
61    R: io::Read,
62{
63    /// Create an NBT Decoder from a given `io::Read` source.
64    pub fn new(src: R) -> Self {
65        Decoder { reader: src }
66    }
67}
68
69impl<'de: 'a, 'a, R: io::Read> de::Deserializer<'de> for &'a mut Decoder<R> {
70    type Error = Error;
71
72    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>
73    where
74        V: de::Visitor<'de>,
75    {
76        // The decoder cannot deserialize types by default. It can only handle
77        // maps and structs.
78        Err(Error::NoRootCompound)
79    }
80
81    fn deserialize_struct<V>(
82        self,
83        _name: &'static str,
84        _fields: &'static [&'static str],
85        visitor: V,
86    ) -> Result<V::Value>
87    where
88        V: de::Visitor<'de>,
89    {
90        self.deserialize_map(visitor)
91    }
92
93    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
94    where
95        V: de::Visitor<'de>,
96    {
97        visitor.visit_unit()
98    }
99
100    /// Deserialize newtype structs by their underlying types.
101    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
102    where
103        V: de::Visitor<'de>,
104    {
105        visitor.visit_newtype_struct(self)
106    }
107
108    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
109    where
110        V: de::Visitor<'de>,
111    {
112        // Ignore the header (if there is one).
113        let (tag, _) = raw::emit_next_header(&mut self.reader)?;
114
115        match tag {
116            0x0a => visitor.visit_map(MapDecoder::new(self)),
117            _ => Err(Error::NoRootCompound),
118        }
119    }
120
121    forward_to_deserialize_any! {
122        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string bytes byte_buf
123        unit seq tuple_struct tuple option enum identifier ignored_any
124    }
125}
126
127/// Decoder for map-like types.
128struct MapDecoder<'a, R: io::Read + 'a> {
129    outer: &'a mut Decoder<R>,
130    tag: Option<u8>,
131}
132
133impl<'a, R> MapDecoder<'a, R>
134where
135    R: io::Read,
136{
137    fn new(outer: &'a mut Decoder<R>) -> Self {
138        MapDecoder { outer, tag: None }
139    }
140}
141
142impl<'de: 'a, 'a, R: io::Read + 'a> de::MapAccess<'de> for MapDecoder<'a, R> {
143    type Error = Error;
144
145    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
146    where
147        K: de::DeserializeSeed<'de>,
148    {
149        let tag = raw::read_bare_byte(&mut self.outer.reader)?;
150
151        // NBT indicates the end of a compound type with a 0x00 tag.
152        if tag == 0x00 {
153            return Ok(None);
154        }
155
156        // Keep track of the tag so that we can decode the field correctly.
157        self.tag = Some(tag as u8);
158
159        // TODO: Enforce that keys must be String. This is a bit of a hack.
160        let mut de = InnerDecoder {
161            outer: self.outer,
162            tag: 0x08,
163        };
164
165        Ok(Some(seed.deserialize(&mut de)?))
166    }
167
168    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
169    where
170        V: de::DeserializeSeed<'de>,
171    {
172        let mut de = match self.tag {
173            Some(tag) => InnerDecoder {
174                outer: self.outer,
175                tag,
176            },
177            None => unimplemented!(),
178        };
179        Ok(seed.deserialize(&mut de)?)
180    }
181}
182
183/// Decoder for list-like types.
184struct SeqDecoder<'a, R: io::Read + 'a> {
185    outer: &'a mut Decoder<R>,
186    tag: u8,
187    length: i32,
188    current: i32,
189}
190
191impl<'a, R> SeqDecoder<'a, R>
192where
193    R: io::Read,
194{
195    fn list(outer: &'a mut Decoder<R>) -> Result<Self> {
196        let tag = raw::read_bare_byte(&mut outer.reader)?;
197        let length = raw::read_bare_int(&mut outer.reader)?;
198        Ok(SeqDecoder {
199            outer,
200            tag: tag as u8,
201            length,
202            current: 0,
203        })
204    }
205
206    fn byte_array(outer: &'a mut Decoder<R>) -> Result<Self> {
207        let length = raw::read_bare_int(&mut outer.reader)?;
208        Ok(SeqDecoder {
209            outer,
210            tag: 0x01,
211            length,
212            current: 0,
213        })
214    }
215
216    fn int_array(outer: &'a mut Decoder<R>) -> Result<Self> {
217        let length = raw::read_bare_int(&mut outer.reader)?;
218        Ok(SeqDecoder {
219            outer,
220            tag: 0x03,
221            length,
222            current: 0,
223        })
224    }
225
226    fn long_array(outer: &'a mut Decoder<R>) -> Result<Self> {
227        let length = raw::read_bare_int(&mut outer.reader)?;
228        Ok(SeqDecoder {
229            outer,
230            tag: 0x04,
231            length,
232            current: 0,
233        })
234    }
235}
236
237impl<'de: 'a, 'a, R: io::Read + 'a> de::SeqAccess<'de> for SeqDecoder<'a, R> {
238    type Error = Error;
239
240    fn next_element_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
241    where
242        K: de::DeserializeSeed<'de>,
243    {
244        if self.current == self.length {
245            return Ok(None);
246        }
247
248        let mut de = InnerDecoder {
249            outer: self.outer,
250            tag: self.tag,
251        };
252        let value = seed.deserialize(&mut de)?;
253
254        self.current += 1;
255
256        Ok(Some(value))
257    }
258
259    /// We always know the length of an NBT list in advance.
260    fn size_hint(&self) -> Option<usize> {
261        Some(self.length as usize)
262    }
263}
264
265/// Private inner decoder, for decoding raw (i.e. non-Compound) types.
266struct InnerDecoder<'a, R: io::Read + 'a> {
267    outer: &'a mut Decoder<R>,
268    tag: u8,
269}
270
271impl<'a, 'b: 'a, 'de, R: io::Read> de::Deserializer<'de> for &'b mut InnerDecoder<'a, R> {
272    type Error = Error;
273
274    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
275    where
276        V: de::Visitor<'de>,
277    {
278        let outer = &mut self.outer;
279
280        match self.tag {
281            0x01 => visitor.visit_i8(raw::read_bare_byte(&mut outer.reader)?),
282            0x02 => visitor.visit_i16(raw::read_bare_short(&mut outer.reader)?),
283            0x03 => visitor.visit_i32(raw::read_bare_int(&mut outer.reader)?),
284            0x04 => visitor.visit_i64(raw::read_bare_long(&mut outer.reader)?),
285            0x05 => visitor.visit_f32(raw::read_bare_float(&mut outer.reader)?),
286            0x06 => visitor.visit_f64(raw::read_bare_double(&mut outer.reader)?),
287            0x07 => visitor.visit_seq(SeqDecoder::byte_array(outer)?),
288            0x08 => visitor.visit_string(raw::read_bare_string(&mut outer.reader)?),
289            0x09 => visitor.visit_seq(SeqDecoder::list(outer)?),
290            0x0a => visitor.visit_map(MapDecoder::new(outer)),
291            0x0b => visitor.visit_seq(SeqDecoder::int_array(outer)?),
292            0x0c => visitor.visit_seq(SeqDecoder::long_array(outer)?),
293            t => Err(Error::InvalidTypeId(t)),
294        }
295    }
296
297    /// Deserialize bool values from a byte. Fail if that byte is not 0 or 1.
298    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
299    where
300        V: de::Visitor<'de>,
301    {
302        match self.tag {
303            0x01 => {
304                let reader = &mut self.outer.reader;
305                let value = raw::read_bare_byte(reader)?;
306                match value {
307                    0 => visitor.visit_bool(false),
308                    1 => visitor.visit_bool(true),
309                    b => Err(Error::NonBooleanByte(b)),
310                }
311            }
312            _ => Err(Error::TagMismatch(self.tag, 0x01)),
313        }
314    }
315
316    /// Interpret missing values as None.
317    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
318    where
319        V: de::Visitor<'de>,
320    {
321        visitor.visit_some(self)
322    }
323
324    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
325    where
326        V: de::Visitor<'de>,
327    {
328        visitor.visit_unit()
329    }
330
331    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
332    where
333        V: de::Visitor<'de>,
334    {
335        visitor.visit_unit()
336    }
337
338    /// Deserialize newtype structs by their underlying types.
339    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
340    where
341        V: de::Visitor<'de>,
342    {
343        visitor.visit_newtype_struct(self)
344    }
345
346    forward_to_deserialize_any! {
347        u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string bytes byte_buf seq
348        map tuple_struct struct tuple enum identifier ignored_any
349    }
350}