serde_content/ser/
mod.rs

1#![cfg(feature = "serde")]
2
3mod r#enum;
4mod map;
5mod number;
6mod seq;
7mod r#struct;
8mod tests;
9mod tuple;
10
11use crate::Data;
12use crate::Error;
13use crate::Expected;
14use crate::Found;
15use crate::Number;
16use crate::Value;
17use alloc::borrow::Cow;
18use alloc::borrow::ToOwned;
19use alloc::boxed::Box;
20use alloc::string::ToString;
21use alloc::vec::Vec;
22use core::fmt;
23use core::marker::PhantomData;
24use map::Map;
25use r#enum::Enum;
26use r#struct::Struct;
27use seq::Seq;
28use serde::ser;
29use serde::ser::SerializeMap;
30use serde::ser::SerializeSeq;
31use serde::ser::SerializeTuple;
32use tuple::Tuple;
33
34/// A structure for serialising Rust values into [crate::Value].
35#[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd)]
36pub struct Serializer<'a> {
37    human_readable: bool,
38    lifetime: PhantomData<&'a ()>,
39}
40
41impl<'a> Serializer<'a> {
42    /// Creates a serializer.
43    ///
44    /// The serializer created doesn't serialize in human-readable form. To serialize
45    /// in human-readable form, call [Serializer::human_readable] on the resulting serializer.
46    pub const fn new() -> Self {
47        Self {
48            human_readable: false,
49            lifetime: PhantomData,
50        }
51    }
52
53    /// Make `Serialize` implementations serialize in human-readable form.
54    pub const fn human_readable(mut self) -> Self {
55        self.human_readable = true;
56        self
57    }
58
59    /// Convert a `T` into `Value` which is an enum that can represent any valid Rust data.
60    pub fn serialize<T>(self, value: T) -> Result<Value<'a>, Error>
61    where
62        T: ser::Serialize,
63    {
64        value.serialize(self)
65    }
66
67    const fn with_human_readable(human_readable: bool) -> Self {
68        Self {
69            human_readable,
70            lifetime: PhantomData,
71        }
72    }
73}
74
75impl<'a> ser::Serializer for Serializer<'a> {
76    type Ok = Value<'a>;
77    type Error = Error;
78
79    type SerializeSeq = Seq<'a>;
80    type SerializeTuple = Tuple<'a>;
81    type SerializeTupleStruct = Struct<'a>;
82    type SerializeTupleVariant = Enum<'a>;
83    type SerializeMap = Map<'a>;
84    type SerializeStruct = Struct<'a>;
85    type SerializeStructVariant = Enum<'a>;
86
87    fn serialize_bool(self, value: bool) -> Result<Self::Ok, Error> {
88        Ok(Value::Bool(value))
89    }
90
91    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Error> {
92        Ok(Value::Number(Number::I8(value)))
93    }
94
95    fn serialize_i16(self, value: i16) -> Result<Self::Ok, Error> {
96        Ok(Value::Number(Number::I16(value)))
97    }
98
99    fn serialize_i32(self, value: i32) -> Result<Self::Ok, Error> {
100        Ok(Value::Number(Number::I32(value)))
101    }
102
103    fn serialize_i64(self, value: i64) -> Result<Self::Ok, Error> {
104        Ok(Value::Number(Number::I64(value)))
105    }
106
107    fn serialize_i128(self, value: i128) -> Result<Self::Ok, Error> {
108        Ok(Value::Number(Number::I128(value)))
109    }
110
111    fn serialize_u8(self, value: u8) -> Result<Self::Ok, Error> {
112        Ok(Value::Number(Number::U8(value)))
113    }
114
115    fn serialize_u16(self, value: u16) -> Result<Self::Ok, Error> {
116        Ok(Value::Number(Number::U16(value)))
117    }
118
119    fn serialize_u32(self, value: u32) -> Result<Self::Ok, Error> {
120        Ok(Value::Number(Number::U32(value)))
121    }
122
123    fn serialize_u64(self, value: u64) -> Result<Self::Ok, Error> {
124        Ok(Value::Number(Number::U64(value)))
125    }
126
127    fn serialize_u128(self, value: u128) -> Result<Self::Ok, Error> {
128        Ok(Value::Number(Number::U128(value)))
129    }
130
131    fn serialize_f32(self, value: f32) -> Result<Self::Ok, Error> {
132        Ok(Value::Number(Number::F32(value)))
133    }
134
135    fn serialize_f64(self, value: f64) -> Result<Self::Ok, Error> {
136        Ok(Value::Number(Number::F64(value)))
137    }
138
139    fn serialize_char(self, value: char) -> Result<Self::Ok, Error> {
140        Ok(Value::Char(value))
141    }
142
143    fn serialize_str(self, value: &str) -> Result<Self::Ok, Error> {
144        Ok(Value::String(Cow::Owned(value.to_owned())))
145    }
146
147    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Error> {
148        Ok(Value::Bytes(Cow::Owned(value.to_owned())))
149    }
150
151    fn serialize_unit(self) -> Result<Self::Ok, Error> {
152        Ok(Value::Unit)
153    }
154
155    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Error> {
156        Ok(Value::Struct(Box::new(super::Struct {
157            name: Cow::Borrowed(name),
158            data: Data::Unit,
159        })))
160    }
161
162    fn serialize_unit_variant(
163        self,
164        name: &'static str,
165        variant_index: u32,
166        variant: &'static str,
167    ) -> Result<Self::Ok, Error> {
168        Ok(Value::Enum(Box::new(super::Enum {
169            name: Cow::Borrowed(name),
170            variant_index,
171            variant: Cow::Borrowed(variant),
172            data: Data::Unit,
173        })))
174    }
175
176    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Self::Ok, Error>
177    where
178        T: ?Sized + ser::Serialize,
179    {
180        Ok(Value::Struct(Box::new(super::Struct {
181            name: Cow::Borrowed(name),
182            data: Data::NewType {
183                value: value.serialize(self)?,
184            },
185        })))
186    }
187
188    fn serialize_newtype_variant<T>(
189        self,
190        name: &'static str,
191        variant_index: u32,
192        variant: &'static str,
193        value: &T,
194    ) -> Result<Self::Ok, Error>
195    where
196        T: ?Sized + ser::Serialize,
197    {
198        Ok(Value::Enum(Box::new(super::Enum {
199            name: Cow::Borrowed(name),
200            variant_index,
201            variant: Cow::Borrowed(variant),
202            data: Data::NewType {
203                value: value.serialize(self)?,
204            },
205        })))
206    }
207
208    fn serialize_none(self) -> Result<Self::Ok, Error> {
209        Ok(Value::Option(None))
210    }
211
212    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Error>
213    where
214        T: ?Sized + ser::Serialize,
215    {
216        let value = value.serialize(self)?;
217        Ok(Value::Option(Some(Box::new(value))))
218    }
219
220    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
221        Ok(Seq::new(
222            Vec::with_capacity(len.unwrap_or_default()),
223            self.human_readable,
224        ))
225    }
226
227    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> {
228        Ok(Tuple::new(Vec::with_capacity(len), self.human_readable))
229    }
230
231    fn serialize_tuple_struct(
232        self,
233        name: &'static str,
234        len: usize,
235    ) -> Result<Self::SerializeTupleStruct, Error> {
236        let st = super::Struct {
237            name: Cow::Borrowed(name),
238            data: Data::Tuple {
239                values: Vec::with_capacity(len),
240            },
241        };
242        Ok(Struct::new(st, self.human_readable))
243    }
244
245    fn serialize_tuple_variant(
246        self,
247        name: &'static str,
248        variant_index: u32,
249        variant: &'static str,
250        len: usize,
251    ) -> Result<Self::SerializeTupleVariant, Error> {
252        let en = super::Enum {
253            name: Cow::Borrowed(name),
254            variant_index,
255            variant: Cow::Borrowed(variant),
256            data: Data::Tuple {
257                values: Vec::with_capacity(len),
258            },
259        };
260        Ok(Enum::new(en, self.human_readable))
261    }
262
263    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
264        Ok(Map::new(
265            Vec::with_capacity(len.unwrap_or_default()),
266            self.human_readable,
267        ))
268    }
269
270    fn serialize_struct(
271        self,
272        name: &'static str,
273        len: usize,
274    ) -> Result<Self::SerializeStruct, Error> {
275        let st = super::Struct {
276            name: Cow::Borrowed(name),
277            data: Data::Struct {
278                fields: Vec::with_capacity(len),
279            },
280        };
281        Ok(Struct::new(st, self.human_readable))
282    }
283
284    fn serialize_struct_variant(
285        self,
286        name: &'static str,
287        variant_index: u32,
288        variant: &'static str,
289        len: usize,
290    ) -> Result<Self::SerializeStructVariant, Error> {
291        let en = super::Enum {
292            name: Cow::Borrowed(name),
293            variant_index,
294            variant: Cow::Borrowed(variant),
295            data: Data::Struct {
296                fields: Vec::with_capacity(len),
297            },
298        };
299        Ok(Enum::new(en, self.human_readable))
300    }
301
302    fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
303    where
304        T: ?Sized + fmt::Display,
305    {
306        Ok(Value::String(Cow::Owned(value.to_string())))
307    }
308
309    fn is_human_readable(&self) -> bool {
310        self.human_readable
311    }
312}
313
314impl ser::Serialize for Value<'_> {
315    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
316    where
317        S: ser::Serializer,
318    {
319        match self {
320            Value::Unit => serializer.serialize_unit(),
321            Value::Bool(v) => serializer.serialize_bool(*v),
322            Value::Number(v) => v.serialize(serializer),
323            Value::Char(v) => serializer.serialize_char(*v),
324            Value::String(v) => serializer.serialize_str(v.as_ref()),
325            Value::Bytes(v) => serializer.serialize_bytes(v.as_ref()),
326            Value::Seq(v) => {
327                let mut seq = serializer.serialize_seq(Some(v.len()))?;
328                for value in v {
329                    seq.serialize_element(value)?;
330                }
331                seq.end()
332            }
333            Value::Map(v) => {
334                let mut map = serializer.serialize_map(Some(v.len()))?;
335                for (key, value) in v {
336                    map.serialize_entry(key, value)?;
337                }
338                map.end()
339            }
340            Value::Option(v) => match v {
341                Some(v) => serializer.serialize_some(v),
342                None => serializer.serialize_none(),
343            },
344            Value::Struct(v) => v.serialize(serializer),
345            Value::Enum(v) => v.serialize(serializer),
346            Value::Tuple(v) => {
347                let mut tup = serializer.serialize_tuple(v.len())?;
348                for value in v {
349                    tup.serialize_element(value)?;
350                }
351                tup.end()
352            }
353        }
354    }
355}
356
357#[allow(clippy::ptr_arg)]
358fn to_static_str<E>(cow: &Cow<'static, str>) -> Result<&'static str, E>
359where
360    E: ser::Error,
361{
362    match cow {
363        Cow::Borrowed(v) => Ok(*v),
364        Cow::Owned(v) => {
365            let found = Found::String(v.clone());
366            let expected = Expected::StaticStr;
367            let error = Error::unexpected(found, expected);
368            Err(ser::Error::custom(error))
369        }
370    }
371}