toml
The toml module reads TOML 1.0 (config files such as Cargo.toml and pyproject.toml) into a struct or into a json.Value, and writes structs back out as TOML. It passes every TOML 1.0 case in the toml-test suite: the valid documents parse to the expected values, and the invalid ones are errors.
import toml
struct Server:
host: str
port: int
struct Config:
name: str
debug: bool
server: Server
tags: [str]
fn main():
text = """name = "app"
tags = ["web", "api"]
[server]
host = "0.0.0.0"
port = 8_080
"""
cfg = Config("", false, Server("localhost", 80), [])
print(toml.decode(text, &cfg))
print(cfg.name, cfg.debug, cfg.server.port, cfg.tags)
print(toml.encode(cfg).unwrap())Ok(0)
app false 8080 ["web", "api"]
name = "app"
debug = false
tags = ["web", "api"]
[server]
host = "0.0.0.0"
port = 8080
decode fills the struct by field name, as json.decode does: a key the file leaves out keeps the value the struct started with (so start it with the defaults), a key the struct doesn't have is ignored, and a field that may be missing can be an Option that starts at None.
Functions
fn decode(text: str, out: mut T) Result[int, str] fill out from the document
fn parse(text: str) Result[json.Value, str] the document as a json.Value
fn encode(value: T) Result[str, str] a struct or map as TOML
fn dump(v: json.Value) Result[str, str] a json.Value (an object) as TOMLValues
| TOML | becomes |
|---|---|
| table, inline table | object (Obj), keys in the order written |
| array, array of tables | array |
| string (all four kinds) | string |
integer (1_000, 0xff, 0o7, 0b1) | number (64-bit) |
| float | number; inf is a float too big for a double (inf when read into a float), nan is null |
true, false | bool |
| date and time | string, in RFC 3339 form: "1979-05-27T07:32:00Z", "1979-05-27T07:32:00", "1979-05-27", "07:32:00" |
A document of unknown shape is a json.Value, read with field, at and the *_or defaults:
import toml
fn main():
doc = toml.parse("""[package]
name = "demo"
version = "0.1.0"
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = "1"
""").unwrap()
print(doc.field("package").field("name").str_or("?"))
for k in doc.field("dependencies").fields():
print(k)
print(doc.field("dependencies").field("serde").field("features").at(0).str_or(""))demo
serde
tokio
deriveErrors
An error names the line and what is wrong there:
import toml
fn main():
for text in ["a = 1\na = 2", "[t]\nx = 1\n[t]", "port = 08080", "s = \"open", "when = 2026-02-30"]:
print(toml.parse(text))Err("toml: line 2: key defined twice")
Err("toml: line 3: table defined twice")
Err("toml: line 1: leading zeros aren't allowed")
Err("toml: line 1: unterminated string")
Err("toml: line 1: date out of range")Writing
encode and dump write a table's plain keys first, then its tables under [headers] and its arrays of tables under [[headers]]; other values (arrays, tables inside arrays) are written inline. TOML has no null, so a None field or a null is left out. Only a struct or a map can be a document: toml.encode(5) is an Err.
Speed and memory
bench/std does the same work with Go's pelletier/go-toml v2 (the fastest Go TOML library) and Rust's toml crate with serde: a 9.7 MB Cargo.lock-like file of 40,000 packages parsed into a dynamic value, decoded into structs, and the structs encoded; and a 1.2 KB service config decoded into a struct 20,000 times.
| Tern | Go (go-toml v2) | Rust (toml 0.9) | |
|---|---|---|---|
| parse into a dynamic value | 396 MB/s | 167 | 209 |
| decode into structs | 528 MB/s | 240 | 231 |
| encode the structs | 510 MB/s | 197 | 315 |
| decode a 1.2 KB config | 4.3 us | 10.6 | 7.6 |
| peak RSS | 86 MB | 91-110 | 318 |
(best of 5 interleaved runs; Go's peak memory moves between 91 and 110 MB with its collector.)
The module is Tern (library/std/toml/); it replaced a C parser in the runtime and is faster than it was. The parser makes one pass over the text into a tree of 24-byte nodes in one array (strings with no escapes point into the text), checking UTF-8 64 bytes at a time and scanning keys and plain runs of strings 16 at a time. A table's members are a list in the order written; a table with more than 8 is also in a hash index for the whole document. The tree is written out as JSON, which the json module turns into a struct or a Value. Writing reads the JSON from json.encode directly: one pass finds where each bracket closes, then each table is written in one walk (its plain keys, then the tables and arrays of tables it set aside).