Skip to main content

Config

Struct Config 

Source
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: u64 = config.get_or("timeout", 30).unwrap();

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Creates a new empty configuration

§Returns

Returns a new configuration instance

§Examples
use qubit_config::Config;

let mut config = Config::new();
assert!(config.is_empty());
Source

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"));
Source

pub fn description(&self) -> Option<&str>

Gets the configuration description

§Returns

Returns the configuration description as Option

Source

pub fn set_description(&mut self, description: Option<String>)

Sets the configuration description

§Parameters
  • description - Configuration description
§Returns

Nothing.

Source

pub fn is_enable_variable_substitution(&self) -> bool

Checks if variable substitution is enabled

§Returns

Returns true if variable substitution is enabled

Source

pub fn set_enable_variable_substitution(&mut self, enable: bool)

Sets whether to enable variable substitution

§Parameters
  • enable - Whether to enable
§Returns

Nothing.

Source

pub fn max_substitution_depth(&self) -> usize

Gets the maximum depth for variable substitution

§Returns

Returns the maximum depth value

Source

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.

Source

pub fn set_read_options(&mut self, read_options: ConfigReadOptions) -> &mut Self

Sets the global read parsing options.

§Parameters
  • read_options - New read parsing options.
§Returns

Mutable reference to this configuration for chaining.

Source

pub fn with_read_options(&self, read_options: ConfigReadOptions) -> Self

Returns a cloned configuration with different read parsing options.

§Parameters
  • read_options - Read options for the returned configuration.
§Returns

A cloned Config using read_options.

Source

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");
Source

pub fn set_max_substitution_depth(&mut self, depth: usize)

Sets the maximum depth for variable substitution

§Parameters
  • depth - Maximum depth
§Returns

Nothing.

Source

pub fn contains(&self, name: &str) -> 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"));
Source

pub fn get_property(&self, name: &str) -> Option<&Property>

Gets a reference to a configuration item

§Parameters
  • name - Configuration item name
§Returns

Returns Option containing the configuration item

Source

pub fn get_property_mut( &mut self, name: &str, ) -> 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.

Source

pub fn set_final(&mut self, name: &str, 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
Source

pub fn remove(&mut self, name: &str) -> 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"));
Source

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.

Source

pub fn len(&self) -> usize

Gets the number of configuration items

§Returns

Returns the number of configuration items

Source

pub fn is_empty(&self) -> bool

Checks if the configuration is empty

§Returns

Returns true if the configuration contains no items

Source

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()));
Source

pub fn get<T>(&self, name: &str) -> ConfigResult<T>
where T: FromConfig,

Gets a configuration value, converting the stored first value to T.

Core read API with type inference.

§Note

This method does not perform variable substitution for string types. If you need variable substitution, use Self::get_string.

§Type Parameters
§Parameters
  • name - Configuration item name
§Returns

The value of the specified type on success, or a ConfigError on failure.

§Errors
§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());
Source

pub fn get_strict<T>(&self, name: &str) -> 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 by [MultiValuesFirstGetter]
§Parameters
  • name - Configuration item name
§Returns

The exact typed value on success, or a ConfigError on failure.

Source

pub fn get_or<T>(&self, name: &str, default: 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
§Parameters
  • name - Configuration item name
  • default - 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".to_string()).unwrap();

assert_eq!(port, 8080);
assert_eq!(host, "localhost");
Source

pub fn get_any<T>(&self, names: &[&str]) -> ConfigResult<T>
where T: FromConfig,

Gets the first configured value from names.

§Parameters
  • names - Candidate keys checked in priority order.
§Returns

Parsed value from the first present and non-empty key.

Source

pub fn get_optional_any<T>(&self, names: &[&str]) -> ConfigResult<Option<T>>
where T: FromConfig,

Gets an optional value from the first configured key.

§Parameters
  • names - Candidate keys checked in priority order.
§Returns

Ok(None) when all keys are missing or empty.

Source

pub fn get_any_or<T>(&self, names: &[&str], default: T) -> ConfigResult<T>
where T: FromConfig,

Gets the first configured value from names, or default when absent.

§Parameters
  • names - Candidate keys checked in priority order.
  • default - Fallback used only when all keys are missing or empty.
§Returns

Parsed value or default; conversion errors are returned.

Source

pub fn get_any_or_with<T>( &self, names: &[&str], default: 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.

Source

pub fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>
where T: FromConfig,

Reads a declared configuration field.

§Parameters
  • field - Field declaration with name, aliases, defaults, and optional read options.
§Returns

Parsed field value or default.

Source

pub fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>
where T: FromConfig,

Reads an optional declared configuration field.

§Parameters
  • field - Field declaration.
§Returns

Parsed field value, default, or None.

Source

pub fn get_list<T>(&self, name: &str) -> 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
§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]);
Source

