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::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_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
120        self.dst.value(v)?;
121        Ok(self.dst)
122    }
123
124    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
125        self.dst.value(v)?;
126        Ok(self.dst)
127    }
128
129    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
130        self.dst.value(v)?;
131        Ok(self.dst)
132    }
133
134    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
135        let v: i64 = v
136            .try_into()
137            .map_err(|_err| Error::out_of_range(Some("u64")))?;
138        self.serialize_i64(v)
139    }
140
141    fn serialize_f32(self, mut v: f32) -> Result<Self::Ok, Self::Error> {
142        // Discard sign of NaN when serialized using Serde.
143        //
144        // In all likelihood the sign of NaNs is not meaningful in the user's
145        // program. Ending up with `-nan` in the TOML document would usually be
146        // surprising and undesirable, when the sign of the NaN was not
147        // intentionally controlled by the caller, or may even be
148        // nondeterministic if it comes from arithmetic operations or a cast.
149        if v.is_nan() {
150            v = v.copysign(1.0);
151        }
152        self.dst.value(v)?;
153        Ok(self.dst)
154    }
155
156    fn serialize_f64(self, mut v: f64) -> Result<Self::Ok, Self::Error> {
157        // Discard sign of NaN when serialized using Serde.
158        //
159        // In all likelihood the sign of NaNs is not meaningful in the user's
160        // program. Ending up with `-nan` in the TOML document would usually be
161        // surprising and undesirable, when the sign of the NaN was not
162        // intentionally controlled by the caller, or may even be
163        // nondeterministic if it comes from arithmetic operations or a cast.
164        if v.is_nan() {
165            v = v.copysign(1.0);
166        }
167        self.dst.value(v)?;
168        Ok(self.dst)
169    }
170
171    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
172        self.dst.value(v)?;
173        Ok(self.dst)
174    }
175
176    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
177        self.dst.value(v)?;
178        Ok(self.dst)
179    }
180
181    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
182        use serde::ser::Serialize;
183        value.serialize(self)
184    }
185
186    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
187        Err(Error::unsupported_none())
188    }
189
190    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
191    where
192        T: serde::ser::Serialize + ?Sized,
193    {
194        value.serialize(self)
195    }
196
197    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
198        Err(Error::unsupported_type(Some("unit")))
199    }
200
201    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
202        Err(Error::unsupported_type(Some(name)))
203    }
204
205    fn serialize_unit_variant(
206        self,
207        _name: &'static str,
208        _variant_index: u32,
209        variant: &'static str,
210    ) -> Result<Self::Ok, Self::Error> {
211        self.serialize_str(variant)
212    }
213
214    fn serialize_newtype_struct<T>(
215        self,
216        _name: &'static str,
217        value: &T,
218    ) -> Result<Self::Ok, Self::Error>
219    where
220        T: serde::ser::Serialize + ?Sized,
221    {
222        value.serialize(self)
223    }
224
225    fn serialize_newtype_variant<T>(
226        self,
227        _name: &'static str,
228        _variant_index: u32,
229        variant: &'static str,
230        value: &T,
231    ) -> Result<Self::Ok, Self::Error>
232    where
233        T: serde::ser::Serialize + ?Sized,
234    {
235        self.dst.open_inline_table()?;
236        self.dst.space()?;
237        self.dst.key(variant)?;
238        self.dst.space()?;
239        self.dst.keyval_sep()?;
240        self.dst.space()?;
241        value.serialize(ValueSerializer::with_style(self.dst, self.style))?;
242        self.dst.space()?;
243        self.dst.close_inline_table()?;
244        Ok(self.dst)
245    }
246
247    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
248        SerializeValueArray::seq(self.dst, self.style, len)
249    }
250
251    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
252        self.serialize_seq(Some(len))
253    }
254
255    fn serialize_tuple_struct(
256        self,
257        _name: &'static str,
258        len: usize,
259    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
260        self.serialize_seq(Some(len))
261    }
262
263    fn serialize_tuple_variant(
264        self,
265        _name: &'static str,
266        _variant_index: u32,
267        variant: &'static str,
268        len: usize,
269    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
270        SerializeTupleVariant::tuple(self.dst, variant, len, self.style)
271    }
272
273    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
274        SerializeMap::map(self.dst, self.style)
275    }
276
277    fn serialize_struct(
278        self,
279        name: &'static str,
280        _len: usize,
281    ) -> Result<Self::SerializeStruct, Self::Error> {
282        SerializeMap::struct_(name, self.dst, self.style)
283    }
284
285    fn serialize_struct_variant(
286        self,
287        _name: &'static str,
288        _variant_index: u32,
289        variant: &'static str,
290        len: usize,
291    ) -> Result<Self::SerializeStructVariant, Self::Error> {
292        SerializeStructVariant::struct_(self.dst, variant, len, self.style)
293    }
294}