Skip to main content

toml/
table.rs

1use serde_core::de;
2use serde_core::ser;
3
4use crate::Value;
5use crate::alloc_prelude::*;
6use crate::map::Map;
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_core::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) = visitor.next_key::<String>()? {
106                    match values.entry(key) {
107                        crate::map::Entry::Vacant(vacant) => {
108                            vacant.insert(visitor.next_value()?);
109                        }
110                        crate::map::Entry::Occupied(occupied) => {
111                            let key = occupied.key();
112                            let msg = format!("duplicate key: `{key}`");
113                            return Err(de::Error::custom(msg));
114                        }
115                    }
116                }
117
118                Ok(values)
119            }
120        }
121
122        deserializer.deserialize_map(Visitor)
123    }
124}
125
126impl<'de> de::Deserializer<'de> for Table {
127    type Error = crate::de::Error;
128
129    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
130    where
131        V: de::Visitor<'de>,
132    {
133        Value::Table(self).deserialize_any(visitor)
134    }
135
136    #[inline]
137    fn deserialize_enum<V>(
138        self,
139        name: &'static str,
140        variants: &'static [&'static str],
141        visitor: V,
142    ) -> Result<V::Value, crate::de::Error>
143    where
144        V: de::Visitor<'de>,
145    {
146        Value::Table(self).deserialize_enum(name, variants, visitor)
147    }
148
149    // `None` is interpreted as a missing field so be sure to implement `Some`
150    // as a present field.
151    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
152    where
153        V: de::Visitor<'de>,
154    {
155        Value::Table(self).deserialize_option(visitor)
156    }
157
158    fn deserialize_newtype_struct<V>(
159        self,
160        name: &'static str,
161        visitor: V,
162    ) -> Result<V::Value, crate::de::Error>
163    where
164        V: de::Visitor<'de>,
165    {
166        Value::Table(self).deserialize_newtype_struct(name, visitor)
167    }
168
169    fn deserialize_struct<V>(
170        self,
171        name: &'static str,
172        fields: &'static [&'static str],
173        visitor: V,
174    ) -> Result<V::Value, crate::de::Error>
175    where
176        V: de::Visitor<'de>,
177    {
178        Value::Table(self).deserialize_struct(name, fields, visitor)
179    }
180
181    serde_core::forward_to_deserialize_any! {
182        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
183        bytes byte_buf map unit_struct tuple_struct
184        tuple ignored_any identifier
185    }
186}
187
188impl de::IntoDeserializer<'_, crate::de::Error> for Table {
189    type Deserializer = Self;
190
191    fn into_deserializer(self) -> Self {
192        self
193    }
194}
195
196pub(crate) struct TableSerializer;
197
198impl ser::Serializer for TableSerializer {
199    type Ok = Table;
200    type Error = crate::ser::Error;
201
202    type SerializeSeq = ser::Impossible<Self::Ok, Self::Error>;
203    type SerializeTuple = ser::Impossible<Self::Ok, Self::Error>;
204    type SerializeTupleStruct = ser::Impossible<Self::Ok, Self::Error>;
205    type SerializeTupleVariant = ser::Impossible<Self::Ok, Self::Error>;
206    type SerializeMap = SerializeMap;
207    type SerializeStruct = SerializeMap;
208    type SerializeStructVariant = ser::Impossible<Self::Ok, Self::Error>;
209
210    fn serialize_bool(self, _value: bool) -> Result<Table, crate::ser::Error> {
211        Err(crate::ser::Error::unsupported_type(None))
212    }
213
214    fn serialize_i8(self, _value: i8) -> Result<Table, crate::ser::Error> {
215        Err(crate::ser::Error::unsupported_type(None))
216    }
217
218    fn serialize_i16(self, _value: i16) -> Result<Table, crate::ser::Error> {
219        Err(crate::ser::Error::unsupported_type(None))
220    }
221
222    fn serialize_i32(self, _value: i32) -> Result<Table, crate::ser::Error> {
223        Err(crate::ser::Error::unsupported_type(None))
224    }
225
226    fn serialize_i64(self, _value: i64) -> Result<Table, crate::ser::Error> {
227        Err(crate::ser::Error::unsupported_type(None))
228    }
229
230    fn serialize_u8(self, _value: u8) -> Result<Table, crate::ser::Error> {
231        Err(crate::ser::Error::unsupported_type(None))
232    }
233
234    fn serialize_u16(self, _value: u16) -> Result<Table, crate::ser::Error> {
235        Err(crate::ser::Error::unsupported_type(None))
236    }
237
238    fn serialize_u32(self, _value: u32) -> Result<Table, crate::ser::Error> {
239        Err(crate::ser::Error::unsupported_type(None))
240    }
241
242    fn serialize_u64(self, _value: u64) -> Result<Table, crate::ser::Error> {
243        Err(crate::ser::Error::unsupported_type(None))
244    }
245
246    fn serialize_f32(self, _value: f32) -> Result<Table, crate::ser::Error> {
247        Err(crate::ser::Error::unsupported_type(None))
248    }
249
250    fn serialize_f64(self, _value: f64) -> Result<Table, crate::ser::Error> {
251        Err(crate::ser::Error::unsupported_type(None))
252    }
253
254    fn serialize_char(self, _value: char) -> Result<Table, crate::ser::Error> {
255        Err(crate::ser::Error::unsupported_type(None))
256    }
257
258    fn serialize_str(self, _value: &str) -> Result<Table, crate::ser::Error> {
259        Err(crate::ser::Error::unsupported_type(None))
260    }
261
262    fn serialize_bytes(self, _value: &[u8]) -> Result<Table, crate::ser::Error> {
263        Err(crate::ser::Error::unsupported_type(None))
264    }
265
266    fn serialize_unit(self) -> Result<Table, crate::ser::Error> {
267        Err(crate::ser::Error::unsupported_type(None))
268    }
269
270    fn serialize_unit_struct(self, _name: &'static str) -> Result<Table, crate::ser::Error> {
271        Err(crate::ser::Error::unsupported_type(None))
272    }
273
274    fn serialize_unit_variant(
275        self,
276        name: &'static str,
277        _variant_index: u32,
278        _variant: &'static str,
279    ) -> Result<Table, crate::ser::Error> {
280        Err(crate::ser::Error::unsupported_type(Some(name)))
281    }
282
283    fn serialize_newtype_struct<T>(
284        self,
285        _name: &'static str,
286        value: &T,
287    ) -> Result<Table, crate::ser::Error>
288    where
289        T: ser::Serialize + ?Sized,
290    {
291        value.serialize(self)
292    }
293
294    fn serialize_newtype_variant<T>(
295        self,
296        _name: &'static str,
297        _variant_index: u32,
298        variant: &'static str,
299        value: &T,
300    ) -> Result<Table, crate::ser::Error>
301    where
302        T: ser::Serialize + ?Sized,
303    {
304        let value = value.serialize(crate::value::ValueSerializer)?;
305        let mut table = Table::new();
306        table.insert(variant.to_owned(), value);
307        Ok(table)
308    }
309
310    fn serialize_none(self) -> Result<Table, crate::ser::Error> {
311        Err(crate::ser::Error::unsupported_none())
312    }
313
314    fn serialize_some<T>(self, value: &T) -> Result<Table, crate::ser::Error>
315    where
316        T: ser::Serialize + ?Sized,
317    {
318        value.serialize(self)
319    }
320
321    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
322        Err(crate::ser::Error::unsupported_type(None))
323    }
324
325    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
326        Err(crate::ser::Error::unsupported_type(None))
327    }
328
329    fn serialize_tuple_struct(
330        self,
331        name: &'static str,
332        _len: usize,
333    ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
334        Err(crate::ser::Error::unsupported_type(Some(name)))
335    }
336
337    fn serialize_tuple_variant(
338        self,
339        name: &'static str,
340        _variant_index: u32,
341        _variant: &'static str,
342        _len: usize,
343    ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
344        Err(crate::ser::Error::unsupported_type(Some(name)))
345    }
346
347    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
348        Ok(SerializeMap::new())
349    }
350
351    fn serialize_struct(
352        self,
353        _name: &'static str,
354        len: usize,
355    ) -> Result<Self::SerializeStruct, crate::ser::Error> {
356        self.serialize_map(Some(len))
357    }
358
359    fn serialize_struct_variant(
360        self,
361        name: &'static str,
362        _variant_index: u32,
363        _variant: &'static str,
364        _len: usize,
365    ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
366        Err(crate::ser::Error::unsupported_type(Some(name)))
367    }
368}
369
370pub(crate) struct SerializeMap {
371    map: Table,
372    next_key: Option<String>,
373}
374
375impl SerializeMap {
376    pub(crate) fn new() -> Self {
377        Self {
378            map: Table::new(),
379            next_key: None,
380        }
381    }
382
383    pub(crate) fn with_capacity(capacity: usize) -> Self {
384        Self {
385            map: Table::with_capacity(capacity),
386            next_key: None,
387        }
388    }
389}
390
391impl ser::SerializeMap for SerializeMap {
392    type Ok = Table;
393    type Error = crate::ser::Error;
394
395    fn serialize_key<T>(&mut self, key: &T) -> Result<(), crate::ser::Error>
396    where
397        T: ser::Serialize + ?Sized,
398    {
399        match Value::try_from(key)? {
400            Value::String(s) => self.next_key = Some(s),
401            _ => return Err(crate::ser::Error::key_not_string()),
402        };
403        Ok(())
404    }
405
406    fn serialize_value<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
407    where
408        T: ser::Serialize + ?Sized,
409    {
410        let key = self.next_key.take();
411        let key = key.expect("serialize_value called before serialize_key");
412        match Value::try_from(value) {
413            Ok(value) => {
414                self.map.insert(key, value);
415            }
416            Err(crate::ser::Error {
417                inner: crate::ser::ErrorInner::UnsupportedNone,
418            }) => {}
419            Err(e) => return Err(e),
420        }
421        Ok(())
422    }
423
424    fn end(self) -> Result<Table, crate::ser::Error> {
425        Ok(self.map)
426    }
427}
428
429impl ser::SerializeStruct for SerializeMap {
430    type Ok = Table;
431    type Error = crate::ser::Error;
432
433    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), crate::ser::Error>
434    where
435        T: ser::Serialize + ?Sized,
436    {
437        ser::SerializeMap::serialize_key(self, key)?;
438        ser::SerializeMap::serialize_value(self, value)
439    }
440
441    fn end(self) -> Result<Table, crate::ser::Error> {
442        ser::SerializeMap::end(self)
443    }
444}