pub struct Config { /* private fields */ }Expand description
Configuration Manager
Manages a set of configuration properties with type-safe read/write interfaces.
§Features
- Supports multiple data types
- Supports variable substitution (
${var_name}format) - Supports configuration merging
- Supports final value protection
- Thread-safe (when wrapped in
Arc<RwLock<Config>>)
§Examples
use qubit_config::Config;
let mut config = Config::new();
// Set configuration values (type inference)
config.set("port", 8080).unwrap(); // inferred as i32
config.set("host", "localhost").unwrap();
// &str is converted to String
config.set("debug", true).unwrap(); // inferred as bool
config.set("timeout", 30.5).unwrap(); // inferred as f64
config.set("code", 42u8).unwrap(); // inferred as u8
// Set multiple values (type inference)
config.set("ports", vec![8080, 8081, 8082]).unwrap(); // inferred as i32
config.set("hosts", vec!["host1", "host2"]).unwrap();
// &str elements are converted
// Read configuration values (type inference)
let port: i32 = config.get("port").unwrap();
let host: String = config.get("host").unwrap();
let debug: bool = config.get("debug").unwrap();
let code: u8 = config.get("code").unwrap();
// Read configuration values (turbofish)
let port = config.get::<i32>("port").unwrap();
// Read configuration value or use default
let timeout: f64 = config.get_or("timeout", 30.0).unwrap();Implementations§
Source§impl Config
impl Config
Sourcepub fn with_description(description: &str) -> Self
pub fn with_description(description: &str) -> Self
Creates a configuration with description
§Parameters
description- Configuration description
§Returns
Returns a new configuration instance
§Examples
use qubit_config::Config;
let config = Config::with_description("Server Configuration");
assert_eq!(config.description(), Some("Server Configuration"));Sourcepub fn description(&self) -> Option<&str>
pub fn description(&self) -> Option<&str>
Sourcepub fn set_description(&mut self, description: Option<String>)
pub fn set_description(&mut self, description: Option<String>)
Sourcepub fn is_enable_variable_substitution(&self) -> bool
pub fn is_enable_variable_substitution(&self) -> bool
Checks if variable substitution is enabled
§Returns
Returns true if variable substitution is enabled
Sourcepub fn set_enable_variable_substitution(&mut self, enable: bool)
pub fn set_enable_variable_substitution(&mut self, enable: bool)
Sourcepub fn max_substitution_depth(&self) -> usize
pub fn max_substitution_depth(&self) -> usize
Sourcepub fn read_options(&self) -> &ConfigReadOptions
pub fn read_options(&self) -> &ConfigReadOptions
Gets the global read parsing options.
§Returns
The options used by get, get_any, and field reads when no
field-level override is provided.
Sourcepub fn set_read_options(&mut self, read_options: ConfigReadOptions) -> &mut Self
pub fn set_read_options(&mut self, read_options: ConfigReadOptions) -> &mut Self
Sourcepub fn with_read_options(&self, read_options: ConfigReadOptions) -> Self
pub fn with_read_options(&self, read_options: ConfigReadOptions) -> Self
Sourcepub fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>
pub fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>
Creates a read-only prefix view using ConfigPrefixView.
§Parameters
prefix- Prefix
§Returns
Returns a read-only prefix view
§Examples
use qubit_config::{Config, ConfigReader};
let mut config = Config::new();
config.set("server.port", 8080).unwrap();
config.set("server.host", "localhost").unwrap();
let server = config.prefix_view("server");
assert_eq!(server.get::<i32>("port").unwrap(), 8080);
assert_eq!(server.get::<String>("host").unwrap(), "localhost");Sourcepub fn set_max_substitution_depth(&mut self, depth: usize)
pub fn set_max_substitution_depth(&mut self, depth: usize)
Sourcepub fn contains(&self, name: impl ConfigName) -> bool
pub fn contains(&self, name: impl ConfigName) -> bool
Checks if the configuration contains an item with the specified name
§Parameters
name- Configuration item name
§Returns
Returns true if the configuration item exists
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
assert!(config.contains("port"));
assert!(!config.contains("host"));Sourcepub fn get_property(&self, name: impl ConfigName) -> Option<&Property>
pub fn get_property(&self, name: impl ConfigName) -> Option<&Property>
Sourcepub fn get_property_mut(
&mut self,
name: impl ConfigName,
) -> ConfigResult<Option<ConfigPropertyMut<'_>>>
pub fn get_property_mut( &mut self, name: impl ConfigName, ) -> ConfigResult<Option<ConfigPropertyMut<'_>>>
Gets guarded mutable access to a non-final configuration item.
§Parameters
name- Configuration item name
§Returns
Returns Ok(Some(_)) for an existing non-final property, Ok(None)
for a missing property, or ConfigError::PropertyIsFinal for an
existing final property. The returned guard re-checks final state before
each value-changing operation.
Sourcepub fn set_final(
&mut self,
name: impl ConfigName,
is_final: bool,
) -> ConfigResult<()>
pub fn set_final( &mut self, name: impl ConfigName, is_final: bool, ) -> ConfigResult<()>
Sets the final flag of an existing configuration item.
A non-final property can be marked final. A property that is already final may be marked final again, but cannot be unset through this API.
§Parameters
name- Configuration item name.is_final- Whether the property should be final.
§Returns
Ok(()) on success.
§Errors
ConfigError::PropertyNotFoundif the key does not exist.ConfigError::PropertyIsFinalwhen trying to unset a final property.
Sourcepub fn remove(
&mut self,
name: impl ConfigName,
) -> ConfigResult<Option<Property>>
pub fn remove( &mut self, name: impl ConfigName, ) -> ConfigResult<Option<Property>>
Removes a non-final configuration item.
§Parameters
name- Configuration item name
§Returns
Returns the removed configuration item, or None if it doesn’t exist
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
let removed = config.remove("port").unwrap();
assert!(removed.is_some());
assert!(!config.contains("port"));Sourcepub fn clear(&mut self) -> ConfigResult<()>
pub fn clear(&mut self) -> ConfigResult<()>
Clears all configuration items if none of them are final.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
config.set("host", "localhost").unwrap();
config.clear().unwrap();
assert!(config.is_empty());§Returns
Ok(()) when all properties were removed.
Sourcepub fn keys(&self) -> Vec<String>
pub fn keys(&self) -> Vec<String>
Gets all configuration item names
§Returns
Returns a Vec of configuration item names
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
config.set("host", "localhost").unwrap();
let keys = config.keys();
assert_eq!(keys.len(), 2);
assert!(keys.contains(&"port".to_string()));
assert!(keys.contains(&"host".to_string()));Sourcepub fn get<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
T: FromConfig,
pub fn get<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
T: FromConfig,
Gets a configuration value, converting the stored first value to T.
Core read API with type inference.
This method does not perform ${...} variable substitution. Use
Self::get_string, Self::get_string_list, or
Self::deserialize when placeholders should be resolved while reading.
§Type Parameters
T- Target type supported byFromConfig
§Parameters
name- Configuration item name
§Returns
The value of the specified type on success, or a ConfigError on
failure.
§Errors
ConfigError::PropertyNotFoundif the key does not existConfigError::PropertyHasNoValueif the property has no valueConfigError::ConversionErrorif the stored value cannot be converted toT
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
config.set("host", "localhost").unwrap();
// Method 1: Type inference
let port: i32 = config.get("port").unwrap();
let host: String = config.get("host").unwrap();
// Method 2: Turbofish
let port = config.get::<i32>("port").unwrap();
let host = config.get::<String>("host").unwrap();
// Method 3: Inference from usage
fn start_server(port: i32, host: String) { }
start_server(config.get("port").unwrap(), config.get("host").unwrap());Sourcepub fn get_strict<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
MultiValues: MultiValuesFirstGetter<T>,
pub fn get_strict<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
MultiValues: MultiValuesFirstGetter<T>,
Gets a configuration value only when the stored value already has the exact requested type.
Unlike Self::get, this method preserves the pre-conversion read
semantics. For example, a stored string "1" can be read as bool by
Self::get, but Self::get_strict returns
ConfigError::TypeMismatch.
§Type Parameters
T- Exact target type supported byMultiValuesFirstGetter
§Parameters
name- Configuration item name
§Returns
The exact typed value on success, or a ConfigError on failure.
Sourcepub fn get_or<T>(
&self,
name: impl ConfigName,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
pub fn get_or<T>(
&self,
name: impl ConfigName,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
Gets a configuration value or returns a default value.
Returns default only if the key is missing or explicitly empty.
Conversion and substitution errors are returned.
§Type Parameters
T- Target type supported byFromConfig
§Parameters
name- Configuration item namedefault- Default value
§Returns
Returns the configuration value or default value. Conversion and substitution errors are returned instead of being hidden by the default.
§Examples
use qubit_config::Config;
let config = Config::new();
let port: i32 = config.get_or("port", 8080).unwrap();
let host: String = config.get_or("host", "localhost").unwrap();
assert_eq!(port, 8080);
assert_eq!(host, "localhost");Sourcepub fn get_any<T>(&self, names: impl ConfigNames) -> ConfigResult<T>where
T: FromConfig,
pub fn get_any<T>(&self, names: impl ConfigNames) -> ConfigResult<T>where
T: FromConfig,
Sourcepub fn get_optional_any<T>(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<T>>where
T: FromConfig,
pub fn get_optional_any<T>(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<T>>where
T: FromConfig,
Sourcepub fn get_any_or<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
pub fn get_any_or<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
Sourcepub fn get_any_or_with<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
read_options: &ConfigReadOptions,
) -> ConfigResult<T>where
T: FromConfig,
pub fn get_any_or_with<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
read_options: &ConfigReadOptions,
) -> ConfigResult<T>where
T: FromConfig,
Gets the first configured value from names with explicit read options,
or default when absent.
§Parameters
names- Candidate keys checked in priority order.default- Fallback used only when all keys are missing or empty.read_options- Parsing options for this read.
§Returns
Parsed value or default; conversion errors are returned.
Sourcepub fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>where
T: FromConfig,
pub fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>where
T: FromConfig,
Sourcepub fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>where
T: FromConfig,
pub fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>where
T: FromConfig,
Sourcepub fn get_list<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
T: FromConfig,
pub fn get_list<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
T: FromConfig,
Gets a list of configuration values, converting each stored element to
T.
Gets all values of a configuration item (multi-value configuration).
§Type Parameters
T- Target type supported byFromConfig
§Parameters
name- Configuration item name
§Returns
Returns a list of values on success, or an error on failure
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("ports", vec![8080, 8081, 8082]).unwrap();
let ports: Vec<i32> = config.get_list("ports").unwrap();
assert_eq!(ports, vec![8080, 8081, 8082]);Sourcepub fn get_list_strict<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
MultiValues: MultiValuesGetter<T>,
pub fn get_list_strict<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
MultiValues: MultiValuesGetter<T>,
Gets all configuration values only when the stored values already have the exact requested element type.
Unlike Self::get_list, this method preserves the pre-conversion
list read semantics. It returns an empty vector for empty properties and
ConfigError::TypeMismatch for non-empty values of another stored
type.
§Type Parameters
T- Exact element type supported byMultiValuesGetter
§Parameters
name- Configuration item name
§Returns
A vector of exact typed values on success, or a ConfigError on
failure.
Sourcepub fn set<S>(&mut self, name: impl ConfigName, values: S) -> ConfigResult<()>where
S: for<'a> MultiValuesSetArg<'a>,
<S as MultiValuesSetArg<'static>>::Item: Clone,
MultiValues: MultiValuesSetter<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetterSlice<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSingleSetter<<S as MultiValuesSetArg<'static>>::Item>,
pub fn set<S>(&mut self, name: impl ConfigName, values: S) -> ConfigResult<()>where
S: for<'a> MultiValuesSetArg<'a>,
<S as MultiValuesSetArg<'static>>::Item: Clone,
MultiValues: MultiValuesSetter<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetterSlice<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSingleSetter<<S as MultiValuesSetArg<'static>>::Item>,
Sets a configuration value
This is the core method for setting configuration values, supporting type inference.
§Type Parameters
T- Element type, automatically inferred from thevaluesparameter
§Parameters
name- Configuration item namevalues- Value to store; supportsT,Vec<T>,&[T], and related forms accepted byMultiValuessetters
§Returns
Returns Ok(()) on success, or an error on failure
§Errors
ConfigError::PropertyIsFinalif the property is marked final
§Examples
use qubit_config::Config;
let mut config = Config::new();
// Set single values (type auto-inference)
config.set("port", 8080).unwrap(); // T inferred as i32
config.set("host", "localhost").unwrap();
// T inferred as String; &str is converted
config.set("debug", true).unwrap(); // T inferred as bool
config.set("timeout", 30.5).unwrap(); // T inferred as f64
// Set multiple values (type auto-inference)
config.set("ports", vec![8080, 8081, 8082]).unwrap(); // T inferred as i32
config.set("hosts", vec!["host1", "host2"]).unwrap();
// T inferred as &str (then converted)Sourcepub fn add<S>(&mut self, name: impl ConfigName, values: S) -> ConfigResult<()>where
S: for<'a> MultiValuesAddArg<'a, Item = <S as MultiValuesSetArg<'static>>::Item> + for<'a> MultiValuesSetArg<'a>,
<S as MultiValuesSetArg<'static>>::Item: Clone,
MultiValues: MultiValuesAdder<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesMultiAdder<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetter<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetterSlice<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSingleSetter<<S as MultiValuesSetArg<'static>>::Item>,
pub fn add<S>(&mut self, name: impl ConfigName, values: S) -> ConfigResult<()>where
S: for<'a> MultiValuesAddArg<'a, Item = <S as MultiValuesSetArg<'static>>::Item> + for<'a> MultiValuesSetArg<'a>,
<S as MultiValuesSetArg<'static>>::Item: Clone,
MultiValues: MultiValuesAdder<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesMultiAdder<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetter<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSetterSlice<<S as MultiValuesSetArg<'static>>::Item> + MultiValuesSingleSetter<<S as MultiValuesSetArg<'static>>::Item>,
Adds configuration values
Adds values to an existing configuration item (multi-value properties).
§Type Parameters
T- Element type, automatically inferred from thevaluesparameter
§Parameters
name- Configuration item namevalues- Values to append; supports the same forms asSelf::set
§Returns
Returns Ok(()) on success, or an error on failure
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap(); // Set initial value
config.add("port", 8081).unwrap(); // Add single value
config.add("port", vec![8082, 8083]).unwrap(); // Add multiple values
config.add("port", vec![8084, 8085]).unwrap(); // Add slice
let ports: Vec<i32> = config.get_list("port").unwrap();
assert_eq!(ports, vec![8080, 8081, 8082, 8083, 8084, 8085]);Sourcepub fn get_string(&self, name: impl ConfigName) -> ConfigResult<String>
pub fn get_string(&self, name: impl ConfigName) -> ConfigResult<String>
Gets a string configuration value (with variable substitution)
If variable substitution is enabled, replaces ${var_name} placeholders
in the stored string.
§Parameters
name- Configuration item name
§Returns
Returns the string value on success, or an error on failure
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("base_url", "http://localhost").unwrap();
config.set("api_url", "${base_url}/api").unwrap();
let api_url = config.get_string("api_url").unwrap();
assert_eq!(api_url, "http://localhost/api");Sourcepub fn get_string_any(&self, names: impl ConfigNames) -> ConfigResult<String>
pub fn get_string_any(&self, names: impl ConfigNames) -> ConfigResult<String>
Sourcepub fn get_optional_string_any(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<String>>
pub fn get_optional_string_any( &self, names: impl ConfigNames, ) -> ConfigResult<Option<String>>
Sourcepub fn get_string_any_or(
&self,
names: impl ConfigNames,
default: &str,
) -> ConfigResult<String>
pub fn get_string_any_or( &self, names: impl ConfigNames, default: &str, ) -> ConfigResult<String>
Gets a string from any key, or default when all keys are missing or
empty.
§Parameters
names- Candidate keys checked in priority order.default- Fallback used only when all keys are missing or empty.
§Returns
Returns the string value or default value. Substitution errors are returned instead of being hidden by the default.
Sourcepub fn get_string_or(
&self,
name: impl ConfigName,
default: &str,
) -> ConfigResult<String>
pub fn get_string_or( &self, name: impl ConfigName, default: &str, ) -> ConfigResult<String>
Sourcepub fn get_string_list(
&self,
name: impl ConfigName,
) -> ConfigResult<Vec<String>>
pub fn get_string_list( &self, name: impl ConfigName, ) -> ConfigResult<Vec<String>>
Gets a list of string configuration values (with variable substitution)
If variable substitution is enabled, runs it on each list element
(same ${var_name} rules as Self::get_string).
§Parameters
name- Configuration item name
§Returns
Returns a list of strings on success, or an error on failure
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("base_path", "/opt/app").unwrap();
config.set("paths", vec!["${base_path}/bin", "${base_path}/lib"]).unwrap();
let paths = config.get_string_list("paths").unwrap();
assert_eq!(paths, vec!["/opt/app/bin", "/opt/app/lib"]);Sourcepub fn get_string_list_or(
&self,
name: impl ConfigName,
default: &[&str],
) -> ConfigResult<Vec<String>>
pub fn get_string_list_or( &self, name: impl ConfigName, default: &[&str], ) -> ConfigResult<Vec<String>>
Gets a list of string configuration values or returns a default value (with variable substitution)
§Parameters
name- Configuration item namedefault- Default value (can be array slice or vec)
§Returns
Returns the list of strings or default value. Substitution and parsing errors are returned instead of being hidden by the default.
§Examples
use qubit_config::Config;
let config = Config::new();
// Using array slice
let paths = config.get_string_list_or("paths", &["/default/path"]).unwrap();
assert_eq!(paths, vec!["/default/path"]);
// Using vec
let paths = config.get_string_list_or("paths", &vec!["path1", "path2"]).unwrap();
assert_eq!(paths, vec!["path1", "path2"]);Sourcepub fn from_source(source: &dyn ConfigSource) -> ConfigResult<Self>
pub fn from_source(source: &dyn ConfigSource) -> ConfigResult<Self>
Creates a new configuration by loading a ConfigSource.
The returned configuration starts empty and is populated by the given
source. This is a convenience constructor for callers that do not need
to customize the target Config before loading.
§Parameters
source- The configuration source to load from.
§Returns
A populated configuration.
§Errors
Returns any ConfigError produced by the source while loading or by
the underlying config mutation methods.
Sourcepub fn from_env() -> ConfigResult<Self>
pub fn from_env() -> ConfigResult<Self>
Creates a configuration from all current process environment variables.
Environment variable names are loaded as-is. Use
Self::from_env_prefix when the application uses a dedicated prefix
and wants normalized dot-separated keys.
§Returns
A configuration populated from the process environment.
§Errors
Returns ConfigError if a matching environment key or value is not
valid Unicode, or if setting a loaded property fails.
Sourcepub fn from_env_prefix(prefix: &str) -> ConfigResult<Self>
pub fn from_env_prefix(prefix: &str) -> ConfigResult<Self>
Creates a configuration from environment variables with a prefix.
Only variables starting with prefix are loaded. The prefix is stripped,
the remaining key is lowercased, and underscores are converted to dots.
§Parameters
prefix- Prefix used to select environment variables.
§Returns
A configuration populated from matching environment variables.
§Errors
Returns ConfigError if a matching environment key or value is not
valid Unicode, or if setting a loaded property fails.
Sourcepub fn from_env_options(
prefix: &str,
strip_prefix: bool,
convert_underscores: bool,
lowercase_keys: bool,
) -> ConfigResult<Self>
pub fn from_env_options( prefix: &str, strip_prefix: bool, convert_underscores: bool, lowercase_keys: bool, ) -> ConfigResult<Self>
Creates a configuration from environment variables with explicit key transformation options.
§Parameters
prefix- Prefix used to select environment variables.strip_prefix- Whether to strip the prefix from loaded keys.convert_underscores- Whether to convert underscores to dots.lowercase_keys- Whether to lowercase loaded keys.
§Returns
A configuration populated from matching environment variables.
§Errors
Returns ConfigError if a matching environment key or value is not
valid Unicode, or if setting a loaded property fails.
Sourcepub fn from_toml_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
pub fn from_toml_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
Creates a configuration from a TOML file.
§Parameters
path- Path to the TOML file.
§Returns
A configuration populated from the TOML file.
§Errors
Returns ConfigError::IoError if the file cannot be read,
ConfigError::ParseError if the TOML cannot be parsed, or another
ConfigError if setting a loaded property fails.
Sourcepub fn from_yaml_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
pub fn from_yaml_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
Creates a configuration from a YAML file.
§Parameters
path- Path to the YAML file.
§Returns
A configuration populated from the YAML file.
§Errors
Returns ConfigError::IoError if the file cannot be read,
ConfigError::ParseError if the YAML cannot be parsed, or another
ConfigError if setting a loaded property fails.
Sourcepub fn from_properties_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
pub fn from_properties_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
Creates a configuration from a Java .properties file.
§Parameters
path- Path to the.propertiesfile.
§Returns
A configuration populated from the .properties file.
§Errors
Returns ConfigError::IoError if the file cannot be read, or another
ConfigError if setting a loaded property fails.
Sourcepub fn from_env_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
pub fn from_env_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>
Creates a configuration from a .env file.
§Parameters
path- Path to the.envfile.
§Returns
A configuration populated from the .env file.
§Errors
Returns ConfigError::IoError if the file cannot be read,
ConfigError::ParseError if dotenv parsing fails, or another
ConfigError if setting a loaded property fails.
Sourcepub fn merge_from_source(
&mut self,
source: &dyn ConfigSource,
) -> ConfigResult<()>
pub fn merge_from_source( &mut self, source: &dyn ConfigSource, ) -> ConfigResult<()>
Merges configuration from a ConfigSource
Loads all key-value pairs from the given source and merges them into this configuration. Existing non-final properties are overwritten; final properties are preserved and cause an error if the source tries to overwrite them.
§Parameters
source- The configuration source to load from
§Returns
Returns Ok(()) on success, or a ConfigError on failure
§Examples
use qubit_config::Config;
use qubit_config::source::{
CompositeConfigSource, ConfigSource,
EnvConfigSource, TomlConfigSource,
};
let mut composite = CompositeConfigSource::new();
let path = std::env::temp_dir().join(format!(
"qubit-config-doc-{}.toml",
std::process::id()
));
std::fs::write(&path, "app.name = \"demo\"").unwrap();
composite.add(TomlConfigSource::from_file(&path));
composite.add(EnvConfigSource::with_prefix("APP_"));
let mut config = Config::new();
config.merge_from_source(&composite).unwrap();
std::fs::remove_file(&path).unwrap();Sourcepub fn iter(&self) -> impl Iterator<Item = (&str, &Property)>
pub fn iter(&self) -> impl Iterator<Item = (&str, &Property)>
Iterates over all configuration entries as (key, &Property) pairs.
§Returns
An iterator yielding (&str, &Property) tuples.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("host", "localhost").unwrap();
config.set("port", 8080).unwrap();
for (key, prop) in config.iter() {
println!("{} = {:?}", key, prop);
}Sourcepub fn iter_prefix<'a>(
&'a self,
prefix: &'a str,
) -> impl Iterator<Item = (&'a str, &'a Property)>
pub fn iter_prefix<'a>( &'a self, prefix: &'a str, ) -> impl Iterator<Item = (&'a str, &'a Property)>
Iterates over all configuration entries whose key starts with prefix.
§Parameters
prefix- The key prefix to filter by (e.g.,"http.")
§Returns
An iterator of (&str, &Property) whose keys start with prefix.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("http.host", "localhost").unwrap();
config.set("http.port", 8080).unwrap();
config.set("db.host", "dbhost").unwrap();
let http_entries: Vec<_> = config.iter_prefix("http.").collect();
assert_eq!(http_entries.len(), 2);Sourcepub fn contains_prefix(&self, prefix: &str) -> bool
pub fn contains_prefix(&self, prefix: &str) -> bool
Returns true if any configuration key starts with prefix.
§Parameters
prefix- The key prefix to check
§Returns
true if at least one key starts with prefix, false otherwise.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("http.host", "localhost").unwrap();
assert!(config.contains_prefix("http."));
assert!(!config.contains_prefix("db."));Sourcepub fn subconfig(
&self,
prefix: &str,
strip_prefix: bool,
) -> ConfigResult<Config>
pub fn subconfig( &self, prefix: &str, strip_prefix: bool, ) -> ConfigResult<Config>
Extracts a sub-configuration for child keys below prefix.
An exact key equal to prefix is treated as a value, not as part of the
extracted subtree. For example, subconfig("http", true) includes
http.host as host, but does not include an exact http property.
§Parameters
prefix- The key prefix to extract (e.g.,"http")strip_prefix- Whentrue, removesprefixand the following dot from keys in the result; whenfalse, keys are copied unchanged.
§Returns
A new Config containing only child entries below prefix.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("http.host", "localhost").unwrap();
config.set("http.port", 8080).unwrap();
config.set("db.host", "dbhost").unwrap();
let http_config = config.subconfig("http", true).unwrap();
assert!(http_config.contains("host"));
assert!(http_config.contains("port"));
assert!(!http_config.contains("db.host"));Sourcepub fn is_null(&self, name: impl ConfigName) -> bool
pub fn is_null(&self, name: impl ConfigName) -> bool
Returns true if the property exists but has no value (empty / null).
This distinguishes between:
- Key does not exist →
contains()returnsfalse - Key exists but is empty/null →
is_null()returnstrue
§Parameters
name- Configuration item name
§Returns
true if the property exists and has no values (is empty).
§Examples
use qubit_config::Config;
use qubit_datatype::DataType;
let mut config = Config::new();
config.set_null("nullable", DataType::String).unwrap();
assert!(config.is_null("nullable"));
assert!(!config.is_null("missing"));Sourcepub fn get_optional<T>(&self, name: impl ConfigName) -> ConfigResult<Option<T>>where
T: FromConfig,
pub fn get_optional<T>(&self, name: impl ConfigName) -> ConfigResult<Option<T>>where
T: FromConfig,
Gets an optional configuration value.
Distinguishes between three states:
Ok(Some(value))– key exists and has a valueOk(None)– key does not exist, or exists but is null/emptyErr(e)– key exists and has a value, but conversion failed
§Type Parameters
T- Target type
§Parameters
name- Configuration item name
§Returns
Ok(Some(value)), Ok(None), or Err as described above.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("port", 8080).unwrap();
let port: Option<i32> = config.get_optional("port").unwrap();
assert_eq!(port, Some(8080));
let missing: Option<i32> = config.get_optional("missing").unwrap();
assert_eq!(missing, None);Sourcepub fn get_optional_list<T>(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<T>>>where
T: FromConfig,
pub fn get_optional_list<T>(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<T>>>where
T: FromConfig,
Gets an optional list of configuration values.
See also Self::get_optional_string_list for optional string lists
with variable substitution.
Distinguishes between three states:
Ok(Some(vec))– key exists and has valuesOk(None)– key does not exist, or exists but is null/emptyErr(e)– key exists and has values, but conversion failed
§Type Parameters
T- Target element type supported byFromConfig
§Parameters
name- Configuration item name
§Returns
Ok(Some(vec)), Ok(None), or Err as described above.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("ports", vec![8080, 8081]).unwrap();
let ports: Option<Vec<i32>> = config.get_optional_list("ports").unwrap();
assert_eq!(ports, Some(vec![8080, 8081]));
let missing: Option<Vec<i32>> = config.get_optional_list("missing").unwrap();
assert_eq!(missing, None);Sourcepub fn get_optional_string(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<String>>
pub fn get_optional_string( &self, name: impl ConfigName, ) -> ConfigResult<Option<String>>
Gets an optional string (with variable substitution when enabled).
Same semantics as Self::get_optional, but values are read via
Self::get_string, so ${...} substitution applies when enabled.
§Parameters
name- Configuration item name
§Returns
Ok(Some(s)), Ok(None), or Err as for Self::get_optional.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("base", "http://localhost").unwrap();
config.set("api", "${base}/api").unwrap();
let api = config.get_optional_string("api").unwrap();
assert_eq!(api.as_deref(), Some("http://localhost/api"));
let missing = config.get_optional_string("missing").unwrap();
assert_eq!(missing, None);Sourcepub fn get_optional_string_list(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<String>>>
pub fn get_optional_string_list( &self, name: impl ConfigName, ) -> ConfigResult<Option<Vec<String>>>
Gets an optional string list (substitution per element when enabled).
Same semantics as Self::get_optional_list, but elements use
Self::get_string_list (same ${...} rules as Self::get_string).
§Parameters
name- Configuration item name
§Returns
Ok(Some(vec)), Ok(None), or Err like Self::get_optional_list.
§Examples
use qubit_config::Config;
let mut config = Config::new();
config.set("root", "/opt/app").unwrap();
config.set("paths", vec!["${root}/bin", "${root}/lib"]).unwrap();
let paths = config.get_optional_string_list("paths").unwrap();
assert_eq!(
paths,
Some(vec![
"/opt/app/bin".to_string(),
"/opt/app/lib".to_string(),
]),
);Sourcepub fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>where
T: DeserializeOwned,
pub fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>where
T: DeserializeOwned,
Deserializes a config value or subtree at prefix into T using serde.
String values inside the generated serde value apply the same
${...} substitution rules as Self::get_string and
Self::get_string_list when substitution is enabled. Scalar strings
are then parsed with this config’s ConfigReadOptions, so
environment-style booleans, numeric strings, and scalar string lists
behave consistently with typed get reads.
When prefix is non-empty, an exact property named prefix is
deserialized as the root value. If no exact property exists, child keys
under prefix (prefix and trailing dot removed) form an object for
serde, for example:
#[derive(serde::Deserialize)]
struct HttpOptions {
host: String,
port: u16,
}can be populated from config keys http.host and http.port by calling
config.deserialize::<HttpOptions>("http"). Defining both http and
http.* is a ConfigError::KeyConflict, as are ambiguous dotted paths
such as a and a.b inside the same deserialized object.
§Type Parameters
T- Target type, must implementserde::de::DeserializeOwned
§Parameters
prefix- Key prefix for the struct fields (""means the root map)
§Returns
The deserialized T.
§Errors
Returns ConfigError::KeyConflict for ambiguous key shapes,
substitution/conversion errors while preparing string values, or
ConfigError::DeserializeError when serde cannot deserialize the
prepared value into T.
§Examples
use qubit_config::Config;
use serde::Deserialize;
#[derive(Deserialize, Debug, PartialEq)]
struct Server {
host: String,
port: i32,
}
let mut config = Config::new();
config.set("server.host", "localhost").unwrap();
config.set("server.port", 8080).unwrap();
let server: Server = config.deserialize("server").unwrap();
assert_eq!(server.host, "localhost");
assert_eq!(server.port, 8080);Sourcepub fn insert_property(
&mut self,
name: impl ConfigName,
property: Property,
) -> ConfigResult<()>
pub fn insert_property( &mut self, name: impl ConfigName, property: Property, ) -> ConfigResult<()>
Inserts or replaces a property using an explicit Property object.
This method enforces two invariants:
namemust exactly matchproperty.name()- existing final properties cannot be overridden
§Parameters
name- Target key in this config.property- Property to store undername.
§Returns
Ok(()) on success.
§Errors
ConfigError::MergeErrorwhennameandproperty.name()differ.ConfigError::PropertyIsFinalwhen trying to override a final property.
Sourcepub fn set_null(
&mut self,
name: impl ConfigName,
data_type: DataType,
) -> ConfigResult<()>
pub fn set_null( &mut self, name: impl ConfigName, data_type: DataType, ) -> ConfigResult<()>
Sets a key to a typed null/empty value.
This is the preferred public API for representing null/empty values without exposing raw mutable access to the internal map.
§Parameters
name- Configuration item name.data_type- Data type metadata for the empty value.
§Returns
Ok(()) on success.
§Errors
ConfigError::PropertyIsFinalwhen trying to override a final property.
Trait Implementations§
Source§impl ConfigReader for Config
impl ConfigReader for Config
Source§fn is_enable_variable_substitution(&self) -> bool
fn is_enable_variable_substitution(&self) -> bool
${...} variable substitution is applied when reading
string values. Read moreSource§fn max_substitution_depth(&self) -> usize
fn max_substitution_depth(&self) -> usize
${...} references. Read moreSource§fn read_options(&self) -> &ConfigReadOptions
fn read_options(&self) -> &ConfigReadOptions
Source§fn description(&self) -> Option<&str>
fn description(&self) -> Option<&str>
crate::Config).Source§fn get_property(&self, name: impl ConfigName) -> Option<&Property>
fn get_property(&self, name: impl ConfigName) -> Option<&Property>
Source§fn len(&self) -> usize
fn len(&self) -> usize
crate::Config; relative keys only for a ConfigPrefixView).Source§fn keys(&self) -> Vec<String>
fn keys(&self) -> Vec<String>
Source§fn contains(&self, name: impl ConfigName) -> bool
fn contains(&self, name: impl ConfigName) -> bool
Source§fn get_strict<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
MultiValues: MultiValuesFirstGetter<T>,
fn get_strict<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
MultiValues: MultiValuesFirstGetter<T>,
name without cross-type conversion. Read moreSource§fn get_list<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
T: FromConfig,
fn get_list<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
T: FromConfig,
Source§fn get_list_strict<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
MultiValues: MultiValuesGetter<T>,
fn get_list_strict<T>(&self, name: impl ConfigName) -> ConfigResult<Vec<T>>where
MultiValues: MultiValuesGetter<T>,
name without cross-type conversion. Read moreSource§fn get_optional_list<T>(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<T>>>where
T: FromConfig,
fn get_optional_list<T>(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<T>>>where
T: FromConfig,
crate::Config::get_optional_list. Read moreSource§fn contains_prefix(&self, prefix: &str) -> bool
fn contains_prefix(&self, prefix: &str) -> bool
prefix. Read moreSource§fn iter_prefix<'a>(
&'a self,
prefix: &'a str,
) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>
fn iter_prefix<'a>( &'a self, prefix: &'a str, ) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>
Source§fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>
(key, property) pairs visible to this reader (same scope
as Self::keys).Source§fn is_null(&self, name: impl ConfigName) -> bool
fn is_null(&self, name: impl ConfigName) -> bool
true if the key exists and the property has no values (same
as crate::Config::is_null).Source§fn subconfig(&self, prefix: &str, strip_prefix: bool) -> ConfigResult<Config>
fn subconfig(&self, prefix: &str, strip_prefix: bool) -> ConfigResult<Config>
Config (same semantics as
crate::Config::subconfig; on a prefix view, prefix is relative to
the view).Source§fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>where
T: DeserializeOwned,
fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>where
T: DeserializeOwned,
prefix with serde (same as
crate::Config::deserialize; on a prefix view, prefix is relative).Source§fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>
fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>
prefix. Read moreSource§fn get<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
T: FromConfig,
fn get<T>(&self, name: impl ConfigName) -> ConfigResult<T>where
T: FromConfig,
Source§fn get_or<T>(
&self,
name: impl ConfigName,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
fn get_or<T>(
&self,
name: impl ConfigName,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
default if the key is missing or empty. Read moreSource§fn get_optional<T>(&self, name: impl ConfigName) -> ConfigResult<Option<T>>where
T: FromConfig,
fn get_optional<T>(&self, name: impl ConfigName) -> ConfigResult<Option<T>>where
T: FromConfig,
crate::Config::get_optional. Read moreSource§fn get_any<T>(&self, names: impl ConfigNames) -> ConfigResult<T>where
T: FromConfig,
fn get_any<T>(&self, names: impl ConfigNames) -> ConfigResult<T>where
T: FromConfig,
names. Read moreSource§fn get_optional_any<T>(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<T>>where
T: FromConfig,
fn get_optional_any<T>(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<T>>where
T: FromConfig,
Source§fn get_any_or<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
fn get_any_or<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
) -> ConfigResult<T>where
T: FromConfig,
default only when all keys are
absent or empty. Read moreSource§fn get_any_or_with<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
read_options: &ConfigReadOptions,
) -> ConfigResult<T>where
T: FromConfig,
fn get_any_or_with<T>(
&self,
names: impl ConfigNames,
default: impl IntoConfigDefault<T>,
read_options: &ConfigReadOptions,
) -> ConfigResult<T>where
T: FromConfig,
default
only when all keys are absent or empty. Read moreSource§fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>where
T: FromConfig,
fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>where
T: FromConfig,
Source§fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>where
T: FromConfig,
fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>where
T: FromConfig,
Source§fn get_optional_any_with_options<T>(
&self,
names: impl ConfigNames,
options: &ConfigReadOptions,
) -> ConfigResult<Option<T>>where
T: FromConfig,
fn get_optional_any_with_options<T>(
&self,
names: impl ConfigNames,
options: &ConfigReadOptions,
) -> ConfigResult<Option<T>>where
T: FromConfig,
Source§fn resolve_key(&self, name: impl ConfigName) -> String
fn resolve_key(&self, name: impl ConfigName) -> String
Source§fn get_string(&self, name: impl ConfigName) -> ConfigResult<String>
fn get_string(&self, name: impl ConfigName) -> ConfigResult<String>
Source§fn get_string_any(&self, names: impl ConfigNames) -> ConfigResult<String>
fn get_string_any(&self, names: impl ConfigNames) -> ConfigResult<String>
names. Read moreSource§fn get_optional_string_any(
&self,
names: impl ConfigNames,
) -> ConfigResult<Option<String>>
fn get_optional_string_any( &self, names: impl ConfigNames, ) -> ConfigResult<Option<String>>
Source§fn get_string_any_or(
&self,
names: impl ConfigNames,
default: &str,
) -> ConfigResult<String>
fn get_string_any_or( &self, names: impl ConfigNames, default: &str, ) -> ConfigResult<String>
default when all keys are missing or
empty. Read moreSource§fn get_string_or(
&self,
name: impl ConfigName,
default: &str,
) -> ConfigResult<String>
fn get_string_or( &self, name: impl ConfigName, default: &str, ) -> ConfigResult<String>
default if the key is
missing or empty. Read moreSource§fn get_string_list(&self, name: impl ConfigName) -> ConfigResult<Vec<String>>
fn get_string_list(&self, name: impl ConfigName) -> ConfigResult<Vec<String>>
name, applying substitution to each element
when enabled. Read moreSource§fn get_string_list_or(
&self,
name: impl ConfigName,
default: &[&str],
) -> ConfigResult<Vec<String>>
fn get_string_list_or( &self, name: impl ConfigName, default: &[&str], ) -> ConfigResult<Vec<String>>
default if the key is
missing or empty. Read moreSource§fn get_optional_string(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<String>>
fn get_optional_string( &self, name: impl ConfigName, ) -> ConfigResult<Option<String>>
crate::Config::get_optional_string. Read moreSource§fn get_optional_string_list(
&self,
name: impl ConfigName,
) -> ConfigResult<Option<Vec<String>>>
fn get_optional_string_list( &self, name: impl ConfigName, ) -> ConfigResult<Option<Vec<String>>>
Source§fn get_optional_any_with_options_and_substitution<T>(
&self,
names: impl ConfigNames,
options: &ConfigReadOptions,
) -> ConfigResult<Option<T>>where
T: FromConfig,
fn get_optional_any_with_options_and_substitution<T>(
&self,
names: impl ConfigNames,
options: &ConfigReadOptions,
) -> ConfigResult<Option<T>>where
T: FromConfig,
Source§impl<'de> Deserialize<'de> for Config
impl<'de> Deserialize<'de> for Config
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
impl StructuralPartialEq for Config
Auto Trait Implementations§
impl Freeze for Config
impl RefUnwindSafe for Config
impl Send for Config
impl Sync for Config
impl Unpin for Config
impl UnsafeUnpin for Config
impl UnwindSafe for Config
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T, D> IntoConfigDefault<T> for Dwhere
D: IntoValueDefault<T>,
impl<T, D> IntoConfigDefault<T> for Dwhere
D: IntoValueDefault<T>,
Source§fn into_config_default(self) -> T
fn into_config_default(self) -> T
T.