Features
Multi-Format Support
- CONF - Built-in parser for standard .conf files (default)
- INI - Full INI file parsing with sections, comments, and data type detection
- JSON - JSON format with edit capabilities and serialization (feature:
jsonxon jsonx-lib, strict and dependency-free; orjsonon serde_json) - XML - Zero-copy XML parsing with quick-xml for Java/.NET environments
- HCL - HashiCorp Configuration Language for DevOps workflows
- Properties - Complete Java .properties file parsing with Unicode and escaping
- NOML - Advanced configuration with dynamic features (feature:
noml) - TOML - TOML format with format preservation (feature:
toml)
Enterprise Performance
- Sub-50ns Cache Access Target - Multi-tier caching designed for sub-50ns reads on hot paths
- Lock-Free Notification Dispatch -
on_changehandlers fire inline from the reloader thread viaArcSwap<Vec<Handler>>; one atomic load + N closure calls, no channel allocation - Zero-Copy Parsing - Minimized allocations and string operations where possible
- Lock-Free Read Paths - Poison-resistant locking with graceful failure recovery
- Hot Value Cache - Ultra-fast access for frequently used values
- Cache Hit Ratio Tracking - Built-in performance statistics and monitoring
Performance numbers, methodology, and tuning guidance live in
docs/PERFORMANCE.md. The committed criterion harnesses inbenches/produce the measured baselines.
Production Features
- Configuration Hot Reloading - File watching with thread-safe Arc swapping
- Audit Logging System - Structured event logging with multiple sinks and severity filtering
- Environment Variable Overrides - Smart caching with prefix matching and type conversion
- Schema Validation - Trait-based validation system with feature gates
- Format Preservation - Maintains comments, whitespace, and original formatting
- Async Native - Full async/await support throughout the API
Reliability & Safety
- Zero Unsafe Code - All
unwrap()calls eliminated, comprehensive error handling - Type Safety - Rich type system with automatic conversions and validation
- Reads only what you give it - TOML never resolves NOML's
includeorenv();Config::from_string_strictrefuses them in NOML too (since v1.3.0) - Enterprise Error Handling - Production-ready error messages with context preservation
- Comprehensive Testing - Extensive unit, integration, and doc test coverage
Why Choose config-lib?
Unified Multi-Format Support
Unlike single-format libraries, config-lib provides seamless access to 8 configuration formats through one consistent API. No need to learn different libraries for TOML, JSON, XML, and HCL - one API handles them all with automatic format detection.
Enterprise-Grade Performance
Multi-tier caching with lock-free read paths is designed to deliver sub-50ns cached access on hot paths. Built for high-throughput applications with minimal performance overhead.
Production-Ready Reliability
Zero unsafe code, comprehensive error handling, and poison-resistant locking ensure your configuration system won't crash your application. Extensive testing coverage validates edge cases and error conditions.
Developer Experience First
Rich type system with automatic conversions, format preservation for round-trip editing, and detailed error messages with source location context. No more cryptic parsing errors or manual type casting.
Advanced Enterprise Features
Hot reloading without service interruption, structured audit logging for compliance, environment variable overrides with smart caching, and schema validation with custom rules - features typically requiring multiple libraries.
Installation
Add to your Cargo.toml:
[]
= "1.3"
# For enhanced functionality, enable optional features:
= { = "1.3", = [
"jsonx", # JSON format support on jsonx-lib (strict, no dependencies; Rust 1.85+)
"json", # JSON format support on serde_json (used when `jsonx` is off)
"xml", # XML format support with quick-xml backend
"hcl", # HashiCorp Configuration Language support
"toml", # TOML format support with preservation
"noml", # NOML format support with dynamic features
"schema", # Schema validation (`Schema`, `SchemaBuilder`)
"validation", # Validation rules (`validation` module)
"async", # Async file loading on tokio
"env-override", # Environment variable override system
] }
Feature Recommendations:
- Minimal: Use default features for CONF/INI/Properties support
- Web Applications: Add
"jsonx"(or"json"),"env-override","validation" - DevOps Tools: Add
"hcl","toml","async" - Enterprise Systems: Add
"xml","validation","env-override" - Full Featured: Include all features for maximum flexibility
Quick Start
use Config;
// Parse a configuration; name the format, or pass `None` to detect it.
let mut config = from_string?;
// Typed reads with a default: the default's type picks the conversion.
let host: String = config.get_or;
let port: u16 = config.get_or;
let debug = config.get_or;
let workers: usize = config.get_or; // missing, so 4
// Reads that must succeed: `get` returns `Option<&Value>`.
let name = config
.get
.ok_or_else?
.as_string?
.to_owned;
// Modify configuration
config.set?;
config.set?;
println!;
Ok::
get_or works for bool, String, f64, and every integer type from
i8/u8 to i64/u64, isize, and usize. Integer reads are
range-checked: a value that does not fit the requested type (say
70000 read as u16, or 8080.5 read as any integer) returns the
default. The same conversions are available directly as
TryFrom<Value> and TryFrom<&Value>.
Multi-Format Support
use Config;
// The same calls work for every format; name it, or pass `None` to detect it.
let config = from_string?;
let port: u16 = config.get_or;
let timeout: u64 = config.get_or;
let name: String = config.get_or;
assert_eq!;
// Check existence
if config.contains_key
Ok::
Format names are "conf", "ini", "properties", "json", "xml",
"hcl", "toml", and "noml"; each format other than CONF, INI, and
properties needs its Cargo feature.
Read-only mode and forward-compatible options
ConfigOptions is the structured place to express the small set of
behaviors that should not be enabled by default — making a Config
read-only, sizing the cache, etc. The struct is #[non_exhaustive]
so v1.x MINOR releases can add new knobs without breaking SemVer;
callers go through the consuming builder methods.
use ;
// Default options — caching on, writes allowed.
let _cfg = with_options;
// Read-only configuration for a hot path that must never be mutated.
let opts = new.read_only;
let mut locked = with_options;
assert!; // rejected
Default Configuration Settings
config-lib offers three ways to supply defaults for keys that are missing from a configuration file.
Method 1: Inline defaults with get_or (recommended)
The default sits at the read, and its type picks the conversion.
use Config;
let config = from_file?;
let app_config = AppConfig ;
Ok::
Method 2: A defaults table
set_default fills a table that get_or_default falls back to when the
main value tree has no entry for the path.
use ;
let config = from_string?;
config.set_default?;
config.set_default?;
config.set_default?;
// File value wins over the default.
assert_eq!;
// Missing from the file, so the default.
assert_eq!;
Ok::
Method 3: The key accessor
use Config;
let config = from_string?;
let cache_ttl = config.key.as_integer_or; // i64
let environment = config.key.as_string_or;
let verbose = config.key.as_bool_or;
assert_eq!;
Ok::
Best Practices for Default Configuration
- Use Sensible Defaults: Choose defaults that work for most use cases
- Document Defaults: Keep defaults in sync with documentation
- Environment-Specific: Use different defaults for dev/staging/production
- Type Safety: Read into the narrowest type that fits (
u16for a port), so an out-of-range value is not accepted - Validation: Validate both defaults and overrides
Environment Variable Integration
Needs the env-override feature.
use EnvOverrideSystem;
use Config;
let config = from_file?;
// MYAPP_DATABASE_HOST overrides database.host, MYAPP_SERVER_PORT
// overrides server.port, and so on.
let overrides = with_prefix;
let config = from;
let host: String = config.get_or;
let port: u16 = config.get_or;
Ok::
Configuration Validation
Needs the validation feature. Rules run against each top-level value.
use ;
use Config;
let mut config = from_string?;
config.set_validation_rules;
let errors = config.validate?;
assert!;
Ok::
Hot Reloading & Audit Logging
use ;
use ;
// Process-wide audit logger
init_audit_logger;
// Hot reloading: take the shared handle before `start_watching` consumes the watcher.
let hot = from_file?;
let shared = hot.config;
let _sub = hot.on_change;
let _handle = hot.start_watching;
let port: u16 = shared
.read
.map
.unwrap_or;
Ok::
Multi-File Configuration
use Config;
// Later files override earlier ones, key by key.
let mut config = from_file?;
config.merge?;
config.merge?;
let database_url: String = config.get_or;
let debug_mode = config.get_or;
Ok::
Documentation & Resources
Documentation
- Documentation Index - Complete documentation hub and navigation
- API Reference - Comprehensive API documentation with examples
- Valid Formats - Detailed format specifications and examples
- Code Guidelines - Development standards and best practices
External Resources
- API Documentation - Complete API reference with examples
- Crate Registry - Official crate distribution
- Examples Directory - 20+ comprehensive examples covering all features
- Performance Benchmarks - Detailed performance analysis and comparisons
- NOML Language - NOML language specification and usage.
Getting Started Guides
- Quick Start Guide - Basic configuration loading and access
- Multi-Format Demo - Working with different configuration formats
- Enterprise Features - Advanced caching and performance
- Hot Reloading - Dynamic configuration updates
- Validation System - Schema validation and type checking
Common Use Cases
- Web Applications: Environment overrides, JSON/TOML configs
- DevOps Tools: HCL integration, audit logging, hot reloading
- Enterprise Systems: XML support, validation, caching
- Microservices: Multi-format support, environment-based configuration
Version Compatibility
- Rust:
1.75+for the default feature set;1.79+with thexmlfeature (quick-xml0.41);1.82+with thenomlortomlfeatures (noml = "=0.9.2");1.85+with thejsonxfeature (jsonx-lib = "=0.5.1") - Edition:
2021 - MSRV Policy: MINOR releases may bump MSRV within the last-12-stable-Rust-versions window; PATCH releases never bump MSRV
- API Stability: v1.x public API is frozen per
docs/STABILITY-1.0.md. Growth-likely enums (Error,ConfigChangeEvent, etc.) are#[non_exhaustive]; new variants land in MINOR releases without breaking SemVer - Feature Flags: All optional features maintain independent compatibility
Development Setup
Contributing
We welcome contributions! See our Contributing Guide for details.