ez_jsonrpc/params/
_ser.rs

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