Debian Codegraph @

debian/missing-sources/toml/src/ser/mod.rs

raw
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
7 #[cfg(feature = "display")]
8 mod document;
9 mod error;
10 #[cfg(feature = "display")]
11 mod style;
12 #[cfg(feature = "display")]
13 mod value;
14
15 use crate::alloc_prelude::*;
16
17 #[cfg(feature = "display")]
18 pub use document::Buffer;
19 #[cfg(feature = "display")]
20 pub use document::Serializer;
21 pub use error::Error;
22 pub(crate) use error::ErrorInner;
23 #[cfg(feature = "display")]
24 pub use value::ValueSerializer;
25
26 /// Serialize the given data structure as a String of TOML.
27 ///
28 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
29 /// fail, if `T` contains a map with non-string keys, or if `T` attempts to
30 /// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
31 ///
32 /// To serialize TOML values, instead of documents, see [`ValueSerializer`].
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use serde::Serialize;
38 ///
39 /// #[derive(Serialize)]
40 /// struct Config {
41 /// database: Database,
42 /// }
43 ///
44 /// #[derive(Serialize)]
45 /// struct Database {
46 /// ip: String,
47 /// port: Vec<u16>,
48 /// connection_max: u32,
49 /// enabled: bool,
50 /// }
51 ///
52 /// let config = Config {
53 /// database: Database {
54 /// ip: "192.168.1.1".to_string(),
55 /// port: vec![8001, 8002, 8003],
56 /// connection_max: 5000,
57 /// enabled: false,
58 /// },
59 /// };
60 ///
61 /// let toml = toml::to_string(&config).unwrap();
62 /// println!("{}", toml)
63 /// ```
64 #[cfg(feature = "display")]
65 pub fn to_string<T>(value: &T) -> Result<String, Error>
66 where
67 T: serde_core::ser::Serialize + ?Sized,
68 {
69 let mut output = Buffer::new();
70 let serializer = Serializer::new(&mut output);
71 value.serialize(serializer)?;
72 Ok(output.to_string())
73 }
74
75 /// Serialize the given data structure as a "pretty" String of TOML.
76 ///
77 /// This is identical to `to_string` except the output string has a more
78 /// "pretty" output. See `Serializer::pretty` for more details.
79 ///
80 /// To serialize TOML values, instead of documents, see [`ValueSerializer`].
81 ///
82 /// For greater customization, instead serialize to a
83 /// [`toml_edit::DocumentMut`](https://docs.rs/toml_edit/latest/toml_edit/struct.DocumentMut.html).
84 #[cfg(feature = "display")]
85 pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
86 where
87 T: serde_core::ser::Serialize + ?Sized,
88 {
89 let mut output = Buffer::new();
90 let serializer = Serializer::pretty(&mut output);
91 value.serialize(serializer)?;
92 Ok(output.to_string())
93 }