qubit-config
A powerful, type-safe configuration management system for Rust, providing flexible configuration management with support for multiple data types, variable substitution, multi-value properties, and pluggable configuration sources (files, environment, and composites).
Features
- ✅ Pure Generic API - Use
get<T>(),read(ConfigField<T>), andset<T>()generic methods with full type inference support - ✅ Rich Data Types - Support for all primitive types, temporal types, strings, byte arrays, and more
- ✅ Multi-Value Properties - Each configuration property can contain multiple values with list operations
- ✅ Variable Substitution - Support for
${var_name}style variable substitution from config, with explicit opt-in fallback to process environment variables - ✅ Type Safety - Compile-time type checking to prevent runtime type errors
- ✅ Serialization Support - Full serde support for serialization and deserialization
- ✅ Extensible - Trait-based design for easy custom type support
- ✅ Configuration sources -
ConfigSourcetrait with built-in loaders: TOML, YAML, Java-style.properties,.envfiles, process environment variables (with optional prefix / key normalization), andCompositeConfigSourceto merge several sources in order (later entries override earlier ones for the same key); built-in sources load transactionally, so failed loads leave the targetConfigunchanged - ✅ Read-only API -
ConfigReadertrait for typed reads without mutation; implemented byConfigandConfigPrefixView, with string helpers, multi-key reads, and field declarations that respect variable substitution - ✅ Configurable parsing -
ConfigReadOptionscontrols string trimming, blank handling, boolean literals, and scalar-string collection splitting globally or per field - ✅ Prefix views -
Config::prefix_viewreturns aConfigPrefixViewscoped to a logical key prefix (relative keys map toprefix.key); nest withConfigPrefixView::prefix_view - ✅ Zero-Cost Abstractions - Uses enums instead of trait objects to avoid dynamic dispatch overhead
Installation
Add this to your Cargo.toml:
[]
= "0.11"
Quick Start
use Config;
Core Concepts
Config
The Config struct is the central configuration manager that stores and manages all configuration properties.
let mut config = new;
config.set?;
config.set?;
Property
Each configuration item is represented by a Property that contains:
- Name (key)
- Multi-value container
- Optional description
- Final flag (immutable after set)
MultiValues
A type-safe container that can hold multiple values of the same data type.
ConfigReader
ConfigReader is the read-only configuration surface. Functions or types that only need settings can take &impl ConfigReader (or a generic R: ConfigReader) instead of &Config; the same API works for Config and ConfigPrefixView. ConfigReader has generic typed methods, so it is not object-safe and should not be used as dyn ConfigReader.
The main read APIs are:
| API | Behavior |
|---|---|
get<T>(name) |
Read a required value through FromConfig. |
get_optional<T>(name) |
Return Ok(None) when the key is missing or empty. |
get_or<T>(name, default) |
Use default only when the key is missing or empty. |
get_any<T>(&[names]) |
Read the first present and non-empty key in order. |
get_optional_any<T>(&[names]) |
Multi-key optional read. |
get_any_or<T>(&[names], default) |
Multi-key defaulted read. |
get_any_or_with<T>(&[names], default, options) |
Multi-key defaulted read with explicit read options. |
get_string, get_string_any, get_string_any_or |
String helpers with variable substitution. |
read(ConfigField<T>) |
Field declaration with name, aliases, default, and field-level read options. |
get_strict / get_list_strict |
Exact stored-type reads without cross-type conversion. |
Defaults do not hide bad configuration. If a key exists and its value fails parsing, type conversion, or variable substitution, the error is returned immediately instead of falling back to a default or later alias.
use ;
let mut config = new;
config.set?;
let missing = config.get_or?;
assert_eq!;
let invalid = config.get_or;
assert!;
Defaulted reads such as get_or, get_any_or, and get_any_or_with accept convenient fallback values. Scalar defaults still use the target type directly, while string defaults can use borrowed literals and string-list defaults can use arrays, slices, or borrowed vectors. Single-key and multi-key arguments also accept direct arrays, slices, vectors, and borrowed vectors.
let host = config.?;
let paths = config.?;
let paths = config.?;
ConfigPrefixView
ConfigPrefixView is a zero-copy borrow of a Config with a logical key prefix. Use Config::prefix_view to create it; keys passed to the view are resolved under that prefix. For example, prefix db and key host read the stored key db.host. Use ConfigPrefixView::prefix_view for nested views.
use ;
let mut config = new;
config.set?;
config.set?;
let db = config.prefix_view;
let host: String = db.get_string?;
let port: i32 = db.get?;
ConfigReadOptions
ConfigReadOptions controls how configured values are parsed. It can be set globally on a Config, or attached to a single ConfigField<T>.
| Option group | Controls |
|---|---|
StringReadOptions |
Trimming and blank-string handling: preserve, treat as missing, or reject. |
BooleanReadOptions |
Accepted boolean literals and case sensitivity. |
CollectionReadOptions |
Splitting scalar strings into lists, delimiters, per-item trimming, and empty-item policy. |
| Environment variable substitution | Whether unresolved ${...} placeholders may fall back to process environment variables. This is disabled by default. |
ConfigReadOptions::env_friendly() is useful for environment-variable style values: it trims strings, treats blank scalar strings as missing, accepts true/false, 1/0, yes/no, and on/off, and splits scalar strings on commas for Vec<T> reads while skipping empty items.
Environment-variable fallback for ${...} substitution is disabled by default, including in ConfigReadOptions::env_friendly(), to avoid accidental injection from the process environment. Enable it explicitly only for trusted configuration flows with with_env_variable_substitution_enabled(true).
use ;
let mut config = new.with_read_options;
config.set?;
config.set?;
let enabled: bool = config.get?;
let ports: = config.get?;
assert!;
assert_eq!;
You can build stricter or domain-specific options with builder-style methods:
use ;
let options = default
.with_boolean_options
.with_collection_options;
let mut config = new.with_read_options;
config.set?;
config.set?;
let feature: bool = config.get?;
let ports: = config.get?;
ConfigField
Use ConfigField<T> when a logical setting has aliases, a default, or field-specific parsing rules. This keeps migration keys, legacy names, and environment-style keys out of application parsing code.
use ;
let mut config = new;
config.set?;
let enabled = config.read?;
assert!;
The builder makes the primary name explicit: build() is available only after name(...) has been supplied.
Multi-Key Reads
Use get_any, get_optional_any, get_any_or, and get_any_or_with for lightweight alias reads when a full ConfigField<T> would be too verbose.
use ;
let mut config = new.with_read_options;
config.set?;
config.set?;
let url = config.get_string_any?;
let timeout = config.get_any_or?;
let optional_port = config.?;
let retries = config.get_any_or_with?;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Multi-key reads scan keys in order. Missing and empty values are skipped; the first configured non-empty value is parsed. If that value is invalid, the error is returned and later keys are not tried.
Configuration sources
Implementations of ConfigSource load external settings into a Config. Call merge_from_source (or load on the source with a &mut Config) to apply them. When no pre-load customization is needed, use the convenience constructors such as Config::from_toml_file, Config::from_yaml_file, Config::from_properties_file, Config::from_env_file, Config::from_env, or Config::from_env_prefix.
Built-in sources and Config::merge_from_source are transactional: if parsing or merging fails, the target Config keeps its previous state.
| Type | Role |
|---|---|
TomlConfigSource |
TOML files; nested tables are flattened to dot-separated keys |
YamlConfigSource |
YAML files; nested mappings flattened similarly |
PropertiesConfigSource |
Java .properties files |
EnvFileConfigSource |
.env-style files |
EnvConfigSource |
Process environment; optional prefix filtering and key normalization (e.g. APP_SERVER_HOST → server.host) |
CompositeConfigSource |
Chains multiple sources in order; later sources win on duplicate keys (subject to Property final semantics) |
use ;
let mut config = new;
let mut composite = new;
composite
.add
.add;
config.merge_from_source?;
use Config;
let config = from_toml_file?;
let env_config = from_env_prefix?;
Usage Examples
Basic Configuration
use Config;
let mut config = new;
// Set various types
config.set?;
config.set?;
config.set?;
config.set?;
config.set?;
// Get values with type inference and conversion
let port: i32 = config.get?;
let host: String = config.get?;
let debug: bool = config.get?;
let is_use_prefix: bool = config.get?;
// Exact stored-type reads remain available when needed
assert!;
Multi-Value Configuration
// Set multiple values
config.set?;
// Get all values
let ports: = config.get_list?;
// Add values incrementally
config.set?;
config.add?;
config.add?;
let servers: = config.get_list?;
Variable Substitution
config.set?;
config.set?;
config.set?;
// Variables are automatically substituted
let url = config.get_string?;
// Result: "http://localhost:8080/api"
// Environment fallback is opt-in because process environment values can be
// attacker-controlled in some deployments.
config.set_read_options;
set_var;
config.set?;
let env = config.get_string?;
// Result: "production"
Structured Configuration
deserialize() uses the same read options as typed get reads. For example, ConfigReadOptions::env_friendly() can parse numeric strings, boolean aliases, comma-separated scalar string lists, and blank strings treated as missing while building a serde struct.
When prefix is non-empty, deserialize(prefix) uses strict root selection:
an exact prefix property is deserialized as the root value, otherwise
prefix.* child keys form the root object. Defining both prefix and
prefix.* is a key conflict. Dotted keys must form an unambiguous object tree;
for example, a and a.b cannot both appear in the same deserialized object.
use ;
let mut config = new;
config.set?;
config.set?;
config.set?;
config.set?;
let db_config = DatabaseConfig ;
Configurable Objects
use ;
// Use the Configured base class
let mut configured = new;
configured.config_mut.set?;
// Custom configurable object
let mut app = new;
app.config_mut.set?;
Supported Data Types
| Rust Type | Description | Example |
|---|---|---|
bool |
Boolean value; string reads accept true / false and 1 / 0 by default; ConfigReadOptions::env_friendly() also accepts yes / no and on / off |
true, false, "0", "yes" |
char |
Character | 'a', '中' |
i8, i16, i32, i64, i128 |
Signed integers | 42, -100 |
u8, u16, u32, u64, u128 |
Unsigned integers | 255, 1000 |
f32, f64 |
Floating point | 3.14, 2.718 |
String |
String | "hello", "世界" |
Vec<T> |
List values; with collection read options, scalar strings can be split into list items | [1, 2, 3], "a,b,c" |
chrono::NaiveDate |
Date | 2025-01-01 |
chrono::NaiveTime |
Time | 12:30:45 |
chrono::NaiveDateTime |
Date and time | 2025-01-01 12:30:45 |
chrono::DateTime<Utc> |
Timestamped datetime | 2025-01-01T12:30:45Z |
Extending with Custom Types
To support domain-specific reads, implement FromConfig for the target type. The implementation can reuse built-in FromConfig parsers and add validation, so call sites still use config.get::<T>(), config.get_or::<T>(), or config.read(ConfigField::<T>) without hand-written parse code.
use ;
use ;
;
let mut config = new;
config.set?;
let port: Port = config.get?;
let fallback = config.get_or?;
Implement lower-level qubit_value traits only when you also need to store the custom type directly or use exact stored-type reads through get_strict / get_list_strict.
API Design Philosophy
Why Pure Generic API?
Typed reads use a generic approach (get<T>(), set<T>(), get_or<T>(), read(ConfigField<T>)) instead of a separate method for every supported type (like get_i32(), get_bool(), etc.) because:
- Universal - Generic methods work with any type that implements the required traits, including custom types
- Concise - Avoids repetitive type-specific method definitions
- Maintainable - Adding new types only requires trait implementation, no modification to Config struct
- Idiomatic Rust - Leverages Rust's type system and type inference capabilities
Three Ways of Type Inference
// 1. Variable type annotation (recommended, most clear)
let port: i32 = config.get?;
// 2. Turbofish syntax (use when needed)
let port = config.?;
// 3. Context inference (most concise)
let server = Server ;
Error Handling
The configuration system uses ConfigResult<T> for error handling:
Performance Considerations
- Zero-Cost Abstractions - Uses enums instead of trait objects to avoid dynamic dispatch overhead
- Variable Substitution Optimization - Uses
OnceLockto cache regex patterns, avoiding repeated compilation - Efficient Storage - Properties stored in
HashMapwith O(1) lookup time complexity - Shallow Copy Optimization - Cloning uses shallow copies when wrapped in
Arc
Testing
Run the test suite:
Run with code coverage:
Documentation
For detailed API documentation, visit docs.rs/qubit-config.
For internal design documentation (Chinese), see src/README.md.
Dependencies
qubit-datatype- Core utilities and data type definitionsqubit-value- Value handling frameworkserde- Serialization frameworkchrono- Date and time handlingregex- Regular expression supporttoml- TOML parsing forTomlConfigSourceserde_norway- YAML parsing forYamlConfigSourcedotenvy-.envfile parsing forEnvFileConfigSource
Roadmap
- Additional configuration loaders (e.g. JSON, XML)
- Advanced merge / overlay policies beyond ordered
CompositeConfigSource - Configuration watching and hot reload
- Configuration validation framework
- Configuration encryption support
- Thread-safe wrapper type
SyncConfig
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
Copyright (c) 2025 - 2026. Haixing Hu, Qubit Co. Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
See LICENSE for the full license text.
Author
Haixing Hu - Qubit Co. Ltd.
For more information about the Qubit Rust libraries, visit our GitHub organization.