Skip to main content

Crate soml

Crate soml 

Source
Expand description

SOML, a config format for humans: a strict reader, serde support, canonical form, and a lossless syntax tree.

SOML keeps JSON’s tree of objects and arrays and its strictness, and adds comments, bare keys, literal strings, block strings, dates, instants, durations, and line breaks as separators, with optional commas. A value’s type comes from its syntax, never from its content. See the specification, v0.1.

use serde::Deserialize;

#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Config {
	name: String,
	replicas: u32,
	timeout: std::time::Duration,
	deployed_at: soml::Instant,
	launch_date: soml::Date,
	labels: Vec<String>,
}

let config: Config = soml::from_str("
# The edge service.
name: 'api-gateway'
replicas: 3
timeout: 1m30s
deployed-at: 2026-09-19T14:00:00Z
launch-date: 2027-09-19
labels: ['prod', 'eu-west']
")?;

assert_eq!(config.replicas, 3);
assert_eq!(config.timeout.as_secs(), 90);

§Reading

from_str and from_slice read a document into any type that implements Deserialize, and Value holds a document of unknown shape. Every rule in the spec is checked: duplicate keys, the int64 range, date, instant, and duration ranges, raw control characters, and more. An error has a line and a column, also when the document is valid but does not fit the type:

#[derive(serde::Deserialize, Debug)]
struct Server {
	port: u16,
}

let error = soml::from_str::<Server>("port: 70000").unwrap_err();
assert_eq!(error.to_string(), "invalid value: integer `70000`, expected u16 at line 1, column 7");

§Writing

to_string writes a document for people to read: one member or item per line, tab indentation, and no commas, because a line break separates members and items. Members keep the order the value gives them, so a struct is written in the order of its fields.

to_string_canonical writes canonical form, the one text the spec defines for a value. It is the same, except that members are sorted by key, so the same value always gives the same bytes. Use it to hash, sign, or compare documents.

#[derive(serde::Serialize)]
struct Server {
	port: u16,
	hosts: Vec<&'static str>,
}

let server = Server { port: 8080, hosts: vec!["a", "b"] };
assert_eq!(soml::to_string(&server)?, "port: 8080\nhosts: [\n\t'a'\n\t'b'\n]\n");
assert_eq!(soml::to_string_canonical(&server)?, "hosts: [\n\t'a'\n\t'b'\n]\nport: 8080\n");

A map is written in the order it iterates in. A HashMap iterates in a different order on each run, so use to_string_canonical, a BTreeMap, or an IndexMap when the order must not change.

§Types

RustSOML
boolbool
i8 to i128, u8 to u128int, which is 64-bit, so a larger value cannot be written
f32, f64float. An int reads into a float only when it converts exactly, and a float never reads into an int.
String, &str, charstring
Option<T>null or the value
(), a unit structnull
Vec<T>, a tuplearray
a struct, HashMap, BTreeMapobject. A map key can also be a char, an integer, a bool, or a unit enum variant.
an enuma string for a unit variant, and a one-member object for the others
DateGregorian date, without a time or timezone
Instantinstant
Duration, std::time::Durationduration. A negative duration does not fit a std::time::Duration. serde gives a std::time::Duration no type of its own, so it is recognized by its shape: a struct named Duration with the fields secs and nanos. A struct of your own with that shape is written as a duration too, and it reads back.
Valueany value

Fields of jiff, chrono, and humantime types, such as jiff::Timestamp, jiff::SignedDuration, and chrono::DateTime<Utc>, read instants and durations too, because they ask for text, and an instant or duration gives its canonical text. humantime reads only instants from 1970 on. The cost of this is that a String field also accepts an instant or duration. chrono::TimeDelta does not ask for text, so it needs soml::chrono::time_delta to read a duration too. Those types write themselves as strings, so use Instant and Duration to write native instants and durations. Native dates require Date or the explicit soml::chrono::naive_date and soml::jiff::date adapters, and do not read into a String field.

#[serde(flatten)], untagged enums, and internally tagged enums read values through serde’s buffer, which has no date, instant, or duration type and no positions. There, a date, instant, or duration is its text: a Value holds it as a string, Date, Instant, and Duration still read it, and a std::time::Duration cannot be read. An int reads into a float even when the float does not hold it exactly. An f32 is read through an f64, as in serde_json, so 2 of the 4.3 billion f32 values read back one step away. A Spanned value has no span.

§Syntax tree

Document is a lossless syntax tree, for tools that read and change documents. An unchanged document prints the exact text it was parsed from, and a changed one keeps the comments and the author’s spelling outside the change. Every parsed node has its position in the text.

let mut document: soml::Document = "port: 0x1F90 # The default.\n".parse()?;
document.set(["port"], 8080)?;
assert_eq!(document.to_string(), "port: 8080 # The default.\n");

See tree for the nodes, and for how whitespace and comments are kept.

format() and Document::format are the spec’s formatter: they change layout and nothing else.

§Positions and errors

Spanned reads any value with the byte range it came from, so a check your app makes after reading can point at the right place, with Error::with_position. Every Error has an ErrorKind, and Error::code_frame shows where it is, for a terminal.

§More

  • soml! builds a Value with JSON-like syntax.
  • from_reader, to_writer, and to_writer_canonical read from an io::Read and write to an io::Write.
  • The jiff and chrono features add conversions, and modules for #[serde(with)] that write their types as native dates, instants, and durations: soml::jiff and soml::chrono.

§Format

  • File extension: .soml
  • Encoding: UTF-8 without a byte order mark, with LF line endings
  • Media type: application/soml
  • Uniform type identifier: com.sindresorhus.soml

§Limits

  • Nesting is limited to 100 levels, as the spec requires. Every object and array counts, including the document’s own.
  • Keys are compared byte for byte, so two keys that differ only in Unicode normalization are different keys, as the spec requires.

Modules§

chrono
Conversions between chrono’s types and SOML’s, and modules for #[serde(with)], with the chrono feature.
jiff
Conversions between jiff’s types and SOML’s, and modules for #[serde(with)], with the jiff feature.
tree
A lossless syntax tree, for tools that read and change SOML documents.

Macros§

soml
Builds a Value with JSON-like syntax.

Structs§

Date
A calendar date in the proleptic Gregorian calendar, from 0001-01-01 to 9999-12-31. It has no timezone, time of day, or duration, and its components never pass through an instant.
Document
A SOML document as a lossless syntax tree, to read with positions, change, and print.
Duration
A SOML duration: a signed length of time, as a whole number of nanoseconds in the i64 range, which is about 292 years either way.
Error
An error from reading or writing SOML.
Instant
A SOML instant: a point in time with nanosecond precision, from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
LineColumn
A place in a document’s text, as a person counts it: a 1-based line, and a 1-based column in Unicode scalar values.
Spanned
A value with the byte range it was read from, so an app can point at it when the value is valid SOML but not valid for the app.

Enums§

ErrorKind
What kind of problem an Error is about.
PathSegment
One step of a path into a document: a key of an object, or a position in an array.
Value
Any SOML value.

Traits§

Index
Something that can index into a Value: a key for an object, or a position for an array.

Functions§

format
Formats a document: it changes layout and nothing else, so comments, member order, and the spelling of every value stay. See Document::format.
from_reader
Reads a document from a reader into T.
from_slice
Reads a document from UTF-8 bytes into T.
from_str
Reads a document into T.
from_value
Converts a Value into T.
to_string
Writes value as a document, for people to read. It follows every rule of canonical form except the order of members, which stay in the order the value gives them: a struct’s fields in the order they are declared, and a map’s entries in the order it iterates in. So a BTreeMap and a Value are sorted by key, an IndexMap keeps its insertion order, and a HashMap has a different order on each run. Use to_string_canonical for the same bytes every time.
to_string_canonical
Writes value as a document in canonical form, the one text the spec defines for a value: the same as to_string, with the members of every object sorted by key. Two equal values always give the same bytes, so use it to hash, sign, or compare documents.
to_value
Converts value into a Value.
to_writer
Writes value as a document to a writer, as to_string does.
to_writer_canonical
Writes value as a document in canonical form to a writer, as to_string_canonical does.

Type Aliases§

Object
A SOML object: members by key.