imbl_value/
ser.rs

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