Skip to main content

toml/ser/document/
mod.rs

1//! Serializing Rust structures into TOML.
2//!
3//! This module contains all the Serde support for serializing Rust structures
4//! into TOML documents (as strings). Note that some top-level functions here
5//! are also provided at the top of the crate.
6
7mod array;
8mod array_of_tables;
9mod buffer;
10mod map;
11mod strategy;
12
13use toml_writer::TomlWrite as _;
14
15use super::Error;
16use super::style;
17use super::value;
18use buffer::Table;
19use strategy::SerializationStrategy;
20
21pub use buffer::Buffer;
22
23/// Serialization for TOML documents.
24///
25/// This structure implements serialization support for TOML to serialize an
26/// arbitrary type to TOML. Note that the TOML format does not support all
27/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
28/// will generate an error when serialized.
29///
30/// Currently a serializer always writes its output to an in-memory `String`,
31/// which is passed in when creating the serializer itself.
32///
33/// To serialize TOML values, instead of documents, see
34/// [`ValueSerializer`][super::value::ValueSerializer].
35pub struct Serializer<'d> {
36    buf: &'d mut Buffer,
37    style: style::Style,
38    table: Table,
39}
40
41impl<'d> Serializer<'d> {
42    /// Creates a new serializer which will emit TOML into the buffer provided.
43    ///
44    /// The serializer can then be used to serialize a type after which the data
45    /// will be present in `buf`.
46    pub fn new(buf: &'d mut Buffer) -> Self {
47        let table = buf.root_table();
48        Self {
49            buf,
50            style: Default::default(),
51            table,
52        }
53    }
54
55    /// Apply a default "pretty" policy to the document
56    ///
57    /// For greater customization, instead serialize to a
58    /// [`toml_edit::DocumentMut`](https://docs.rs/toml_edit/latest/toml_edit/struct.DocumentMut.html).
59    pub fn pretty(buf: &'d mut Buffer) -> Self {
60        let mut ser = Serializer::new(buf);
61        ser.style.multiline_array = true;
62        ser
63    }
64
65    pub(crate) fn with_table(buf: &'d mut Buffer, table: Table, style: style::Style) -> Self {
66        Self { buf, style, table }
67    }
68
69    fn end(self) -> Result<&'d mut Buffer, Error> {
70        self.buf.push(self.table);
71        Ok(self.buf)
72    }
73}
74
75impl<'d> serde_core::ser::Serializer for Serializer<'d> {
76    type Ok = &'d mut Buffer;
77    type Error = Error;
78    type SerializeSeq = serde_core::ser::Impossible<Self::Ok, Self::Error>;
79    type SerializeTuple = serde_core::ser::Impossible<Self::Ok, Self::Error>;
80    type SerializeTupleStruct = serde_core::ser::Impossible<Self::Ok, Self::Error>;
81    type SerializeTupleVariant = array::SerializeDocumentTupleVariant<'d>;
82    type SerializeMap = map::SerializeDocumentTable<'d>;
83    type SerializeStruct = map::SerializeDocumentTable<'d>;
84    type SerializeStructVariant = map::SerializeDocumentTable<'d>;
85
86    fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
87        Err(Error::unsupported_type(Some("bool")))
88    }
89
90    fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
91        Err(Error::unsupported_type(Some("i8")))
92    }
93
94    fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
95        Err(Error::unsupported_type(Some("i16")))
96    }
97
98    fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
99        Err(Error::unsupported_type(Some("i32")))
100    }
101
102    fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
103        Err(Error::unsupported_type(Some("i64")))
104    }
105
106    fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
107        Err(Error::unsupported_type(Some("u8")))
108    }
109
110    fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
111        Err(Error::unsupported_type(Some("u16")))
112    }
113
114    fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
115        Err(Error::unsupported_type(Some("u32")))
116    }
117
118    fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
119        Err(Error::unsupported_type(Some("u64")))
120    }
121
122    fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
123        Err(Error::unsupported_type(Some("f32")))
124    }
125
126    fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
127        Err(Error::unsupported_type(Some("f64")))
128    }
129
130    fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
131        Err(Error::unsupported_type(Some("char")))
132    }
133
134    fn serialize_str(self, _v: &str) -> Result<Self::Ok, Self::Error> {
135        Err(Error::unsupported_type(Some("str")))
136    }
137
138    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
139        Err(Error::unsupported_type(Some("bytes")))
140    }
141
142    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
143        Err(Error::unsupported_none())
144    }
145
146    fn serialize_some<T>(self, v: &T) -> Result<Self::Ok, Self::Error>
147    where
148        T: serde_core::ser::Serialize + ?Sized,
149    {
150        v.serialize(self)
151    }
152
153    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
154        Err(Error::unsupported_type(Some("unit")))
155    }
156
157    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
158        Err(Error::unsupported_type(Some(name)))
159    }
160
161    fn serialize_unit_variant(
162        self,
163        name: &'static str,
164        _variant_index: u32,
165        _variant: &'static str,
166    ) -> Result<Self::Ok, Self::Error> {
167        Err(Error::unsupported_type(Some(name)))
168    }
169
170    fn serialize_newtype_struct<T>(
171        self,
172        _name: &'static str,
173        v: &T,
174    ) -> Result<Self::Ok, Self::Error>
175    where
176        T: serde_core::ser::Serialize + ?Sized,
177    {
178        v.serialize(self)
179    }
180
181    fn serialize_newtype_variant<T>(
182        mut self,
183        _name: &'static str,
184        _variant_index: u32,
185        variant: &'static str,
186        value: &T,
187    ) -> Result<Self::Ok, Self::Error>
188    where
189        T: serde_core::ser::Serialize + ?Sized,
190    {
191        match SerializationStrategy::from(value) {
192            SerializationStrategy::Value | SerializationStrategy::ArrayOfTables => {
193                let dst = self.buf.ensure_body(&mut self.table);
194
195                dst.key(variant)?;
196                dst.space()?;
197                dst.keyval_sep()?;
198                dst.space()?;
199                let value_serializer = value::ValueSerializer::with_style(dst, self.style);
200                let dst = value.serialize(value_serializer)?;
201                dst.newline()?;
202            }
203            SerializationStrategy::Table | SerializationStrategy::Unknown => {
204                let child = self
205                    .buf
206                    .child_table(&mut self.table, |dst| dst.key(variant).map_err(Error::from))?;
207                let value_serializer = Serializer::with_table(self.buf, child, self.style);
208                value.serialize(value_serializer)?;
209            }
210            SerializationStrategy::Skip => {
211                // silently drop these key-value pairs
212            }
213        }
214
215        self.end()
216    }
217
218    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
219        Err(Error::unsupported_type(Some("array")))
220    }
221
222    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
223        self.serialize_seq(Some(len))
224    }
225
226    fn serialize_tuple_struct(
227        self,
228        _name: &'static str,
229        len: usize,
230    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
231        self.serialize_seq(Some(len))
232    }
233
234    fn serialize_tuple_variant(
235        self,
236        _name: &'static str,
237        _variant_index: u32,
238        variant: &'static str,
239        len: usize,
240    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
241        array::SerializeDocumentTupleVariant::tuple(self.buf, self.table, variant, len, self.style)
242    }
243
244    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
245        map::SerializeDocumentTable::map(self.buf, self.table, self.style)
246    }
247
248    fn serialize_struct(
249        self,
250        _name: &'static str,
251        len: usize,
252    ) -> Result<Self::SerializeStruct, Self::Error> {
253        self.serialize_map(Some(len))
254    }
255
256    fn serialize_struct_variant(
257        mut self,
258        _name: &'static str,
259        _variant_index: u32,
260        variant: &'static str,
261        _len: usize,
262    ) -> Result<Self::SerializeStructVariant, Self::Error> {
263        let child = self
264            .buf
265            .child_table(&mut self.table, |dst| dst.key(variant).map_err(Error::from))?;
266        self.buf.push(self.table);
267        map::SerializeDocumentTable::map(self.buf, child, self.style)
268    }
269}