Crate valid_toml

Source
Expand description

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};

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);
        }
    }
}

Structs§

  • This object contains all the problems that occured while loading a TOML file.
  • A duration item allows a user to provide a time duration in the TOML file.
  • This item is used to read an string value from the TOML file
  • This item is used to read an 16 bit unsigned number from the TOML file.
  • This item is used to read an 64 bit unsigned number from the TOML file.
  • Contains the verified results from a TOML file. Only the data elements defined are stored from the TOML file. This object is not created unless the TOML data matches the definition so it is safe to assume required values are present and valid.
  • Defines a group in the TOML file. Also the starting point for defining the contents of the file, since the file is basically an unnamed group.

Enums§

  • This enumeration identifies various errors that may occur when reading a TOML file.
  • Provides a description of how an element should be formatted.
  • Holds a validation error. A validation error occurs when a value is defined in the TOML file but does not match the rules defined for that value.
  • Defines the possible warnings.