#toml #read-file #validation #string #value #valid #applications

valid_toml

Provides the ability to load a TOML file with validation

2 releases

Uses old Rust 2015

0.0.2 Jun 12, 2016
0.0.1 Jun 12, 2016

#58 in #valid

AML/Apache-2.0

170KB
3K SLoC

This crate provides validation on a TOML file to ensure that the values read from the file are correct for the application.

Currently the crate only supports reading strings, usize, u16, and durations elements from the TOML file. The usize and u16 elements are basically a customization of a TOML number where the range is restricted to valid values. Likewise a duration element is a specialized string in the format "##d ##h ##m ##s ##ms".

There are plans for adding more data types, but so far I've only created the data types that I need for to read from the configuration file.

Given a TOML file like:

threads = 16

[database]
host = "localhost"
port = 5432

You can access the data using the following code:

use valid_toml::{TomlDef, ItemStr, ItemUsize, ItemU16};

# fn main() {
let mut def = TomlDef::new()
    .add(ItemUsize::with_name("threads").min(1).max(32).default(4))
    .add(TomlDef::with_name("database")
        .add(ItemStr::with_name("host").default("localhost"))
        .add(ItemU16::with_name("port").default(5432)));

// Load the contents of the TOML file into the string "file" and call
// TomlDef::parse_toml::<T:AsRef<str>>(input : T ) to parse it.  Or just call
// TomlDef::load_toml::<P : AsRef<Path>>(file : P ) to have the crate load it.
match def.parse_toml(file) {
    Ok(data) => {
        assert_eq!(data.get_usize("threads"), 16);
        assert_eq!(data.get_str("database.host"), "localhost");
        assert_eq!(data.get_u16("database.port"), 5432);
    },
    Err(issues) => {
        println!("Error reading the configuration file: ");
        for err in issues.errors.iter() {
            println!("    {}", err);
        }
    }
}

Dependencies

~600KB
~12K SLoC