ijson/
ser.rs

1use serde::ser::{
2    Error as _, Impossible, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
3    SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
4};
5use serde::{Serialize, Serializer};
6use serde_json::error::Error;
7
8use super::array::IArray;
9use super::number::INumber;
10use super::object::IObject;
11use super::string::IString;
12use super::value::{DestructuredRef, IValue};
13
14impl Serialize for IValue {
15    #[inline]
16    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
17    where
18        S: Serializer,
19    {
20        match self.destructure_ref() {
21            DestructuredRef::Null => serializer.serialize_unit(),
22            DestructuredRef::Bool(b) => serializer.serialize_bool(b),
23            DestructuredRef::Number(n) => n.serialize(serializer),
24            DestructuredRef::String(s) => s.serialize(serializer),
25            DestructuredRef::Array(v) => v.serialize(serializer),
26            DestructuredRef::Object(o) => o.serialize(serializer),
27        }
28    }
29}
30
31impl Serialize for INumber {
32    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
33    where
34        S: Serializer,
35    {
36        if self.has_decimal_point() {
37            serializer.serialize_f64(self.to_f64().unwrap())
38        } else if let Some(v) = self.to_i64() {
39            serializer.serialize_i64(v)
40        } else {
41            serializer.serialize_u64(self.to_u64().unwrap())
42        }
43    }
44}
45
46impl Serialize for IString {
47    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
48    where
49        S: Serializer,
50    {
51        serializer.serialize_str(self.as_str())
52    }
53}
54
55impl Serialize for IArray {
56    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
57    where
58        S: Serializer,
59    {
60        let mut s = serializer.serialize_seq(Some(self.len()))?;
61        for v in self {
62            s.serialize_element(v)?;
63        }
64        s.end()
65    }
66}
67
68impl Serialize for IObject {
69    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
70    where
71        S: Serializer,
72    {
73        let mut m = serializer.serialize_map(Some(self.len()))?;
74        for (k, v) in self {
75            m.serialize_entry(k, v)?;
76        }
77        m.end()
78    }
79}
80
81pub struct ValueSerializer;
82
83impl Serializer for ValueSerializer {
84    type Ok = IValue;
85    type Error = Error;
86
87    type SerializeSeq = SerializeArray;
88    type SerializeTuple = SerializeArray;
89    type SerializeTupleStruct = SerializeArray;
90    type SerializeTupleVariant = SerializeArrayVariant;
91    type SerializeMap = SerializeObject;
92    type SerializeStruct = SerializeObject;
93    type SerializeStructVariant = SerializeObjectVariant;
94
95    #[inline]
96    fn serialize_bool(self, value: bool) -> Result<IValue, Self::Error> {
97        Ok(value.into())
98    }
99
100    #[inline]
101    fn serialize_i8(self, value: i8) -> Result<IValue, Self::Error> {
102        Ok(value.into())
103    }
104
105    #[inline]
106    fn serialize_i16(self, value: i16) -> Result<IValue, Self::Error> {
107        Ok(value.into())
108    }
109
110    #[inline]
111    fn serialize_i32(self, value: i32) -> Result<IValue, Self::Error> {
112        Ok(value.into())
113    }
114
115    fn serialize_i64(self, value: i64) -> Result<IValue, Self::Error> {
116        Ok(value.into())
117    }
118
119    #[inline]
120    fn serialize_u8(self, value: u8) -> Result<IValue, Self::Error> {
121        Ok(value.into())
122    }
123
124    #[inline]
125    fn serialize_u16(self, value: u16) -> Result<IValue, Self::Error> {
126        Ok(value.into())
127    }
128
129    #[inline]
130    fn serialize_u32(self, value: u32) -> Result<IValue, Self::Error> {
131        Ok(value.into())
132    }
133
134    #[inline]
135    fn serialize_u64(self, value: u64) -> Result<IValue, Self::Error> {
136        Ok(value.into())
137    }
138
139    #[inline]
140    fn serialize_f32(self, value: f32) -> Result<IValue, Self::Error> {
141        Ok(value.into())
142    }
143
144    #[inline]
145    fn serialize_f64(self, value: f64) -> Result<IValue, Self::Error> {
146        Ok(value.into())
147    }
148
149    #[inline]
150    fn serialize_char(self, value: char) -> Result<IValue, Self::Error> {
151        let mut buffer = [0_u8; 4];
152        Ok(value.encode_utf8(&mut buffer).into())
153    }
154
155    #[inline]
156    fn serialize_str(self, value: &str) -> Result<IValue, Self::Error> {
157        Ok(value.into())
158    }
159
160    fn serialize_bytes(self, value: &[u8]) -> Result<IValue, Self::Error> {
161        let array: IArray = value.iter().copied().collect();
162        Ok(array.into())
163    }
164
165    #[inline]
166    fn serialize_unit(self) -> Result<IValue, Self::Error> {
167        Ok(IValue::NULL)
168    }
169
170    #[inline]
171    fn serialize_unit_struct(self, _name: &'static str) -> Result<IValue, Self::Error> {
172        self.serialize_unit()
173    }
174
175    #[inline]
176    fn serialize_unit_variant(
177        self,
178        _name: &'static str,
179        _variant_index: u32,
180        variant: &'static str,
181    ) -> Result<IValue, Self::Error> {
182        self.serialize_str(variant)
183    }
184
185    #[inline]
186    fn serialize_newtype_struct<T>(
187        self,
188        _name: &'static str,
189        value: &T,
190    ) -> Result<IValue, Self::Error>
191    where
192        T: ?Sized + Serialize,
193    {
194        value.serialize(self)
195    }
196
197    fn serialize_newtype_variant<T>(
198        self,
199        _name: &'static str,
200        _variant_index: u32,
201        variant: &'static str,
202        value: &T,
203    ) -> Result<IValue, Self::Error>
204    where
205        T: ?Sized + Serialize,
206    {
207        let mut obj = IObject::new();
208        obj.insert(variant, value.serialize(self)?);
209        Ok(obj.into())
210    }
211
212    #[inline]
213    fn serialize_none(self) -> Result<IValue, Self::Error> {
214        self.serialize_unit()
215    }
216
217    #[inline]
218    fn serialize_some<T>(self, value: &T) -> Result<IValue, Self::Error>
219    where
220        T: ?Sized + Serialize,
221    {
222        value.serialize(self)
223    }
224
225    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
226        Ok(SerializeArray {
227            array: IArray::with_capacity(len.unwrap_or(0)),
228        })
229    }
230
231    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
232        self.serialize_seq(Some(len))
233    }
234
235    fn serialize_tuple_struct(
236        self,
237        _name: &'static str,
238        len: usize,
239    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
240        self.serialize_seq(Some(len))
241    }
242
243    fn serialize_tuple_variant(
244        self,
245        _name: &'static str,
246        _variant_index: u32,
247        variant: &'static str,
248        len: usize,
249    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
250        Ok(SerializeArrayVariant {
251            name: variant.into(),
252            array: IArray::with_capacity(len),
253        })
254    }
255
256    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
257        Ok(SerializeObject {
258            object: IObject::with_capacity(len.unwrap_or(0)),
259            next_key: None,
260        })
261    }
262
263    fn serialize_struct(
264        self,
265        _name: &'static str,
266        len: usize,
267    ) -> Result<Self::SerializeStruct, Self::Error> {
268        self.serialize_map(Some(len))
269    }
270
271    fn serialize_struct_variant(
272        self,
273        _name: &'static str,
274        _variant_index: u32,
275        variant: &'static str,
276        len: usize,
277    ) -> Result<Self::SerializeStructVariant, Self::Error> {
278        Ok(SerializeObjectVariant {
279            name: variant.into(),
280            object: IObject::with_capacity(len),
281        })
282    }
283}
284
285pub struct SerializeArray {
286    array: IArray,
287}
288
289pub struct SerializeArrayVariant {
290    name: IString,
291    array: IArray,
292}
293
294pub struct SerializeObject {
295    object: IObject,
296    next_key: Option<IString>,
297}
298
299pub struct SerializeObjectVariant {
300    name: IString,
301    object: IObject,
302}
303
304impl SerializeSeq for SerializeArray {
305    type Ok = IValue;
306    type Error = Error;
307
308    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
309    where
310        T: ?Sized + Serialize,
311    {
312        self.array.push(value.serialize(ValueSerializer)?);
313        Ok(())
314    }
315
316    fn end(self) -> Result<IValue, Self::Error> {
317        Ok(self.array.into())
318    }
319}
320
321impl SerializeTuple for SerializeArray {
322    type Ok = IValue;
323    type Error = Error;
324
325    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
326    where
327        T: ?Sized + Serialize,
328    {
329        SerializeSeq::serialize_element(self, value)
330    }
331
332    fn end(self) -> Result<IValue, Self::Error> {
333        SerializeSeq::end(self)
334    }
335}
336
337impl SerializeTupleStruct for SerializeArray {
338    type Ok = IValue;
339    type Error = Error;
340
341    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
342    where
343        T: ?Sized + Serialize,
344    {
345        SerializeSeq::serialize_element(self, value)
346    }
347
348    fn end(self) -> Result<IValue, Self::Error> {
349        SerializeSeq::end(self)
350    }
351}
352
353impl SerializeTupleVariant for SerializeArrayVariant {
354    type Ok = IValue;
355    type Error = Error;
356
357    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
358    where
359        T: ?Sized + Serialize,
360    {
361        self.array.push(value.serialize(ValueSerializer)?);
362        Ok(())
363    }
364
365    fn end(self) -> Result<IValue, Self::Error> {
366        let mut object = IObject::new();
367        object.insert(self.name, self.array);
368
369        Ok(object.into())
370    }
371}
372
373impl SerializeMap for SerializeObject {
374    type Ok = IValue;
375    type Error = Error;
376
377    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
378    where
379        T: ?Sized + Serialize,
380    {
381        self.next_key = Some(key.serialize(ObjectKeySerializer)?);
382        Ok(())
383    }
384
385    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
386    where
387        T: ?Sized + Serialize,
388    {
389        // Panic because this indicates a bug in the program rather than an
390        // expected failure.
391        let key = self
392            .next_key
393            .take()
394            .expect("serialize_value called before serialize_key");
395        self.object.insert(key, value.serialize(ValueSerializer)?);
396        Ok(())
397    }
398
399    fn end(self) -> Result<IValue, Self::Error> {
400        Ok(self.object.into())
401    }
402}
403
404struct ObjectKeySerializer;
405
406fn key_must_be_a_string() -> Error {
407    Error::custom("Object key must be a string")
408}
409
410impl Serializer for ObjectKeySerializer {
411    type Ok = IString;
412    type Error = Error;
413
414    type SerializeSeq = Impossible<IString, Error>;
415    type SerializeTuple = Impossible<IString, Error>;
416    type SerializeTupleStruct = Impossible<IString, Error>;
417    type SerializeTupleVariant = Impossible<IString, Error>;
418    type SerializeMap = Impossible<IString, Error>;
419    type SerializeStruct = Impossible<IString, Error>;
420    type SerializeStructVariant = Impossible<IString, Error>;
421
422    #[inline]
423    fn serialize_unit_variant(
424        self,
425        _name: &'static str,
426        _variant_index: u32,
427        variant: &'static str,
428    ) -> Result<IString, Self::Error> {
429        Ok(variant.into())
430    }
431
432    #[inline]
433    fn serialize_newtype_struct<T>(
434        self,
435        _name: &'static str,
436        value: &T,
437    ) -> Result<IString, Self::Error>
438    where
439        T: ?Sized + Serialize,
440    {
441        value.serialize(self)
442    }
443
444    fn serialize_bool(self, _value: bool) -> Result<IString, Self::Error> {
445        Err(key_must_be_a_string())
446    }
447
448    fn serialize_i8(self, value: i8) -> Result<IString, Self::Error> {
449        Ok(value.to_string().into())
450    }
451
452    fn serialize_i16(self, value: i16) -> Result<IString, Self::Error> {
453        Ok(value.to_string().into())
454    }
455
456    fn serialize_i32(self, value: i32) -> Result<IString, Self::Error> {
457        Ok(value.to_string().into())
458    }
459
460    fn serialize_i64(self, value: i64) -> Result<IString, Self::Error> {
461        Ok(value.to_string().into())
462    }
463
464    fn serialize_u8(self, value: u8) -> Result<IString, Self::Error> {
465        Ok(value.to_string().into())
466    }
467
468    fn serialize_u16(self, value: u16) -> Result<IString, Self::Error> {
469        Ok(value.to_string().into())
470    }
471
472    fn serialize_u32(self, value: u32) -> Result<IString, Self::Error> {
473        Ok(value.to_string().into())
474    }
475
476    fn serialize_u64(self, value: u64) -> Result<IString, Self::Error> {
477        Ok(value.to_string().into())
478    }
479
480    fn serialize_f32(self, _value: f32) -> Result<IString, Self::Error> {
481        Err(key_must_be_a_string())
482    }
483
484    fn serialize_f64(self, _value: f64) -> Result<IString, Self::Error> {
485        Err(key_must_be_a_string())
486    }
487
488    #[inline]
489    fn serialize_char(self, value: char) -> Result<IString, Self::Error> {
490        let mut buffer = [0_u8; 4];
491        Ok(value.encode_utf8(&mut buffer).into())
492    }
493
494    #[inline]
495    fn serialize_str(self, value: &str) -> Result<IString, Self::Error> {
496        Ok(value.into())
497    }
498
499    fn serialize_bytes(self, _value: &[u8]) -> Result<IString, Self::Error> {
500        Err(key_must_be_a_string())
501    }
502
503    fn serialize_unit(self) -> Result<IString, Self::Error> {
504        Err(key_must_be_a_string())
505    }
506
507    fn serialize_unit_struct(self, _name: &'static str) -> Result<IString, Self::Error> {
508        Err(key_must_be_a_string())
509    }
510
511    fn serialize_newtype_variant<T>(
512        self,
513        _name: &'static str,
514        _variant_index: u32,
515        _variant: &'static str,
516        _value: &T,
517    ) -> Result<IString, Self::Error>
518    where
519        T: ?Sized + Serialize,
520    {
521        Err(key_must_be_a_string())
522    }
523
524    fn serialize_none(self) -> Result<IString, Self::Error> {
525        Err(key_must_be_a_string())
526    }
527
528    fn serialize_some<T>(self, _value: &T) -> Result<IString, Self::Error>
529    where
530        T: ?Sized + Serialize,
531    {
532        Err(key_must_be_a_string())
533    }
534
535    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
536        Err(key_must_be_a_string())
537    }
538
539    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
540        Err(key_must_be_a_string())
541    }
542
543    fn serialize_tuple_struct(
544        self,
545        _name: &'static str,
546        _len: usize,
547    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
548        Err(key_must_be_a_string())
549    }
550
551    fn serialize_tuple_variant(
552        self,
553        _name: &'static str,
554        _variant_index: u32,
555        _variant: &'static str,
556        _len: usize,
557    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
558        Err(key_must_be_a_string())
559    }
560
561    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
562        Err(key_must_be_a_string())
563    }
564
565    fn serialize_struct(
566        self,
567        _name: &'static str,
568        _len: usize,
569    ) -> Result<Self::SerializeStruct, Self::Error> {
570        Err(key_must_be_a_string())
571    }
572
573    fn serialize_struct_variant(
574        self,
575        _name: &'static str,
576        _variant_index: u32,
577        _variant: &'static str,
578        _len: usize,
579    ) -> Result<Self::SerializeStructVariant, Self::Error> {
580        Err(key_must_be_a_string())
581    }
582}
583
584impl SerializeStruct for SerializeObject {
585    type Ok = IValue;
586    type Error = Error;
587
588    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
589    where
590        T: ?Sized + Serialize,
591    {
592        SerializeMap::serialize_entry(self, key, value)
593    }
594
595    fn end(self) -> Result<IValue, Self::Error> {
596        SerializeMap::end(self)
597    }
598}
599
600impl SerializeStructVariant for SerializeObjectVariant {
601    type Ok = IValue;
602    type Error = Error;
603
604    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
605    where
606        T: ?Sized + Serialize,
607    {
608        self.object.insert(key, value.serialize(ValueSerializer)?);
609        Ok(())
610    }
611
612    fn end(self) -> Result<IValue, Self::Error> {
613        let mut object = IObject::new();
614        object.insert(self.name, self.object);
615        Ok(object.into())
616    }
617}
618
619/// Converts an arbitrary type to an [`IValue`] using that type's [`serde::Serialize`]
620/// implementation.
621/// # Errors
622///
623/// Will return `Error` if `value` fails to serialize.
624pub fn to_value<T>(value: T) -> Result<IValue, Error>
625where
626    T: Serialize,
627{
628    value.serialize(ValueSerializer)
629}