pub fn get_list_strict<T>(&self, name: &str) -> 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 by [MultiValuesGetter]
§Parameters
  • name - Configuration item name
§Returns

A vector of exact typed values on success, or a ConfigError on failure.

Source

pub fn set<S>(&mut self, name: &str, 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 the values parameter
§Parameters
  • name - Configuration item name
  • values - Value to store; supports T, Vec<T>, &[T], and related forms accepted by MultiValues setters
§Returns

Returns Ok(()) on success, or an error on failure

§Errors
§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)
Source

pub fn add<S>(&mut self, name: &str, 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 the values parameter
§Parameters
  • name - Configuration item name
  • values - Values to append; supports the same forms as Self::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]);
Source

pub fn get_string(&self, name: &str) -> 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");
Source

pub fn get_string_any(&self, names: &[&str]) -> ConfigResult<String>

Gets a string value from the first present and non-empty key in names.

§Parameters
  • names - Candidate keys checked in priority order.
§Returns

Returns the string value on success, or an error on failure.

Source

pub fn get_optional_string_any( &self, names: &[&str], ) -> ConfigResult<Option<String>>

Gets an optional string value from the first present and non-empty key.

§Parameters
  • names - Candidate keys checked in priority order.
§Returns

Ok(None) when all keys are missing or empty.

Source

pub fn get_string_any_or( &self, names: &[&str], 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.

Source

pub fn get_string_or(&self, name: &str, default: &str) -> ConfigResult<String>

Gets a string with substitution, or default if the key is absent or empty.

§Parameters
  • name - Configuration item name
  • default - Default value
§Returns

Returns the string value or default value. Substitution errors are returned instead of being hidden by the default.

Source

pub fn get_string_list(&self, name: &str) -> 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"]);
Source

pub fn get_string_list_or( &self, name: &str, default: &[&str], ) -> ConfigResult<Vec<String>>

Gets a list of string configuration values or returns a default value (with variable substitution)

§Parameters
  • name - Configuration item name
  • default - 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"]);
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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 .properties file.
§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.

Source

pub fn from_env_file<P: AsRef<Path>>(path: P) -> ConfigResult<Self>

Creates a configuration from a .env file.

§Parameters
  • path - Path to the .env file.
§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.

Source

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();
Source

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

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

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."));
Source

pub fn subconfig( &self, prefix: &str, strip_prefix: bool, ) -> ConfigResult<Config>

Extracts a sub-configuration for keys matching prefix.

§Parameters
  • prefix - The key prefix to extract (e.g., "http")
  • strip_prefix - When true, removes prefix and the following dot from keys in the result; when false, keys are copied unchanged.
§Returns

A new Config containing only the matching entries.

§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"));
Source

pub fn is_null(&self, name: &str) -> bool

Returns true if the property exists but has no value (empty / null).

This distinguishes between:

  • Key does not exist → contains() returns false
  • Key exists but is empty/null → is_null() returns true
§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"));
Source

pub fn get_optional<T>(&self, name: &str) -> ConfigResult<Option<T>>
where T: FromConfig,

Gets an optional configuration value.

Distinguishes between three states:

  • Ok(Some(value)) – key exists and has a value
  • Ok(None) – key does not exist, or exists but is null/empty
  • Err(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);
Source

pub fn get_optional_list<T>(&self, name: &str) -> 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 values
  • Ok(None) – key does not exist, or exists but is null/empty
  • Err(e) – key exists and has values, but conversion failed
§Type Parameters
§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);
Source

