Skip to main content

toml_edit/ser/
mod.rs

1//! Serializing Rust structures into TOML.
2//!
3//! This module contains all the Serde support for serializing Rust structures into TOML.
4
5mod array;
6mod error;
7mod key;
8mod map;
9mod pretty;
10mod value;
11
12use crate::visit_mut::VisitMut as _;
13#[allow(clippy::wildcard_imports)]
14use array::*;
15#[allow(clippy::wildcard_imports)]
16use map::*;
17
18pub use error::Error;
19pub use value::ValueSerializer;
20
21/// Serialize the given data structure as a TOML byte vector.
22///
23/// Serialization can fail if `T`'s implementation of `Serialize` decides to
24/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
25/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
26#[cfg(feature = "display")]
27pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
28where
29    T: serde_core::ser::Serialize + ?Sized,
30{
31    to_string(value).map(|e| e.into_bytes())
32}
33
34/// Serialize the given data structure as a String of TOML.
35///
36/// Serialization can fail if `T`'s implementation of `Serialize` decides to
37/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
38/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
39///
40/// # Examples
41///
42/// ```
43/// use serde::Serialize;
44///
45/// #[derive(Serialize)]
46/// struct Config {
47///     database: Database,
48/// }
49///
50/// #[derive(Serialize)]
51/// struct Database {
52///     ip: String,
53///     port: Vec<u16>,
54///     connection_max: u32,
55///     enabled: bool,
56/// }
57///
58/// let config = Config {
59///     database: Database {
60///         ip: "192.168.1.1".to_string(),
61///         port: vec![8001, 8002, 8003],
62///         connection_max: 5000,
63///         enabled: false,
64///     },
65/// };
66///
67/// let toml = toml_edit::ser::to_string(&config).unwrap();
68/// println!("{}", toml)
69/// ```
70#[cfg(feature = "display")]
71pub fn to_string<T>(value: &T) -> Result<String, Error>
72where
73    T: serde_core::ser::Serialize + ?Sized,
74{
75    to_document(value).map(document_to_string)
76}
77
78/// Serialize the given data structure as a "pretty" String of TOML.
79///
80/// This is identical to [`to_string`] except the output string has a more
81/// "pretty" output.
82#[cfg(feature = "display")]
83pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
84where
85    T: serde_core::ser::Serialize + ?Sized,
86{
87    let mut document = to_document(value)?;
88    pretty::Pretty::new().visit_document_mut(&mut document);
89    Ok(document_to_string(document))
90}
91
92#[cfg(feature = "display")]
93fn document_to_string(document: crate::DocumentMut) -> String {
94    use std::fmt::Write as _;
95
96    let mut output = String::with_capacity(128);
97    write!(output, "{document}").expect("writing to a String cannot fail");
98    output
99}
100
101/// Serialize the given data structure into a TOML document.
102///
103/// This would allow custom formatting to be applied, mixing with format preserving edits, etc.
104pub fn to_document<T>(value: &T) -> Result<crate::DocumentMut, Error>
105where
106    T: serde_core::ser::Serialize + ?Sized,
107{
108    let value = value.serialize(ValueSerializer::new())?;
109    let item = crate::Item::Value(value);
110    let root = item
111        .into_table()
112        .map_err(|_| Error::UnsupportedType(None))?;
113    Ok(root.into())
114}