Skip to main content

fastnbt/value/
ser.rs

1use core::result;
2use std::collections::HashMap;
3
4use serde::{ser::Impossible, Serialize};
5
6use crate::{
7    error::{Error, Result},
8    ByteArray, IntArray, LongArray, Tag, Value, BYTE_ARRAY_TOKEN, INT_ARRAY_TOKEN,
9    LONG_ARRAY_TOKEN,
10};
11
12use super::array_serializer::ArraySerializer;
13
14impl Serialize for Value {
15    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
16    where
17        S: serde::Serializer,
18    {
19        match self {
20            Value::Byte(v) => serializer.serialize_i8(*v),
21            Value::Short(v) => serializer.serialize_i16(*v),
22            Value::Int(v) => serializer.serialize_i32(*v),
23            Value::Long(v) => serializer.serialize_i64(*v),
24            Value::Float(v) => serializer.serialize_f32(*v),
25            Value::Double(v) => serializer.serialize_f64(*v),
26            Value::String(v) => serializer.serialize_str(v),
27            Value::ByteArray(v) => v.serialize(serializer),
28            Value::IntArray(v) => v.serialize(serializer),
29            Value::LongArray(v) => v.serialize(serializer),
30            Value::List(v) => v.serialize(serializer),
31            Value::Compound(v) => v.serialize(serializer),
32        }
33    }
34}
35
36//
37// Everything below is copied and modified from serde_json:
38// https://github.com/serde-rs/json/blob/52a9c050f5dcc0dc3de4825b131b8ff05219cc82/src/value/ser.rs
39//
40// For which the license is MIT:
41//
42// Permission is hereby granted, free of charge, to any
43// person obtaining a copy of this software and associated
44// documentation files (the "Software"), to deal in the
45// Software without restriction, including without
46// limitation the rights to use, copy, modify, merge,
47// publish, distribute, sublicense, and/or sell copies of
48// the Software, and to permit persons to whom the Software
49// is furnished to do so, subject to the following
50// conditions:
51//
52// The above copyright notice and this permission notice
53// shall be included in all copies or substantial portions
54// of the Software.
55//
56// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
57// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
58// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
59// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
60// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
61// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
62// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
63// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
64// DEALINGS IN THE SOFTWARE.
65//
66
67/// Serializer whose output is a `Value`.
68///
69/// This is the serializer that backs [`fastnbt::to_value`][crate::to_value].
70/// Unlike the main fastnbt serializer which goes from some serializable
71/// value of type `T` to NBT bytes, this one goes from `T` to
72/// `fastnbt::Value`.
73///
74/// The `to_value` function is implementable as:
75///
76/// ```
77/// use serde::Serialize;
78/// use fastnbt::{error::Error, Value};
79///
80/// pub fn to_value<T>(input: T) -> Result<Value, Error>
81/// where
82///     T: Serialize,
83/// {
84///     input.serialize(&mut fastnbt::value::Serializer)
85/// }
86/// ```
87pub struct Serializer;
88
89impl serde::Serializer for &mut Serializer {
90    type Ok = Value;
91    type Error = Error;
92
93    type SerializeSeq = SerializeVec;
94    type SerializeTuple = SerializeVec;
95    type SerializeTupleStruct = SerializeVec;
96    type SerializeTupleVariant = SerializeTupleVariant;
97    type SerializeMap = SerializeMap;
98    type SerializeStruct = SerializeMap;
99    type SerializeStructVariant = SerializeStructVariant;
100
101    #[inline]
102    fn serialize_bool(self, value: bool) -> Result<Value> {
103        Ok(Value::Byte(value as i8))
104    }
105
106    #[inline]
107    fn serialize_i8(self, value: i8) -> Result<Value> {
108        Ok(Value::Byte(value))
109    }
110
111    #[inline]
112    fn serialize_i16(self, value: i16) -> Result<Value> {
113        Ok(Value::Short(value))
114    }
115
116    #[inline]
117    fn serialize_i32(self, value: i32) -> Result<Value> {
118        Ok(Value::Int(value))
119    }
120
121    fn serialize_i64(self, value: i64) -> Result<Value> {
122        Ok(Value::Long(value))
123    }
124
125    fn serialize_i128(self, v: i128) -> Result<Value> {
126        let v = v as u128;
127        Ok(Value::IntArray(IntArray::new(vec![
128            (v >> 96) as i32,
129            (v >> 64) as i32,
130            (v >> 32) as i32,
131            v as i32,
132        ])))
133    }
134
135    fn serialize_u128(self, v: u128) -> Result<Value> {
136        Ok(Value::IntArray(IntArray::new(vec![
137            (v >> 96) as i32,
138            (v >> 64) as i32,
139            (v >> 32) as i32,
140            v as i32,
141        ])))
142    }
143
144    #[inline]
145    fn serialize_u8(self, value: u8) -> Result<Value> {
146        Ok(Value::Byte(value as i8))
147    }
148
149    #[inline]
150    fn serialize_u16(self, value: u16) -> Result<Value> {
151        Ok(Value::Short(value as i16))
152    }
153
154    #[inline]
155    fn serialize_u32(self, value: u32) -> Result<Value> {
156        Ok(Value::Int(value as i32))
157    }
158
159    #[inline]
160    fn serialize_u64(self, value: u64) -> Result<Value> {
161        Ok(Value::Long(value as i64))
162    }
163
164    #[inline]
165    fn serialize_f32(self, value: f32) -> Result<Value> {
166        Ok(Value::Float(value))
167    }
168
169    #[inline]
170    fn serialize_f64(self, value: f64) -> Result<Value> {
171        Ok(Value::Double(value))
172    }
173
174    #[inline]
175    fn serialize_char(self, value: char) -> Result<Value> {
176        Ok(Value::Int(value as i32))
177    }
178
179    #[inline]
180    fn serialize_str(self, value: &str) -> Result<Value> {
181        Ok(Value::String(value.to_owned()))
182    }
183
184    fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
185        Ok(Value::List(
186            value.iter().map(|byte| Value::Byte(*byte as i8)).collect(),
187        ))
188    }
189
190    #[inline]
191    fn serialize_unit_variant(
192        self,
193        _name: &'static str,
194        _variant_index: u32,
195        variant: &'static str,
196    ) -> Result<Value> {
197        self.serialize_str(variant)
198    }
199
200    #[inline]
201    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
202    where
203        T: ?Sized + Serialize,
204    {
205        value.serialize(self)
206    }
207
208    fn serialize_newtype_variant<T>(
209        self,
210        _name: &'static str,
211        _variant_index: u32,
212        variant: &'static str,
213        value: &T,
214    ) -> Result<Value>
215    where
216        T: ?Sized + Serialize,
217    {
218        match variant {
219            crate::BYTE_ARRAY_TOKEN => value.serialize(ArraySerializer {
220                tag: Tag::ByteArray,
221            }),
222            crate::INT_ARRAY_TOKEN => value.serialize(ArraySerializer { tag: Tag::IntArray }),
223            crate::LONG_ARRAY_TOKEN => value.serialize(ArraySerializer {
224                tag: Tag::LongArray,
225            }),
226            _ => todo!("newtype variants that are not nbt arrays"),
227        }
228    }
229
230    #[inline]
231    fn serialize_some<T>(self, value: &T) -> Result<Value>
232    where
233        T: ?Sized + Serialize,
234    {
235        value.serialize(self)
236    }
237
238    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
239        Ok(SerializeVec {
240            vec: Vec::with_capacity(len.unwrap_or(0)),
241        })
242    }
243
244    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
245        self.serialize_seq(Some(len))
246    }
247
248    fn serialize_tuple_struct(
249        self,
250        _name: &'static str,
251        len: usize,
252    ) -> Result<Self::SerializeTupleStruct> {
253        self.serialize_seq(Some(len))
254    }
255
256    fn serialize_tuple_variant(
257        self,
258        _name: &'static str,
259        _variant_index: u32,
260        variant: &'static str,
261        len: usize,
262    ) -> Result<Self::SerializeTupleVariant> {
263        Ok(SerializeTupleVariant {
264            name: variant.into(),
265            vec: Vec::with_capacity(len),
266        })
267    }
268
269    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
270        Ok(SerializeMap {
271            map: HashMap::new(),
272            next_key: None,
273        })
274    }
275
276    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
277        self.serialize_map(Some(len))
278    }
279
280    fn serialize_struct_variant(
281        self,
282        _name: &'static str,
283        _variant_index: u32,
284        variant: &'static str,
285        _len: usize,
286    ) -> Result<Self::SerializeStructVariant> {
287        Ok(SerializeStructVariant {
288            name: variant.into(),
289            map: HashMap::new(),
290        })
291    }
292
293    fn collect_str<T>(self, value: &T) -> Result<Value>
294    where
295        T: ?Sized + std::fmt::Display,
296    {
297        Ok(Value::String(value.to_string()))
298    }
299
300    fn serialize_none(self) -> Result<Self::Ok> {
301        todo!()
302    }
303
304    fn serialize_unit(self) -> Result<Self::Ok> {
305        todo!()
306    }
307
308    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
309        todo!()
310    }
311}
312
313pub struct SerializeVec {
314    vec: Vec<Value>,
315}
316
317pub struct SerializeTupleVariant {
318    name: String,
319    vec: Vec<Value>,
320}
321
322pub struct SerializeMap {
323    map: HashMap<String, Value>,
324    next_key: Option<String>,
325}
326
327pub struct SerializeStructVariant {
328    name: String,
329    map: HashMap<String, Value>,
330}
331
332impl serde::ser::SerializeSeq for SerializeVec {
333    type Ok = Value;
334    type Error = Error;
335
336    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
337    where
338        T: ?Sized + Serialize,
339    {
340        self.vec.push(crate::to_value(value)?);
341        Ok(())
342    }
343
344    fn end(self) -> Result<Value> {
345        Ok(Value::List(self.vec))
346    }
347}
348
349impl serde::ser::SerializeTuple for SerializeVec {
350    type Ok = Value;
351    type Error = Error;
352
353    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
354    where
355        T: ?Sized + Serialize,
356    {
357        serde::ser::SerializeSeq::serialize_element(self, value)
358    }
359
360    fn end(self) -> Result<Value> {
361        serde::ser::SerializeSeq::end(self)
362    }
363}
364
365impl serde::ser::SerializeTupleStruct for SerializeVec {
366    type Ok = Value;
367    type Error = Error;
368
369    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
370    where
371        T: ?Sized + Serialize,
372    {
373        serde::ser::SerializeSeq::serialize_element(self, value)
374    }
375
376    fn end(self) -> Result<Value> {
377        serde::ser::SerializeSeq::end(self)
378    }
379}
380
381impl serde::ser::SerializeTupleVariant for SerializeTupleVariant {
382    type Ok = Value;
383    type Error = Error;
384
385    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
386    where
387        T: ?Sized + Serialize,
388    {
389        self.vec.push(crate::to_value(value)?);
390        Ok(())
391    }
392
393    fn end(self) -> Result<Value> {
394        let mut object = HashMap::new();
395
396        object.insert(self.name, Value::List(self.vec));
397
398        Ok(Value::Compound(object))
399    }
400}
401
402impl serde::ser::SerializeMap for SerializeMap {
403    type Ok = Value;
404    type Error = Error;
405
406    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
407    where
408        T: ?Sized + Serialize,
409    {
410        self.next_key = Some(key.serialize(MapKeySerializer)?);
411        Ok(())
412    }
413
414    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
415    where
416        T: ?Sized + Serialize,
417    {
418        let key = self.next_key.take();
419        // Panic because this indicates a bug in the program rather than an
420        // expected failure.
421        let key = key.expect("serialize_value called before serialize_key");
422
423        self.map.insert(key, crate::to_value(value)?);
424        Ok(())
425    }
426
427    fn end(self) -> Result<Value> {
428        if self.map.len() == 1 {
429            let (key, val) = self.map.iter().next().unwrap();
430            let data = || match val {
431                Value::List(bs) => bs
432                    .iter()
433                    .map(|v| v.as_i64().unwrap() as u8)
434                    .collect::<Vec<u8>>(),
435                _ => panic!(),
436            };
437
438            Ok(match key.as_str() {
439                BYTE_ARRAY_TOKEN => Value::ByteArray(ByteArray::from_bytes(&data())),
440                INT_ARRAY_TOKEN => Value::IntArray(IntArray::from_bytes(&data())?),
441                LONG_ARRAY_TOKEN => Value::LongArray(LongArray::from_bytes(&data())?),
442                _ => Value::Compound(self.map),
443            })
444        } else {
445            Ok(Value::Compound(self.map))
446        }
447    }
448}
449
450struct MapKeySerializer;
451
452fn key_must_be_a_string() -> Error {
453    Error::bespoke("Key must be a string".to_string())
454}
455
456impl serde::Serializer for MapKeySerializer {
457    type Ok = String;
458    type Error = Error;
459
460    type SerializeSeq = Impossible<String, Error>;
461    type SerializeTuple = Impossible<String, Error>;
462    type SerializeTupleStruct = Impossible<String, Error>;
463    type SerializeTupleVariant = Impossible<String, Error>;
464    type SerializeMap = Impossible<String, Error>;
465    type SerializeStruct = Impossible<String, Error>;
466    type SerializeStructVariant = Impossible<String, Error>;
467
468    #[inline]
469    fn serialize_unit_variant(
470        self,
471        _name: &'static str,
472        _variant_index: u32,
473        variant: &'static str,
474    ) -> Result<String> {
475        Ok(variant.to_owned())
476    }
477
478    #[inline]
479    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<String>
480    where
481        T: ?Sized + Serialize,
482    {
483        value.serialize(self)
484    }
485
486    fn serialize_bool(self, _value: bool) -> Result<String> {
487        Err(key_must_be_a_string())
488    }
489
490    fn serialize_i8(self, value: i8) -> Result<String> {
491        Ok(value.to_string())
492    }
493
494    fn serialize_i16(self, value: i16) -> Result<String> {
495        Ok(value.to_string())
496    }
497
498    fn serialize_i32(self, value: i32) -> Result<String> {
499        Ok(value.to_string())
500    }
501
502    fn serialize_i64(self, value: i64) -> Result<String> {
503        Ok(value.to_string())
504    }
505
506    fn serialize_u8(self, value: u8) -> Result<String> {
507        Ok(value.to_string())
508    }
509
510    fn serialize_u16(self, value: u16) -> Result<String> {
511        Ok(value.to_string())
512    }
513
514    fn serialize_u32(self, value: u32) -> Result<String> {
515        Ok(value.to_string())
516    }
517
518    fn serialize_u64(self, value: u64) -> Result<String> {
519        Ok(value.to_string())
520    }
521
522    fn serialize_f32(self, _value: f32) -> Result<String> {
523        Err(key_must_be_a_string())
524    }
525
526    fn serialize_f64(self, _value: f64) -> Result<String> {
527        Err(key_must_be_a_string())
528    }
529
530    #[inline]
531    fn serialize_char(self, value: char) -> Result<String> {
532        Ok(value.to_string())
533    }
534
535    #[inline]
536    fn serialize_str(self, value: &str) -> Result<String> {
537        Ok(value.to_owned())
538    }
539
540    fn serialize_bytes(self, _value: &[u8]) -> Result<String> {
541        Err(key_must_be_a_string())
542    }
543
544    fn serialize_unit(self) -> Result<String> {
545        Err(key_must_be_a_string())
546    }
547
548    fn serialize_unit_struct(self, _name: &'static str) -> Result<String> {
549        Err(key_must_be_a_string())
550    }
551
552    fn serialize_newtype_variant<T>(
553        self,
554        _name: &'static str,
555        _variant_index: u32,
556        _variant: &'static str,
557        _value: &T,
558    ) -> Result<String>
559    where
560        T: ?Sized + Serialize,
561    {
562        Err(key_must_be_a_string())
563    }
564
565    fn serialize_none(self) -> Result<String> {
566        Err(key_must_be_a_string())
567    }
568
569    fn serialize_some<T>(self, _value: &T) -> Result<String>
570    where
571        T: ?Sized + Serialize,
572    {
573        Err(key_must_be_a_string())
574    }
575
576    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
577        Err(key_must_be_a_string())
578    }
579
580    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
581        Err(key_must_be_a_string())
582    }
583
584    fn serialize_tuple_struct(
585        self,
586        _name: &'static str,
587        _len: usize,
588    ) -> Result<Self::SerializeTupleStruct> {
589        Err(key_must_be_a_string())
590    }
591
592    fn serialize_tuple_variant(
593        self,
594        _name: &'static str,
595        _variant_index: u32,
596        _variant: &'static str,
597        _len: usize,
598    ) -> Result<Self::SerializeTupleVariant> {
599        Err(key_must_be_a_string())
600    }
601
602    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
603        Err(key_must_be_a_string())
604    }
605
606    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
607        Err(key_must_be_a_string())
608    }
609
610    fn serialize_struct_variant(
611        self,
612        _name: &'static str,
613        _variant_index: u32,
614        _variant: &'static str,
615        _len: usize,
616    ) -> Result<Self::SerializeStructVariant> {
617        Err(key_must_be_a_string())
618    }
619
620    fn collect_str<T>(self, value: &T) -> Result<String>
621    where
622        T: ?Sized + std::fmt::Display,
623    {
624        Ok(value.to_string())
625    }
626}
627
628impl serde::ser::SerializeStruct for SerializeMap {
629    type Ok = Value;
630    type Error = Error;
631
632    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
633    where
634        T: ?Sized + Serialize,
635    {
636        serde::ser::SerializeMap::serialize_entry(self, key, value)
637    }
638
639    fn end(self) -> Result<Value> {
640        serde::ser::SerializeMap::end(self)
641    }
642}
643
644impl serde::ser::SerializeStructVariant for SerializeStructVariant {
645    type Ok = Value;
646    type Error = Error;
647
648    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
649    where
650        T: ?Sized + Serialize,
651    {
652        self.map.insert(String::from(key), crate::to_value(value)?);
653        Ok(())
654    }
655
656    fn end(self) -> Result<Value> {
657        let mut object = HashMap::new();
658
659        object.insert(self.name, Value::Compound(self.map));
660
661        Ok(Value::Compound(object))
662    }
663}