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