Skip to main content

jasn_core/value/
ser.rs

1//! Serialization to JASN Value.
2//!
3//! This module provides serialization from Rust types to JASN `Value`.
4
5use std::collections::BTreeMap;
6
7use serde::{Serialize, ser};
8
9use crate::{Binary, Value};
10
11/// Error type for serialization.
12#[derive(Debug, thiserror::Error)]
13pub enum Error {
14    /// Custom serialization error.
15    #[error("custom error: {0}")]
16    Custom(String),
17    /// Maps with non-string keys are not supported.
18    #[error("maps with non-string keys are not supported")]
19    NonStringKey,
20}
21
22impl ser::Error for Error {
23    fn custom<T: std::fmt::Display>(msg: T) -> Self {
24        Error::Custom(msg.to_string())
25    }
26}
27
28type Result<T> = std::result::Result<T, Error>;
29
30/// Serialize a Rust value to a JASN [`Value`].
31pub fn to_value<T>(value: &T) -> Result<Value>
32where
33    T: Serialize + ?Sized,
34{
35    value.serialize(Serializer)
36}
37
38/// Serializer whose output is a [`Value`].
39pub struct Serializer;
40
41impl ser::Serializer for Serializer {
42    type Ok = Value;
43    type Error = Error;
44
45    type SerializeSeq = SerializeVec;
46    type SerializeTuple = SerializeVec;
47    type SerializeTupleStruct = SerializeVec;
48    type SerializeTupleVariant = SerializeTupleVariant;
49    type SerializeMap = SerializeMap;
50    type SerializeStruct = SerializeMap;
51    type SerializeStructVariant = SerializeStructVariant;
52
53    fn serialize_bool(self, v: bool) -> Result<Value> {
54        Ok(Value::Bool(v))
55    }
56
57    fn serialize_i8(self, v: i8) -> Result<Value> {
58        Ok(Value::Int(v as i64))
59    }
60
61    fn serialize_i16(self, v: i16) -> Result<Value> {
62        Ok(Value::Int(v as i64))
63    }
64
65    fn serialize_i32(self, v: i32) -> Result<Value> {
66        Ok(Value::Int(v as i64))
67    }
68
69    fn serialize_i64(self, v: i64) -> Result<Value> {
70        Ok(Value::Int(v))
71    }
72
73    fn serialize_u8(self, v: u8) -> Result<Value> {
74        Ok(Value::Int(v as i64))
75    }
76
77    fn serialize_u16(self, v: u16) -> Result<Value> {
78        Ok(Value::Int(v as i64))
79    }
80
81    fn serialize_u32(self, v: u32) -> Result<Value> {
82        Ok(Value::Int(v as i64))
83    }
84
85    fn serialize_u64(self, v: u64) -> Result<Value> {
86        if v > i64::MAX as u64 {
87            Ok(Value::Float(v as f64))
88        } else {
89            Ok(Value::Int(v as i64))
90        }
91    }
92
93    fn serialize_f32(self, v: f32) -> Result<Value> {
94        Ok(Value::Float(v as f64))
95    }
96
97    fn serialize_f64(self, v: f64) -> Result<Value> {
98        Ok(Value::Float(v))
99    }
100
101    fn serialize_char(self, v: char) -> Result<Value> {
102        Ok(Value::String(v.to_string()))
103    }
104
105    fn serialize_str(self, v: &str) -> Result<Value> {
106        Ok(Value::String(v.to_string()))
107    }
108
109    fn serialize_bytes(self, v: &[u8]) -> Result<Value> {
110        Ok(Value::Binary(Binary(v.to_vec())))
111    }
112
113    fn serialize_none(self) -> Result<Value> {
114        Ok(Value::Null)
115    }
116
117    fn serialize_some<T>(self, value: &T) -> Result<Value>
118    where
119        T: ?Sized + Serialize,
120    {
121        value.serialize(self)
122    }
123
124    fn serialize_unit(self) -> Result<Value> {
125        Ok(Value::Null)
126    }
127
128    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
129        Ok(Value::Null)
130    }
131
132    fn serialize_unit_variant(
133        self,
134        _name: &'static str,
135        _variant_index: u32,
136        variant: &'static str,
137    ) -> Result<Value> {
138        Ok(Value::String(variant.to_string()))
139    }
140
141    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value>
142    where
143        T: ?Sized + Serialize,
144    {
145        value.serialize(self)
146    }
147
148    fn serialize_newtype_variant<T>(
149        self,
150        _name: &'static str,
151        _variant_index: u32,
152        variant: &'static str,
153        value: &T,
154    ) -> Result<Value>
155    where
156        T: ?Sized + Serialize,
157    {
158        let mut map = BTreeMap::new();
159        map.insert(variant.to_string(), to_value(value)?);
160        Ok(Value::Map(map))
161    }
162
163    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
164        Ok(SerializeVec {
165            vec: Vec::with_capacity(len.unwrap_or(0)),
166        })
167    }
168
169    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
170        self.serialize_seq(Some(len))
171    }
172
173    fn serialize_tuple_struct(
174        self,
175        _name: &'static str,
176        len: usize,
177    ) -> Result<Self::SerializeTupleStruct> {
178        self.serialize_seq(Some(len))
179    }
180
181    fn serialize_tuple_variant(
182        self,
183        _name: &'static str,
184        _variant_index: u32,
185        variant: &'static str,
186        len: usize,
187    ) -> Result<Self::SerializeTupleVariant> {
188        Ok(SerializeTupleVariant {
189            name: variant.to_string(),
190            vec: Vec::with_capacity(len),
191        })
192    }
193
194    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
195        Ok(SerializeMap {
196            map: BTreeMap::new(),
197            next_key: None,
198        })
199    }
200
201    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
202        self.serialize_map(Some(len))
203    }
204
205    fn serialize_struct_variant(
206        self,
207        _name: &'static str,
208        _variant_index: u32,
209        variant: &'static str,
210        _len: usize,
211    ) -> Result<Self::SerializeStructVariant> {
212        Ok(SerializeStructVariant {
213            name: variant.to_string(),
214            map: BTreeMap::new(),
215        })
216    }
217}
218
219/// Helper for serializing sequences.
220pub struct SerializeVec {
221    vec: Vec<Value>,
222}
223
224impl ser::SerializeSeq for SerializeVec {
225    type Ok = Value;
226    type Error = Error;
227
228    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
229    where
230        T: ?Sized + Serialize,
231    {
232        self.vec.push(to_value(value)?);
233        Ok(())
234    }
235
236    fn end(self) -> Result<Value> {
237        Ok(Value::List(self.vec))
238    }
239}
240
241impl ser::SerializeTuple for SerializeVec {
242    type Ok = Value;
243    type Error = Error;
244
245    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
246    where
247        T: ?Sized + Serialize,
248    {
249        ser::SerializeSeq::serialize_element(self, value)
250    }
251
252    fn end(self) -> Result<Value> {
253        ser::SerializeSeq::end(self)
254    }
255}
256
257impl ser::SerializeTupleStruct for SerializeVec {
258    type Ok = Value;
259    type Error = Error;
260
261    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
262    where
263        T: ?Sized + Serialize,
264    {
265        ser::SerializeSeq::serialize_element(self, value)
266    }
267
268    fn end(self) -> Result<Value> {
269        ser::SerializeSeq::end(self)
270    }
271}
272
273/// Helper for serializing tuple variants.
274pub struct SerializeTupleVariant {
275    name: String,
276    vec: Vec<Value>,
277}
278
279impl ser::SerializeTupleVariant for SerializeTupleVariant {
280    type Ok = Value;
281    type Error = Error;
282
283    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
284    where
285        T: ?Sized + Serialize,
286    {
287        self.vec.push(to_value(value)?);
288        Ok(())
289    }
290
291    fn end(self) -> Result<Value> {
292        let mut map = BTreeMap::new();
293        map.insert(self.name, Value::List(self.vec));
294        Ok(Value::Map(map))
295    }
296}
297
298/// Helper for serializing maps and structs.
299pub struct SerializeMap {
300    map: BTreeMap<String, Value>,
301    next_key: Option<String>,
302}
303
304impl ser::SerializeMap for SerializeMap {
305    type Ok = Value;
306    type Error = Error;
307
308    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
309    where
310        T: ?Sized + Serialize,
311    {
312        self.next_key = Some(key.serialize(KeySerializer)?);
313        Ok(())
314    }
315
316    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
317    where
318        T: ?Sized + Serialize,
319    {
320        let key = self
321            .next_key
322            .take()
323            .expect("serialize_value called before serialize_key");
324        self.map.insert(key, to_value(value)?);
325        Ok(())
326    }
327
328    fn end(self) -> Result<Value> {
329        Ok(Value::Map(self.map))
330    }
331}
332
333impl ser::SerializeStruct for SerializeMap {
334    type Ok = Value;
335    type Error = Error;
336
337    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
338    where
339        T: ?Sized + Serialize,
340    {
341        self.map.insert(key.to_string(), to_value(value)?);
342        Ok(())
343    }
344
345    fn end(self) -> Result<Value> {
346        Ok(Value::Map(self.map))
347    }
348}
349
350/// Helper for serializing struct variants.
351pub struct SerializeStructVariant {
352    name: String,
353    map: BTreeMap<String, Value>,
354}
355
356impl ser::SerializeStructVariant for SerializeStructVariant {
357    type Ok = Value;
358    type Error = Error;
359
360    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
361    where
362        T: ?Sized + Serialize,
363    {
364        self.map.insert(key.to_string(), to_value(value)?);
365        Ok(())
366    }
367
368    fn end(self) -> Result<Value> {
369        let mut outer = BTreeMap::new();
370        outer.insert(self.name, Value::Map(self.map));
371        Ok(Value::Map(outer))
372    }
373}
374
375struct KeySerializer;
376
377impl ser::Serializer for KeySerializer {
378    type Ok = String;
379    type Error = Error;
380
381    type SerializeSeq = ser::Impossible<String, Error>;
382    type SerializeTuple = ser::Impossible<String, Error>;
383    type SerializeTupleStruct = ser::Impossible<String, Error>;
384    type SerializeTupleVariant = ser::Impossible<String, Error>;
385    type SerializeMap = ser::Impossible<String, Error>;
386    type SerializeStruct = ser::Impossible<String, Error>;
387    type SerializeStructVariant = ser::Impossible<String, Error>;
388
389    fn serialize_bool(self, _v: bool) -> Result<String> {
390        Err(Error::NonStringKey)
391    }
392
393    fn serialize_i8(self, v: i8) -> Result<String> {
394        Ok(v.to_string())
395    }
396
397    fn serialize_i16(self, v: i16) -> Result<String> {
398        Ok(v.to_string())
399    }
400
401    fn serialize_i32(self, v: i32) -> Result<String> {
402        Ok(v.to_string())
403    }
404
405    fn serialize_i64(self, v: i64) -> Result<String> {
406        Ok(v.to_string())
407    }
408
409    fn serialize_u8(self, v: u8) -> Result<String> {
410        Ok(v.to_string())
411    }
412
413    fn serialize_u16(self, v: u16) -> Result<String> {
414        Ok(v.to_string())
415    }
416
417    fn serialize_u32(self, v: u32) -> Result<String> {
418        Ok(v.to_string())
419    }
420
421    fn serialize_u64(self, v: u64) -> Result<String> {
422        Ok(v.to_string())
423    }
424
425    fn serialize_f32(self, _v: f32) -> Result<String> {
426        Err(Error::NonStringKey)
427    }
428
429    fn serialize_f64(self, _v: f64) -> Result<String> {
430        Err(Error::NonStringKey)
431    }
432
433    fn serialize_char(self, v: char) -> Result<String> {
434        Ok(v.to_string())
435    }
436
437    fn serialize_str(self, v: &str) -> Result<String> {
438        Ok(v.to_string())
439    }
440
441    fn serialize_bytes(self, _v: &[u8]) -> Result<String> {
442        Err(Error::NonStringKey)
443    }
444
445    fn serialize_none(self) -> Result<String> {
446        Err(Error::NonStringKey)
447    }
448
449    fn serialize_some<T>(self, _value: &T) -> Result<String>
450    where
451        T: ?Sized + Serialize,
452    {
453        Err(Error::NonStringKey)
454    }
455
456    fn serialize_unit(self) -> Result<String> {
457        Err(Error::NonStringKey)
458    }
459
460    fn serialize_unit_struct(self, _name: &'static str) -> Result<String> {
461        Err(Error::NonStringKey)
462    }
463
464    fn serialize_unit_variant(
465        self,
466        _name: &'static str,
467        _variant_index: u32,
468        variant: &'static str,
469    ) -> Result<String> {
470        Ok(variant.to_string())
471    }
472
473    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<String>
474    where
475        T: ?Sized + Serialize,
476    {
477        value.serialize(self)
478    }
479
480    fn serialize_newtype_variant<T>(
481        self,
482        _name: &'static str,
483        _variant_index: u32,
484        _variant: &'static str,
485        _value: &T,
486    ) -> Result<String>
487    where
488        T: ?Sized + Serialize,
489    {
490        Err(Error::NonStringKey)
491    }
492
493    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
494        Err(Error::NonStringKey)
495    }
496
497    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
498        Err(Error::NonStringKey)
499    }
500
501    fn serialize_tuple_struct(
502        self,
503        _name: &'static str,
504        _len: usize,
505    ) -> Result<Self::SerializeTupleStruct> {
506        Err(Error::NonStringKey)
507    }
508
509    fn serialize_tuple_variant(
510        self,
511        _name: &'static str,
512        _variant_index: u32,
513        _variant: &'static str,
514        _len: usize,
515    ) -> Result<Self::SerializeTupleVariant> {
516        Err(Error::NonStringKey)
517    }
518
519    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
520        Err(Error::NonStringKey)
521    }
522
523    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
524        Err(Error::NonStringKey)
525    }
526
527    fn serialize_struct_variant(
528        self,
529        _name: &'static str,
530        _variant_index: u32,
531        _variant: &'static str,
532        _len: usize,
533    ) -> Result<Self::SerializeStructVariant> {
534        Err(Error::NonStringKey)
535    }
536}