toml/
table.rs

1use serde::de;
2use serde::ser;
3
4use crate::alloc_prelude::*;
5use crate::map::Map;
6use crate::Value;
7
8/// Type representing a TOML table, payload of the `Value::Table` variant.
9///
10/// By default it entries are stored in
11/// [lexicographic order](https://doc.rust-lang.org/std/primitive.str.html#impl-Ord-for-str)
12/// of the keys. Enable the `preserve_order` feature to store entries in the order they appear in
13/// the source file.
14pub type Table = Map<String, Value>;
15
16impl Table {
17    /// Convert a `T` into `toml::Table`.
18    ///
19    /// This conversion can fail if `T`'s implementation of `Serialize` decides to
20    /// fail, or if `T` contains a map with non-string keys.
21    pub fn try_from<T>(value: T) -> Result<Self, crate::ser::Error>
22    where
23        T: ser::Serialize,
24    {
25        value.serialize(TableSerializer)
26    }
27
28    /// Interpret a `toml::Table` as an instance of type `T`.
29    ///
30    /// This conversion can fail if the structure of the `Table` does not match the structure
31    /// expected by `T`, for example if `T` is a bool which can't be mapped to a `Table`. It can
32    /// also fail if the structure is correct but `T`'s implementation of `Deserialize` decides
33    /// that something is wrong with the data, for example required struct fields are missing from
34    /// the TOML map or some number is too big to fit in the expected primitive type.
35    pub fn try_into<'de, T>(self) -> Result<T, crate::de::Error>
36    where
37        T: de::Deserialize<'de>,
38    {
39        de::Deserialize::deserialize(self)
40    }
41}
42
43#[cfg(feature = "display")]
44impl core::fmt::Display for Table {
45    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
46        crate::ser::to_string(self)
47            .expect("Unable to represent value as string")
48            .fmt(f)
49    }
50}
51
52#[cfg(feature = "parse")]
53impl core::str::FromStr for Table {
54    type Err = crate::de::Error;
55    fn from_str(s: &str) -> Result<Self, Self::Err> {
56        crate::from_str(s)
57    }
58}
59impl ser::Serialize for Table {
60    #[inline]
61    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62    where
63        S: ser::Serializer,
64    {
65        use serde::ser::SerializeMap;
66        let mut map = serializer.serialize_map(Some(self.len()))?;
67        for (k, v) in self {
68            map.serialize_key(k)?;
69            map.serialize_value(v)?;
70        }
71        map.end()
72    }
73}
74
75impl<'de> de::Deserialize<'de> for Table {
76    #[inline]
77    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
78    where
79        D: de::Deserializer<'de>,
80    {
81        struct Visitor;
82
83        impl<'de> de::Visitor<'de> for Visitor {
84            type Value = Map<String, Value>;
85
86            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
87                formatter.write_str("a map")
88            }
89
90            #[inline]
91            fn visit_unit<E>(self) -> Result<Self::Value, E>
92            where
93                E: de::Error,
94            {
95                Ok(Map::new())
96            }
97
98            #[inline]
99            fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
100            where
101                V: de::MapAccess<'de>,
102            {
103                let mut values = Map::new();
104
105                while let Some((key, value)) = visitor.next_entry()? {
106                    values.insert(key, value);
107                }
108
109                Ok(values)
110            }
111        }
112
113        deserializer.deserialize_map(Visitor)
114    }
115}
116
117impl<'de> de::Deserializer<'de> for Table {
118    type Error = crate::de::Error;
119
120    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
121    where
122        V: de::Visitor<'de>,
123    {
124        Value::Table(self).deserialize_any(visitor)
125    }
126
127    #[inline]
128    fn deserialize_enum<V>(
129        self,
130        name: &'static str,
131        variants: &'static [&'static str],
132        visitor: V,
133    ) -> Result<V::Value, crate::de::Error>
134    where
135        V: de::Visitor<'de>,
136    {
137        Value::Table(self).deserialize_enum(name, variants, visitor)
138    }
139
140    // `None` is interpreted as a missing field so be sure to implement `Some`
141    // as a present field.
142    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
143    where
144        V: de::Visitor<'de>,
145    {
146        Value::Table(self).deserialize_option(visitor)
147    }
148
149    fn deserialize_newtype_struct<V>(
150        self,
151        name: &'static str,
152        visitor: V,
153    ) -> Result<V::Value, crate::de::Error>
154    where
155        V: de::Visitor<'de>,
156    {
157        Value::Table(self).deserialize_newtype_struct(name, visitor)
158    }
159
160    serde::forward_to_deserialize_any! {
161        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
162        bytes byte_buf map unit_struct tuple_struct struct
163        tuple ignored_any identifier
164    }
165}
166
167impl de::IntoDeserializer<'_, crate::de::Error> for Table {
168    type Deserializer = Self;
169
170    fn into_deserializer(self) -> Self {
171        self
172    }
173}
174
175pub(crate) struct TableSerializer;
176
177impl ser::Serializer for TableSerializer {
178    type Ok = Table;
179    type Error = crate::ser::Error;
180
181    type SerializeSeq = ser::Impossible<Self::Ok, Self::Error>;
182    type SerializeTuple = ser::Impossible<Self::Ok, Self::Error>;
183    type SerializeTupleStruct = ser::Impossible<Self::Ok, Self::Error>;
184    type SerializeTupleVariant = ser::Impossible<Self::Ok, Self::Error>;
185    type SerializeMap = SerializeMap;
186    type SerializeStruct = SerializeMap;
187    type SerializeStructVariant = ser::Impossible<Self::Ok, Self::Error>;
188
189    fn serialize_bool(self, _value: bool) -> Result<Table, crate::ser::Error> {
190        Err(crate::ser::Error::unsupported_type(None))
191    }
192
193    fn serialize_i8(self, _value: i8) -> Result<Table, crate::ser::Error> {
194        Err(crate::ser::Error::unsupported_type(None))
195    }
196
197    fn serialize_i16(self, _value: i16) -> Result<Table, crate::ser::Error> {
198        Err(crate::ser::Error::unsupported_type(None))
199    }
200
201    fn serialize_i32(self, _value: i32) -> Result<Table, crate::ser::Error> {
202        Err(crate::ser::Error::unsupported_type(None))
203    }
204
205    fn serialize_i64(self, _value: i64) -> Result<Table, crate::ser::Error> {
206        Err(crate::ser::Error::unsupported_type(None))
207    }
208
209    fn serialize_u8(self, _value: u8) -> Result<Table, crate::ser::Error> {
210        Err(crate::ser::Error::unsupported_type(None))
211    }
212
213    fn serialize_u16(self, _value: u16) -> Result<Table, crate::ser::Error> {
214        Err(crate::ser::Error::unsupported_type(None))
215    }
216
217    fn serialize_u32(self, _value: u32) -> Result<Table, crate::ser::Error> {
218        Err(crate::ser::Error::unsupported_type(None))
219    }
220
221    fn serialize_u64(self, _value: u64) -> Result<Table, crate::ser::Error> {
222        Err(crate::ser::Error::unsupported_type(None))
223    }
224
225    fn serialize_f32(self, _value: f32) -> Result<Table, crate::ser::Error> {
226        Err(crate::ser::Error::unsupported_type(None))
227    }
228
229    fn serialize_f64(self, _value: f64) -> Result<Table, crate::ser::Error> {
230        Err(crate::ser::Error::unsupported_type(None))
231    }
232
233    fn serialize_char(self, _value: char) -> Result<Table, crate::ser::Error> {
234        Err(crate::ser::Error::unsupported_type(None))
235    }
236
237    fn serialize_str(self, _value: &str) -> Result<Table, crate::ser::Error> {
238        Err(crate::ser::Error::unsupported_type(None))
239    }
240
241    fn serialize_bytes(self, _value: &[u8]) -> Result<Table, crate::ser::Error> {
242        Err(crate::ser::Error::unsupported_type(None))
243    }
244
245    fn serialize_unit(self) -> Result<Table, crate::ser::Error> {
246        Err(crate::ser::Error::unsupported_type(None))
247    }
248
249    fn serialize_unit_struct(self, _name: &'static str) -> Result<Table, crate::ser::Error> {
250        Err(crate::ser::Error::unsupported_type(None))
251    }
252
253    fn serialize_unit_variant(
254        self,
255        name: &'static str,
256        _variant_index: u32,
257        _variant: &'static str,
258    ) -> Result<Table, crate::ser::Error> {
259        Err(crate::ser::Error::unsupported_type(Some(name)))
260    }
261
262    fn serialize_newtype_struct<T>(
263        self,
264        _name: &'static str,
265        value: &T,
266    ) -> Result<Table, crate::ser::Error>
267    where
268        T: ser::Serialize + ?Sized,
269    {
270        value.serialize(self)
271    }
272
273    fn serialize_newtype_variant<T>(
274        self,
275        _name: &'static str,
276        _variant_index: u32,
277        variant: &'static str,
278        value: &T,
279    ) -> Result<Table, crate::ser::Error>
280    where
281        T: ser::Serialize + ?Sized,
282    {
283        let value = value.serialize(crate::value::ValueSerializer)?;
284        let mut table = Table::new();
285        table.insert(variant.to_owned(), value);
286        Ok(table)
287    }
288
289    fn serialize_none(self) -> Result<Table, crate::ser::Error> {
290        Err(crate::ser::Error::unsupported_none())
291    }
292
293    fn serialize_some<T>(self, value: &T) -> Result<Table, crate::ser::Error>
294    where
295        T: ser::Serialize + ?Sized,
296    {
297        value.serialize(self)
298    }
299
300    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
301        Err(crate::ser::Error::unsupported_type(None))
302    }
303
304    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
305        Err(crate::ser::Error::unsupported_type(None))
306    }
307
308    fn serialize_tuple_struct(
309        self,
310        name: &'static str,
311        _len: usize,
312    ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
313        Err(crate::ser::Error::unsupported_type(Some(name)))
314    }
315
316    fn serialize_tuple_variant(
317        self,
318        name: &'static str,
319        _variant_index: u32,
320        _variant: &'static str,
321        _len: usize,
322    ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
323        Err(crate::ser::Error::unsupported_type(Some(name)))
324    }
325
326    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
327        Ok(SerializeMap::new())
328    }
329
330    fn serialize_struct(
331        self,
332        _name: &'static str,
333        len: usize,
334    ) -> Result<Self::SerializeStruct, crate::ser::Error> {
335        self.serialize_map(Some(len))
336    }
337
338    fn serialize_struct_variant(
339        self,
340        name: &'static str,
341        _variant_index: u32,
342        _variant: &'static str,
343        _len: usize,
344    ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
345        Err(crate::ser::Error::unsupported_type(Some(name)))
346    }
347}
348
349pub(crate) struct SerializeMap {
350    map: Table,
351    next_key: Option<String>,
352}
353
354impl SerializeMap {
355    pub(crate) fn new() -> Self {
356        Self {
357            map: Table::new(),
358            next_key: None,
359        }
360    }
361
362    pub(crate) fn with_capacity(capacity: usize) -> Self {
363        Self {
364            map: Table::with_capacity(capacity),
365            next_key: None,
366        }
367    }
368}
369
370impl ser::SerializeMap for SerializeMap {
371    type Ok = Table;
372    type Error = crate::ser::Error;
373
374    fn serialize_key<T>(&mut self, key: &T) -> Result<(), crate::ser::Error>
375    where
376        T: ser::Serialize + ?Sized,
377    {
378        match Value::try_from(key)? {
379            Value::String(s) => self.next_key = Some(s),
380            _ => return Err(crate::ser::Error::key_not_string()),
381        };
382        Ok(())
383    }
384
385    fn serialize_value<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
386    where
387        T: ser::Serialize + ?Sized,
388    {
389        let key = self.next_key.take();
390        let key = key.expect("serialize_value called before serialize_key");
391        match Value::try_from(value) {
392            Ok(value) => {
393                self.map.insert(key, value);
394            }
395            Err(crate::ser::Error {
396                inner: crate::ser::ErrorInner::UnsupportedNone,
397            }) => {}
398            Err(e) => return Err(e),
399        }
400        Ok(())
401    }
402
403    fn end(self) -> Result<Table, crate::ser::Error> {
404        Ok(self.map)
405    }
406}
407
408impl ser::SerializeStruct for SerializeMap {
409    type Ok = Table;
410    type Error = crate::ser::Error;
411
412    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), crate::ser::Error>
413    where
414        T: ser::Serialize + ?Sized,
415    {
416        ser::SerializeMap::serialize_key(self, key)?;
417        ser::SerializeMap::serialize_value(self, value)
418    }
419
420    fn end(self) -> Result<Table, crate::ser::Error> {
421        ser::SerializeMap::end(self)
422    }
423}