Skip to main content

Crate toml_spanner

Crate toml_spanner 

Source
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§

helperfrom-toml
Contains submodules for use with the #[toml(with = ...)] field attribute.
impl_serdeserde
Serde serialization support for Spanned<T> and Item.

Structs§

Arena
Bump allocator backing all data structures produced by the parser.
Array
A TOML array with span information.
Contextfrom-toml
Shared state that accumulates errors and holds the arena.
Date
A calendar date with year, month, and day components.
DateTime
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.
Formattingto-toml
Controls how TOML output is formatted when serializing.
FromTomlErrorfrom-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.
MaybeItem
A nullable reference to a parsed TOML value.
Span
A byte-offset range within a TOML document.
Spanned
Wraps a value T with its source Span.
Table
A TOML table, a transient collection of key/value pairs inside an Item.
TableHelperfrom-toml
Guides extraction from a Table by tracking which fields have been consumed.
Time
Represents the time of day portion of a TOML datetime value.
ToTomlErrorto-toml
An error produced during ToToml conversion or TOML emission.
TomlPath
Represents the dotted path to a value within a TOML document.

Enums§

ArrayStyle
The kind of a TOML array, distinguishing inline arrays from arrays of tables.
ErrorKind
The specific kind of error.
Indentto-toml
Indentation unit for expanded inline arrays.
Kind
Discriminant for the TOML value types stored in an Item.
TableStyle
The kind of a TOML table, distinguishing how it was defined in the source.
TimeOffset
A UTC offset attached to an offset date-time.
Value
Borrowed view into an Item for pattern matching.
ValueMut
Mutable view into an Item for pattern matching.

Traits§

FromFlattenedfrom-toml
Trait for types that can be constructed from flattened TOML table entries.
FromTomlfrom-toml
Trait for types that can be constructed from a TOML Item.
ToFlattenedto-toml
Trait for types that can be converted into flattened TOML table entries.
ToTomlto-toml
Trait for types that can be converted into a TOML Item tree.

Functions§

from_strfrom-toml
Parses and deserializes a TOML document in one step.
parse
Parses a TOML document and returns a Document containing the parsed tree.
parse_recoverablefrom-toml
Parses a TOML document in recovery mode, accumulating errors instead of stopping on the first one.
to_stringto-toml
Serializes a ToToml value into a TOML document string with default formatting.

Derive Macros§

Tomlderive
Unified derive macro for implementing TOML conversion traits.