6 releases (3 breaking)
Uses new Rust 2024
| 0.4.0 | Mar 16, 2026 |
|---|---|
| 0.3.2 | Feb 24, 2026 |
| 0.3.1 | Jan 19, 2026 |
| 0.2.0 | Jan 15, 2026 |
| 0.1.0 | Dec 30, 2025 |
#484 in Configuration
18KB
118 lines
inline-config
Effortlessly embed config modules and access with any compatible types.
A procedual macro Config is provided to parse sources at compile time, generate corresponding data structures, from which we can access values via the Index trait and the From trait.
Features
- JSON, YAML, TOML formats are supported.
- Both inline literal configs and file inclusions are supported; overwriting is supported.
- Compile-time source validation. Errors are clearly reported for easier debugging.
- Infallible data access. Path existence and type compatibility are both checked at compile time.
- Define custom data structures to access data.
- The feature flag
indexmapenables preserving orders of tables. Check this example for details.
Usage
Add inline-config to your dependencies
cargo add inline-config
In your source file, derive a unit struct with Config and attach the config data
use inline_config::Config;
// Declare a config type containing literal sources.
#[derive(Config)]
// While only using literal sources,
// a format needs to be specified.
// Including a file from disk is also possible,
// see `examples/include.rs`.
#[config(format = "toml")]
// When there are multiple sources,
// latter ones overwrite former ones.
#[config(src = r#"
title = "TOML example"
[server]
owner = "Tom"
timeout = 2000
ports = [ 8000, 8001, 8002 ]
"#)]
#[config(src = r#"
[server]
timeout = 5000
"#)]
struct MyConfig;
Then, access the data inside using the path!() macro
use inline_config::path;
// Use `Index`, `From` traits to access data.
// Different types may be accessible from a field.
let title: &str = MyConfig[path!(title)].into();
assert_eq!("TOML example", title);
let title: String = MyConfig[path!(title)].into();
assert_eq!("TOML example", title);
// A deeper path.
let owner: &str = MyConfig[path!(server.owner)].into();
assert_eq!("Tom", owner);
// Any numerical types.
let timeout: u32 = MyConfig[path!(server.timeout)].into();
assert_eq!(5000, timeout);
let timeout: f32 = MyConfig[path!(server.timeout)].into();
// A homogeneous array can be accessed as `Vec<T>`.
let ports: Vec<u64> = MyConfig[path!(server.ports)].into();
assert_eq!([8000, 8001, 8002].to_vec(), ports);
Check out more examples for more details about usage.
Dependencies
~0.8–1.6MB
~34K SLoC