Crate basic_toml

source ·
Expand description

githubcrates-iodocs-rs


A library for parsing and producing data in TOML format using Serde.

TOML is designed to be “a config file format for humans”: minimal and easy to read due to obvious semantics.

[package]
name = "basic-toml"
version = "0.1.9"
authors = ["Alex Crichton <alex@alexcrichton.com>"]

[dependencies]
serde = "1.0"

The TOML format is widely used throughout the Rust community for configuration, notably being used by Cargo, Rust’s package manager.

§Deserialization

use semver::{Version, VersionReq};
use serde_derive::Deserialize;
use std::collections::BTreeMap as Map;

#[derive(Deserialize)]
struct Manifest {
    package: Package,
    #[serde(default)]
    dependencies: Map<String, VersionReq>,
}

#[derive(Deserialize)]
struct Package {
    name: String,
    version: Version,
    #[serde(default)]
    authors: Vec<String>,
}

fn main() {
    let manifest: Manifest = basic_toml::from_str(r#"
        [package]
        name = "basic-toml"
        version = "0.1.9"
        authors = ["Alex Crichton <alex@alexcrichton.com>"]

        [dependencies]
        serde = "^1.0"
    "#).unwrap();

    assert_eq!(manifest.package.name, "basic-toml");
    assert_eq!(manifest.package.version, Version::new(0, 1, 9));
    assert_eq!(manifest.package.authors, ["Alex Crichton <alex@alexcrichton.com>"]);
    assert_eq!(manifest.dependencies["serde"].to_string(), "^1.0");
}

§Serialization

use semver::{Version, VersionReq};
use serde_derive::Serialize;
use std::collections::BTreeMap as Map;

#[derive(Serialize)]
struct Manifest {
    package: Package,
    dependencies: Map<String, VersionReq>,
}

#[derive(Serialize)]
struct Package {
    name: String,
    version: Version,
    authors: Vec<String>,
}

fn main() {
    let manifest = Manifest {
        package: Package {
            name: "basic-toml".to_owned(),
            version: Version::new(0, 1, 9),
            authors: vec!["Alex Crichton <alex@alexcrichton.com>".to_owned()],
        },
        dependencies: {
            let mut dependencies = Map::new();
            dependencies.insert("serde".to_owned(), "^1.0".parse().unwrap());
            dependencies
        },
    };

    let toml = basic_toml::to_string(&manifest).unwrap();
    print!("{}", toml);
}

§Spec compatibility

TOML v0.5.0.

TOML’s date and time syntax are not supported.

Structs§

  • Errors that can occur when serializing or deserializing TOML.

Functions§

  • Deserializes a byte slice into a type.
  • Deserializes a string into a type.
  • Serialize the given data structure as a String of TOML.