pub fn get_optional_string(&self, name: &str) -> 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);
Source

pub fn get_optional_string_list( &self, name: &str, ) -> 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(),
    ]),
);
Source

pub fn deserialize<T>(&self, prefix: &str) -> ConfigResult<T>

Deserializes the 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.

Keys under prefix (prefix and trailing dot removed) form a flat map 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").

§Type Parameters
  • T - Target type, must implement serde::de::DeserializeOwned
§Parameters
  • prefix - Key prefix for the struct fields ("" means the root map)
§Returns

The deserialized T, or a ConfigError::DeserializeError on failure.

§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);
Source

pub fn insert_property( &mut self, name: &str, property: Property, ) -> ConfigResult<()>

Inserts or replaces a property using an explicit Property object.

This method enforces two invariants:

  • name must exactly match property.name()
  • existing final properties cannot be overridden
§Parameters
  • name - Target key in this config.
  • property - Property to store under name.
§Returns

Ok(()) on success.

§Errors
Source

pub fn set_null(&mut self, name: &str, 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

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ConfigReader for Config

Source§

fn is_enable_variable_substitution(&self) -> bool

Returns whether ${...} variable substitution is applied when reading string values. Read more
Source§

fn max_substitution_depth(&self) -> usize

Returns the maximum recursion depth allowed when resolving nested ${...} references. Read more
Source§

fn read_options(&self) -> &ConfigReadOptions

Gets the read options active for this reader. Read more
Source§

fn description(&self) -> Option<&str>

Returns the optional human-readable description attached to this configuration (the whole document; prefix views expose the same value as the underlying crate::Config).
Source§

fn get_property(&self, name: &str) -> Option<&Property>

Returns a reference to the raw Property for name, if present. Read more
Source§

fn len(&self) -> usize

Number of configuration entries visible to this reader (all keys for crate::Config; relative keys only for a ConfigPrefixView).
Source§

fn is_empty(&self) -> bool

Returns true when Self::len is zero.
Source§

fn keys(&self) -> Vec<String>

All keys visible to this reader (relative keys for a prefix view).
Source§

fn contains(&self, name: &str) -> bool

Returns whether a property exists for the given key. Read more
Source§

fn get_strict<T>(&self, name: &str) -> ConfigResult<T>
where MultiValues: MultiValuesFirstGetter<T>,

Reads the first stored value for name without cross-type conversion. Read more
Source§

fn get_list<T>(&self, name: &str) -> ConfigResult<Vec<T>>
where T: FromConfig,

Reads all stored values for name and converts each element to T. Read more
Source§

fn get_list_strict<T>(&self, name: &str) -> ConfigResult<Vec<T>>
where MultiValues: MultiValuesGetter<T>,

Reads all stored values for name without cross-type conversion. Read more
Source§

fn get_optional_list<T>(&self, name: &str) -> ConfigResult<Option<Vec<T>>>
where T: FromConfig,

Gets an optional list with the same semantics as crate::Config::get_optional_list. Read more
Source§

fn contains_prefix(&self, prefix: &str) -> bool

Returns whether any key visible to this reader starts with prefix. Read more
Source§

fn iter_prefix<'a>( &'a self, prefix: &'a str, ) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>

Iterates (key, property) pairs for keys that start with prefix. Read more
Source§

fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a Property)> + 'a>

Iterates all (key, property) pairs visible to this reader (same scope as Self::keys).
Source§

fn is_null(&self, name: &str) -> bool

Returns 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>

Extracts a subtree as a new 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>

Deserializes the subtree at prefix with serde (same as crate::Config::deserialize; on a prefix view, prefix is relative).
Source§

