toml/ser/value/
mod.rs

1mod array;
2mod key;
3mod map;
4
5use toml_writer::TomlWrite as _;
6
7use super::style::Style;
8use super::Error;
9use crate::alloc_prelude::*;
10#[allow(clippy::wildcard_imports)]
11pub(crate) use array::*;
12#[allow(clippy::wildcard_imports)]
13pub(crate) use key::*;
14#[allow(clippy::wildcard_imports)]
15pub(crate) use map::*;
16
17/// Serialization for TOML [values][crate::Value].
18///
19/// This structure implements serialization support for TOML to serialize an
20/// arbitrary type to TOML. Note that the TOML format does not support all
21/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
22/// will generate an error when serialized.
23///
24/// Currently a serializer always writes its output to an in-memory `String`,
25/// which is passed in when creating the serializer itself.
26///
27/// # Examples
28///
29/// ```
30/// use serde::Serialize;
31///
32/// #[derive(Serialize)]
33/// struct Config {
34///     database: Database,
35/// }
36///
37/// #[derive(Serialize)]
38/// struct Database {
39///     ip: String,
40///     port: Vec<u16>,
41///     connection_max: u32,
42///     enabled: bool,
43/// }
44///
45/// let config = Config {
46///     database: Database {
47///         ip: "192.168.1.1".to_string(),
48///         port: vec![8001, 8002, 8003],
49///         connection_max: 5000,
50///         enabled: false,
51///     },
52/// };
53///
54/// let mut value = String::new();
55/// serde::Serialize::serialize(
56///     &config,
57///     toml::ser::ValueSerializer::new(&mut value)
58/// ).unwrap();
59/// println!("{}", value)
60/// ```
61pub struct ValueSerializer<'d> {
62    dst: &'d mut String,
63    style: Style,
64}
65
66impl<'d> ValueSerializer<'d> {
67    /// Creates a new serializer which will emit TOML into the buffer provided.
68    ///
69    /// The serializer can then be used to serialize a type after which the data
70    /// will be present in `dst`.
71    pub fn new(dst: &'d mut String) -> Self {
72        Self {
73            dst,
74            style: Default::default(),
75        }
76    }
77
78    pub(crate) fn with_style(dst: &'d mut String, style: Style) -> Self {
79        Self { dst, style }
80    }
81}
82
83impl<'d> serde_core::ser::Serializer for ValueSerializer<'d> {
84    type Ok = &'d mut String;
85    type Error = Error;
86    type SerializeSeq = SerializeValueArray<'d>;
87    type SerializeTuple = SerializeValueArray<'d>;
88    type SerializeTupleStruct = SerializeValueArray<'d>;
89    type SerializeTupleVariant = SerializeTupleVariant<'d>;
90    type SerializeMap = SerializeMap<'d>;
91    type SerializeStruct = SerializeMap<'d>;
92    type SerializeStructVariant = SerializeStructVariant<'d>;
93
94    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
95        self.dst.value(v)?;
96        Ok(self.dst)
97    }
98
99    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
100        self.dst.value(v)?;
101        Ok(self.dst)
102    }
103
104    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
105        self.dst.value(v)?;
106        Ok(self.dst)
107    }
108
109    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
110        self.dst.value(v)?;
111        Ok(self.dst)
112    }
113
114    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
115        self.dst.value(v)?;
116        Ok(self.dst)
117    }
118
119    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
120        self.dst.value(v)?;
121        Ok(self.dst)
122    }
123
124    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
125        self.dst.value(v)?;
126        Ok(self.dst)
127    }
128
129    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
130        self.dst.value(v)?;
131        Ok(self.dst)
132    }
133
134    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
135        self.dst.value(v)?;
136        Ok(self.dst)
137    }
138
139    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
140        self.dst.value(v)?;
141        Ok(self.dst)
142    }
143
144    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
145        self.dst.value(v)?;
146        Ok(self.dst)
147    }
148
149    fn serialize_f32(self, mut v: f32) -> Result<Self::Ok, Self::Error> {
150        // Discard sign of NaN when serialized using Serde.
151        //
152        // In all likelihood the sign of NaNs is not meaningful in the user's
153        // program. Ending up with `-nan` in the TOML document would usually be
154        // surprising and undesirable, when the sign of the NaN was not
155        // intentionally controlled by the caller, or may even be
156        // nondeterministic if it comes from arithmetic operations or a cast.
157        if v.is_nan() {
158            v = v.copysign(1.0);
159        }
160        self.dst.value(v)?;
161        Ok(self.dst)
162    }
163
164    fn serialize_f64(self, mut v: f64) -> Result<Self::Ok, Self::Error> {
165        // Discard sign of NaN when serialized using Serde.
166        //
167        // In all likelihood the sign of NaNs is not meaningful in the user's
168        // program. Ending up with `-nan` in the TOML document would usually be
169        // surprising and undesirable, when the sign of the NaN was not
170        // intentionally controlled by the caller, or may even be
171        // nondeterministic if it comes from arithmetic operations or a cast.
172        if v.is_nan() {
173            v = v.copysign(1.0);
174        }
175        self.dst.value(v)?;
176        Ok(self.dst)
177    }
178
179    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
180        self.dst.value(v)?;
181        Ok(self.dst)
182    }
183
184    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
185        self.dst.value(v)?;
186        Ok(self.dst)
187    }
188
189    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
190        use serde_core::ser::Serialize;
191        value.serialize(self)
192    }
193
194    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
195        Err(Error::unsupported_none())
196    }
197
198    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
199    where
200        T: serde_core::ser::Serialize + ?Sized,
201    {
202        value.serialize(self)
203    }
204
205    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
206        Err(Error::unsupported_type(Some("unit")))
207    }
208
209    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
210        Err(Error::unsupported_type(Some(name)))
211    }
212
213    fn serialize_unit_variant(
214        self,
215        _name: &'static str,
216        _variant_index: u32,
217        variant: &'static str,
218    ) -> Result<Self::Ok, Self::Error> {
219        self.serialize_str(variant)
220    }
221
222    fn serialize_newtype_struct<T>(
223        self,
224        _name: &'static str,
225        value: &T,
226    ) -> Result<Self::Ok, Self::Error>
227    where
228        T: serde_core::ser::Serialize + ?Sized,
229    {
230        value.serialize(self)
231    }
232
233    fn serialize_newtype_variant<T>(
234        self,
235        _name: &'static str,
236        _variant_index: u32,
237        variant: &'static str,
238        value: &T,
239    ) -> Result<Self::Ok, Self::Error>
240    where
241        T: serde_core::ser::Serialize + ?Sized,
242    {
243        self.dst.open_inline_table()?;
244        self.dst.space()?;
245        self.dst.key(variant)?;
246        self.dst.space()?;
247        self.dst.keyval_sep()?;
248        self.dst.space()?;
249        value.serialize(ValueSerializer::with_style(self.dst, self.style))?;
250        self.dst.space()?;
251        self.dst.close_inline_table()?;
252        Ok(self.dst)
253    }
254
255    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
256        SerializeValueArray::seq(self.dst, self.style, len)
257    }
258
259    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
260        self.serialize_seq(Some(len))
261    }
262
263    fn serialize_tuple_struct(
264        self,
265        _name: &'static str,
266        len: usize,
267    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
268        self.serialize_seq(Some(len))
269    }
270
271    fn serialize_tuple_variant(
272        self,
273        _name: &'static str,
274        _variant_index: u32,
275        variant: &'static str,
276        len: usize,
277    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
278        SerializeTupleVariant::tuple(self.dst, variant, len, self.style)
279    }
280
281    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
282        SerializeMap::map(self.dst, self.style)
283    }
284
285    fn serialize_struct(
286        self,
287        name: &'static str,
288        _len: usize,
289    ) -> Result<Self::SerializeStruct, Self::Error> {
290        SerializeMap::struct_(name, self.dst, self.style)
291    }
292
293    fn serialize_struct_variant(
294        self,
295        _name: &'static str,
296        _variant_index: u32,
297        variant: &'static str,
298        len: usize,
299    ) -> Result<Self::SerializeStructVariant, Self::Error> {
300        SerializeStructVariant::struct_(self.dst, variant, len, self.style)
301    }
302}