Expand description
A high-performance TOML parser that preserves span information for values and keys.
§Parsing and Traversal
Use parse with a TOML string and an Arena to get a Root.
let arena = toml_spanner::Arena::new();
let root = toml_spanner::parse("key = 'value'", &arena)?;Traverse the tree for inspection via index operators which return a MaybeItem:
let name: Option<&str> = root["name"].as_str();
let numbers: Option<i64> = root["numbers"][50].as_i64();Use the MaybeItem::item() method get an Item which contains a Value and Span.
let Some(item) = root["item"].item() else {
panic!("Missing key `custom`");
};
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
Use Root::helper() to create a TableHelper for type-safe field extraction
via the Deserialize trait. Errors are accumulated in the Root’s context
rather than failing on the first error.
let mut helper = root.helper();
let name: String = helper.required("name").ok().unwrap();Extract values with Item::parse which uses std::str::FromStr expecting a String kinded TOML Value.
let item = root["ip-address"].item().unwrap();
let ip: std::net::Ipv4Addr = item.parse()?;Toggle More Extensive Example
use toml_spanner::{Arena, Deserialize, Item, Context, Failed, TableHelper};
#[derive(Debug)]
struct Things {
name: String,
value: u32,
color: Option<String>,
}
impl<'de> Deserialize<'de> for Things {
fn deserialize(ctx: &mut Context<'de>, value: &Item<'de>) -> Result<Self, Failed> {
let Some(table) = value.as_table() else {
return Err(ctx.error_expected_but_found("a table", value));
};
let mut th = TableHelper::new(ctx, table);
let name = th.required("name")?;
let value = th.required("value")?;
let color = th.optional("color");
th.expect_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 root = toml_spanner::parse(content, &arena)?;
// Null-coalescing index operators — missing keys return a None-like
// MaybeItem instead of panicking.
assert_eq!(root["things"][0]["color"].as_str(), None);
assert_eq!(root["things"][1]["color"].as_str(), Some("green"));
// Deserialize typed values out of the root table.
let mut helper = root.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.expect_empty().ok();
assert_eq!(things.len(), 2);
assert_eq!(things[0].name, "hammer");
assert!(dev_mode);Structs§
- Arena
- Bump allocator backing all data structures produced by the parser.
- Array
- A growable array of TOML
Items. - Context
- Shared deserialization 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.
- Error
- An error from parsing or deserializing TOML.
- Failed
- Sentinel indicating that a deserialization error has been recorded in the
Context. - 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.
- Root
- Holds both the root table and the parsing context for deserialization.
- Span
- A byte-offset range within a TOML document.
- Spanned
- Wraps a value
Twith its sourceSpan. - Table
- A TOML table with span information.
- Table
Helper - Guides deserialization of a
Tableby tracking which fields have been consumed. - Time
- Represents the time of day portion of a TOML datetime value.
Enums§
- Error
Kind - The specific kind of parse or deserialization error.
- Kind
- Discriminant for the TOML value types stored in an
Item. - 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§
- Deserialize
- Trait for types that can be deserialized from a TOML
Item.