fn prefix_view(&self, prefix: &str) -> ConfigPrefixView<'_>

Creates a read-only prefix view; relative keys resolve under prefix. Read more
Source§

fn get<T>(&self, name: &str) -> ConfigResult<T>
where T: FromConfig,

Reads the first stored value for name and converts it to T. Read more
Source§

fn get_or<T>(&self, name: &str, default: T) -> ConfigResult<T>
where T: FromConfig,

Gets a value or default if the key is missing or empty. Read more
Source§

fn get_optional<T>(&self, name: &str) -> ConfigResult<Option<T>>
where T: FromConfig,

Gets an optional value with the same semantics as crate::Config::get_optional. Read more
Source§

fn get_any<T>(&self, names: &[&str]) -> ConfigResult<T>
where T: FromConfig,

Reads a value from the first present and non-empty key in names. Read more
Source§

fn get_optional_any<T>(&self, names: &[&str]) -> ConfigResult<Option<T>>
where T: FromConfig,

Reads an optional value from the first present and non-empty key. Read more
Source§

fn get_any_or<T>(&self, names: &[&str], default: T) -> ConfigResult<T>
where T: FromConfig,

Reads a value from any key, using default only when all keys are absent or empty. Read more
Source§

fn get_any_or_with<T>( &self, names: &[&str], default: T, read_options: &ConfigReadOptions, ) -> ConfigResult<T>
where T: FromConfig,

Reads a value from any key with explicit read options, using default only when all keys are absent or empty. Read more
Source§

fn read<T>(&self, field: ConfigField<T>) -> ConfigResult<T>
where T: FromConfig,

Reads a declared field. Read more
Source§

fn read_optional<T>(&self, field: ConfigField<T>) -> ConfigResult<Option<T>>
where T: FromConfig,

Reads an optional declared field. Read more
Source§

fn get_optional_any_with_options<T>( &self, names: &[&str], options: &ConfigReadOptions, ) -> ConfigResult<Option<T>>
where T: FromConfig,

Shared implementation for field-level and global multi-key reads.
Source§

fn resolve_key(&self, name: &str) -> String

Resolves name into the canonical key path against the root crate::Config. Read more
Source§

fn get_string(&self, name: &str) -> ConfigResult<String>

Gets a string value, applying variable substitution when enabled. Read more
Source§

fn get_string_any(&self, names: &[&str]) -> ConfigResult<String>

Gets a string value from the first present and non-empty key in names. Read more
Source§

fn get_optional_string_any( &self, names: &[&str], ) -> ConfigResult<Option<String>>

Gets an optional string value from the first present and non-empty key. Read more
Source§

fn get_string_any_or( &self, names: &[&str], default: &str, ) -> ConfigResult<String>

Gets a string from any key, or default when all keys are missing or empty. Read more
Source§

fn get_string_or(&self, name: &str, default: &str) -> ConfigResult<String>

Gets a string value with substitution, or default if the key is missing or empty. Read more
Source§

fn get_string_list(&self, name: &str) -> ConfigResult<Vec<String>>

Gets all string values for name, applying substitution to each element when enabled. Read more
Source§

fn get_string_list_or( &self, name: &str, default: &[&str], ) -> ConfigResult<Vec<String>>

Gets a string list with substitution, or copies default if the key is missing or empty. Read more
Source§

fn get_optional_string(&self, name: &str) -> ConfigResult<Option<String>>

Gets an optional string with the same three-way semantics as crate::Config::get_optional_string. Read more
Source§

fn get_optional_string_list( &self, name: &str, ) -> ConfigResult<Option<Vec<String>>>

Gets an optional string list with per-element substitution when enabled. Read more
Source§

impl Debug for Config

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Config

Source§

fn default() -> Self

Creates a new default configuration

§Returns

Returns a new configuration instance

§Examples
use qubit_config::Config;

let config = Config::default();
assert!(config.is_empty());
Source§

impl<'de> Deserialize<'de> for Config

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Config

Source§

fn eq(&self, other: &Config) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Config

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Config

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,