Expand description
High-performance, fast compiling, TOML serialization and deserialization library for rust with full compliance with the TOML 1.1 spec.
§Parsing and Traversal
Use parse with a TOML string and an Arena to get a Document.
let arena = toml_spanner::Arena::new();
let doc = toml_spanner::parse("key = 'value'", &arena).unwrap();Traverse the tree via index operators, which return a MaybeItem:
let name: Option<&str> = doc["name"].as_str();
let numbers: Option<i64> = doc["numbers"][50].as_i64();Use MaybeItem::item() to get an Item containing a Value and Span.
let Some(item) = doc["item"].item() else {
panic!("Missing key `item`");
};
match item.value() {
Value::String(string) => {},
Value::Integer(integer) => {}
Value::Float(float) => {},
Value::Boolean(boolean) => {},
Value::Array(array) => {},
Value::Table(table) => {},
Value::DateTime(date_time) => {},
}
// Get byte offset of where item was defined in the source.
let Span{start, end} = item.span();§Deserialization
Document::table_helper() creates a TableHelper for type-safe field extraction
via FromToml. Errors accumulate in the Document’s context rather than
failing on the first error.
let mut helper = doc.table_helper();
let name: Option<String> = helper.optional("name");Item::parse extracts values from string items via std::str::FromStr.
let item = doc["ip-address"].item().unwrap();
let ip: std::net::Ipv4Addr = item.parse()?;Toggle More Extensive Example
use toml_spanner::{Arena, FromToml, Item, Context, Failed, TableHelper};
#[derive(Debug)]
struct Things {
name: String,
value: u32,
color: Option<String>,
}
impl<'de> FromToml<'de> for Things {
fn from_toml(ctx: &mut Context<'de>, value: &Item<'de>) -> Result<Self, Failed> {
let mut th = value.table_helper(ctx)?;
let name = th.required("name")?;
let value = th.required("value")?;
let color = th.optional("color");
th.require_empty()?;
Ok(Things { name, value, color })
}
}
let content = r#"
dev-mode = true
[[things]]
name = "hammer"
value = 43
[[things]]
name = "drill"
value = 300
color = "green"
"#;
let arena = Arena::new();
let mut doc = toml_spanner::parse(content, &arena).unwrap();
// Null-coalescing index operators: missing keys return a None-like
// MaybeItem instead of panicking.
assert_eq!(doc["things"][0]["color"].as_str(), None);
assert_eq!(doc["things"][1]["color"].as_str(), Some("green"));
// Deserialize typed values out of the document table.
let mut helper = doc.table_helper();
let things: Vec<Things> = helper.required("things").ok().unwrap();
let dev_mode: bool = helper.optional("dev-mode").unwrap_or(false);
// Error if unconsumed fields remain.
helper.require_empty().ok();
assert_eq!(things.len(), 2);
assert_eq!(things[0].name, "hammer");
assert!(dev_mode);§Derive Macro
The Toml derive macro generates FromToml and ToToml
implementations. A bare #[derive(Toml)] generates FromToml only.
Annotate with #[toml(Toml)] for both directions.
use toml_spanner::{Arena, Toml};
#[derive(Debug, Toml)]
#[toml(Toml)]
struct Config {
name: String,
port: u16,
#[toml(default)]
debug: bool,
}
let arena = Arena::new();
let mut doc = toml_spanner::parse("name = 'app'\nport = 8080", &arena).unwrap();
let config = doc.to::<Config>().unwrap();
assert_eq!(config.name, "app");
let output = toml_spanner::to_string(&config).unwrap();
assert!(output.contains("name = \"app\""));See the Toml macro documentation for all supported attributes
(rename, default, flatten, skip, tagged enums, etc.).
§Serialization
Types implementing ToToml can be written back to TOML text with
to_string or the Formatting builder for more control.
use toml_spanner::{Arena, Formatting};
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert("key", "value");
// Using default formatting.
let output = toml_spanner::to_string(&map).unwrap();
// Preserve formatting from a parsed document
let arena = Arena::new();
let doc = toml_spanner::parse("key = \"old\"\n", &arena).unwrap();
let output = Formatting::preserved_from(&doc).format(&map).unwrap();See Formatting for indentation, format preservation, and other options.
Modules§
- helper
from-toml - Contains submodules for use with the
#[toml(with = ...)]field attribute. - impl_
serde serde - Serde serialization support for
Spanned<T>andItem.
Structs§
- Arena
- Bump allocator backing all data structures produced by the parser.
- Array
- A TOML array with span information.
- Context
from-toml - Shared state that accumulates errors and holds the arena.
- Date
- A calendar date with year, month, and day components.
- Date
Time - Container for temporal values for TOML format, based on RFC 3339.
- Document
- The result of parsing a TOML document.
- Error
- A single error from parsing or converting a TOML document.
- Failed
- Error sentinel indicating a failure.
- Formatting
to-toml - Controls how TOML output is formatted when serializing.
- From
Toml Error from-toml - Collects errors encountered during parsing and conversion.
- Integer
- A TOML integer value.
- Item
- A parsed TOML value with span information.
- Key
- A TOML table key with its source span.
- Maybe
Item - A nullable reference to a parsed TOML value.
- Owned
Item - A self-contained TOML value that owns its backing storage.
- Owned
Table - A self-contained TOML table that owns its backing storage.
- Span
- A byte-offset range within a TOML document.
- Spanned
- Wraps a value
Twith its sourceSpan. - Table
- A TOML table, a transient collection of key/value pairs inside an
Item. - Table
Helper from-toml - Guides extraction from a
Tableby tracking which fields have been consumed. - Time
- Represents the time of day portion of a TOML datetime value.
- ToToml
Error to-toml - An error produced during
ToTomlconversion or TOML emission. - Toml
Path - Represents the dotted path to a value within a TOML document.
Enums§
- Array
Style - How a TOML array is spelled in source text.
- Error
Kind - The specific kind of error.
- Indent
to-toml - Indentation unit for expanded inline arrays.
- Kind
- Discriminant for the TOML value types stored in an
Item. - Table
Style - How a TOML table is spelled in source text.
- Time
Offset - A UTC offset attached to an offset date-time.
- Value
- Borrowed view into an
Itemfor pattern matching. - Value
Mut - Mutable view into an
Itemfor pattern matching.
Traits§
- From
Flattened from-toml - Trait for types that can be constructed from flattened TOML table entries.
- From
Toml from-toml - Converts a TOML
Iteminto a Rust type. - ToFlattened
to-toml - Trait for types that can be converted into flattened TOML table entries.
- ToToml
to-toml - Converts a Rust type into a TOML
Itemtree.
Functions§
- from_
str from-toml - Parses and deserializes a TOML document in one step.
- parse
- Parses a TOML document and returns a
Documentcontaining the parsed tree. - parse_
recoverable from-toml - Parses a TOML document in recovery mode, accumulating errors instead of stopping on the first one.
- to_
string to-toml - Serializes a
ToTomlvalue into a TOML document string with default formatting.
Derive Macros§
- Toml
derive - Unified derive macro for implementing TOML conversion traits.