TOML
Recipe | Crates | Categories |
---|---|---|
basic_toml | ||
toml_edit | ||
toml |
toml
⮳ is the primary crate.
toml
toml
⮳ is a native Rust encoder and decoder of TOML-formatted files and streams. Provides implementations of the standard Serialize/Deserialize traits for TOML data to facilitate deserializing and serializing Rust structures.
//! Example demonstrating TOML parsing and deserialization. use serde::Deserialize; use toml::value::Datetime; #[derive(Deserialize, Debug)] struct Config { title: String, database: Database, } #[derive(Deserialize, Debug)] struct Database { server: String, ports: Vec<u32>, connection_max: u32, enabled: bool, date: Datetime, } /// Demonstrates parsing a TOML string into a `Config` struct. /// /// It uses `toml::from_str` to parse a string into a /// `Config` struct. fn main() { let toml_string = r#" title = "TOML Example" [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true date = 1979-05-27T07:32:00Z "#; let parsed_toml: Config = toml::from_str(toml_string).unwrap(); println!("{:#?}", parsed_toml); }
toml_edit
toml_edit
⮳ is a format-preserving TOML parser.
//! This example demonstrates how to use the `toml_edit` crate to //! parse, modify, and print TOML documents while preserving the //! original formatting (comments, spaces and relative order or items). //! //! Use `toml_edit` instead of `toml` for format-preserving editing or finer //! control over output. use toml_edit::DocumentMut; use toml_edit::Item; use toml_edit::value; fn main() -> anyhow::Result<()> { // Parse existing TOML, here a `Cargo.toml` file: let toml_content = r#" [package] name = "my-package" version = "0.1.0" authors = ["Me <me@example.com>"] [dependencies] serde = "1.0" tokio = { version = "1.0", features = ["full"] } [[bin]] name = "app" path = "src/main.rs" "#; // Parse the document. let mut doc: DocumentMut = toml_content.parse::<DocumentMut>()?; // Modify values. doc["package"]["version"] = value("0.2.0"); // Add a new dependency. doc["dependencies"]["toml_edit"] = value("0.22.24"); // Add a feature to an existing dependency. // `Item` is an enum representing either a value, a table, an array of // tables, or none. if let Some(Item::Value(tokio)) = doc .get_mut("dependencies") .and_then(|deps| deps.get_mut("tokio")) { if let Some(t) = tokio.as_inline_table_mut() { let features = t .get_mut("features") .and_then(|f| f.as_array_mut()) .expect("`tokio` features should be an array"); features.push("time"); } } // Add a new table. let mut dev_deps = toml_edit::table(); // Empty table. dev_deps .as_table_mut() .unwrap() .insert("pretty_assertions", value("1.4.1")); doc.insert("dev-dependencies", dev_deps); // Add to the array of tables. if let Some(Item::ArrayOfTables(bins)) = doc.get_mut("bin") { let mut new_bin = toml_edit::Table::new(); new_bin.insert("name", value("cli")); new_bin.insert("path", value("src/cli.rs")); bins.push(new_bin); } // Print the modified document - calls `to_string()`. println!("{}", doc); Ok(()) }
basic_toml
basic_toml
⮳ is a minimal TOML library with few dependencies
//! This example demonstrates how to use the `basic-toml` crate to parse and //! serialize TOML data. //! //! Add to your `Cargo.toml`: //! ```toml //! [dependencies] //! basic-toml = "0.1.9" # Or latest //! chrono = { version = "0.4.40", features = [ "serde" ] } //! serde = { version = "1.0.219", features = [ "derive" ] } //! ``` use std::collections::HashMap; use std::fs; // Struct that will be serialized/deserialized. #[derive(Debug, serde::Serialize, serde::Deserialize)] struct Config { // Custom type. server: ServerConfig, // Hashmap. limits: HashMap<String, i64>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] struct ServerConfig { host: String, port: u16, // Option. debug: Option<bool>, // Vec. features: Vec<String>, // Custom serialization: timestamp in seconds since the epoch. #[serde(with = "chrono::serde::ts_seconds")] reset_datetime: chrono::DateTime<chrono::Utc>, } fn main() -> anyhow::Result<()> { // 1. Parse TOML from a string. let toml_str = r#" [server] host = "127.0.0.1" port = 8080 reset_datetime = 1431684000 features = ["auth", "api", "webhooks"] [limits] requests_per_minute = 60 max_payload_size = 1048576 "#; // Parse the TOML string into our `Config` struct. let config: Config = basic_toml::from_str(toml_str)?; println!("Parsed config: {:#?}", config); // 2. Convert back to TOML string. let modified_toml = basic_toml::to_string(&config)?; println!("\nModified TOML:\n{}", modified_toml); // 3. Write TOML to file. fs::write("temp/config.toml", &modified_toml)?; // 4. Read TOML from file. let file_content = fs::read_to_string("temp/config.toml")?; let file_config: Config = basic_toml::from_str(&file_content)?; println!("\nConfig from file: {:#?}", file_config); // 5. Error handling. let invalid_toml = r#" [server] host = 127.0.0.1 # Missing quotes around string port = "8080" # String instead of integer Missing fields "#; match basic_toml::from_str::<Config>(invalid_toml) { Ok(config) => println!("Successfully parsed: {:?}", config), Err(e) => println!("Parse error: {}", e), } Ok(()) }