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

§Important Limitations of Generic set/add Methods

u8 type does not support generic set() and add() methods. See MultiValues documentation for details.

For u8 type configuration values, use dedicated methods:

use qubit_config::Config;

let mut config = Config::new();

// ❌ Not supported: config.set("byte_value", 42u8)?;

// ✅ Method 1: Use dedicated method via get_property_mut
config.get_property_mut("byte_value")
    .unwrap()
    .set_uint8(42)
    .unwrap();

// ✅ Method 2: Create property first if it doesn't exist
if config.get_property("byte_value").is_none() {
    let mut prop = Property::new("byte_value");
    prop.set_uint8(42).unwrap();
    config.properties.insert("byte_value".to_string(), prop);
}

// Reading works normally
let value: u8 = config.get("byte_value")?;

Recommendation: If you truly need to store u8 values, consider using u16 instead, as u8 is rarely used for configuration values in practice, while Vec<u8> is more commonly used for byte arrays (such as keys, hashes, etc.).

§Examples

use qubit_config::Config;

let mut config = Config::new();

// Set configuration values (type inference)
config.set("port", 8080)?;                    // inferred as i32
config.set("host", "localhost")?;              // &str automatically converted to String
config.set("debug", true)?;                   // inferred as bool
config.set("timeout", 30.5)?;                 // inferred as f64

// Set multiple values (type inference)
config.set("ports", vec![8080, 8081, 8082])?; // inferred as i32
config.set("hosts", &["host1", "host2"])?;     // &str automatically converted

// Read configuration values (type inference)
let port: i32 = config.get("port")?;
let host: String = config.get("host")?;
let debug: bool = config.get("debug")?;

// Read configuration values (turbofish)
let port = config.get::<i32>("port")?;

// Read configuration value or use default
let timeout: u64 = config.get_or("timeout", 30);

§Author

Haixing Hu

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

pub fn max_substitution_depth(&self) -> usize

Gets the maximum depth for variable substitution

§Returns

Returns the maximum depth value

Source

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

Sets the maximum depth for variable substitution

§Parameters
  • depth - Maximum depth
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)?;

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) -> Option<&mut Property>

Gets a mutable reference to a configuration item

§Parameters
  • name - Configuration item name
§Returns

Returns mutable Option containing the configuration item

Source

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

Removes a 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)?;

let removed = config.remove("port");
assert!(removed.is_some());
assert!(!config.contains("port"));
Source

pub fn clear(&mut self)

Clears all configuration items

§Examples
use qubit_config::Config;

let mut config = Config::new();
config.set("port", 8080)?;
config.set("host", "localhost")?;

config.clear();
assert!(config.is_empty());
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)?;
config.set("host", "localhost")?;

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 MultiValues: MultiValuesFirstGetter<T>,

Gets a configuration value

This is the core method for getting configuration values, supporting type inference.

§Note

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

§Type Parameters
  • T - Target type, must implement FromPropertyValue trait
§Parameters
  • name - Configuration item name
§Returns

Returns the value of the specified type on success, or an error on failure

§Errors
  • Returns ConfigError::PropertyNotFound if the configuration item doesn’t exist
  • Returns ConfigError::PropertyHasNoValue if the configuration item has no value
  • Returns ConfigError::TypeMismatch if the type doesn’t match
§Examples
use qubit_config::Config;

let mut config = Config::new();
config.set("port", 8080)?;
config.set("host", "localhost")?;

// Method 1: Type inference
let port: i32 = config.get("port")?;
let host: String = config.get("host")?;

// Method 2: Turbofish
let port = config.get::<i32>("port")?;
let host = config.get::<String>("host")?;

// Method 3: Inference from usage
fn start_server(port: i32, host: String) { }
start_server(config.get("port")?, config.get("host")?);
Source

pub fn get_or<T>(&self, name: &str, default: T) -> T
where MultiValues: MultiValuesFirstGetter<T>,

Gets a configuration value or returns a default value

Returns the default value if the configuration item doesn’t exist or retrieval fails.

§Type Parameters
  • T - Target type, must implement FromPropertyValue trait
§Parameters
  • name - Configuration item name
  • default - Default value
§Returns

Returns the configuration value or default value

§Examples
use qubit_config::Config;

let config = Config::new();

let port: i32 = config.get_or("port", 8080);
let host: String = config.get_or("host", "localhost".to_string());

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

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

Gets a list of configuration values

Gets all values of a configuration item (multi-value configuration).

§Type Parameters
  • T - Target type, must implement FromPropertyValue trait
§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])?;

let ports: Vec<i32> = config.get_list("ports")?;
assert_eq!(ports, vec![8080, 8081, 8082]);
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 - Configuration value, supports T, Vec<T>, &[T], and other types
§Returns

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

§Errors
  • Returns ConfigError::PropertyIsFinal if the configuration item is final
§Examples
use qubit_config::Config;

let mut config = Config::new();

// Set single values (type auto-inference)
config.set("port", 8080)?;                    // T inferred as i32
config.set("host", "localhost")?;              // T inferred as String (&str auto-converted)
config.set("debug", true)?;                   // T inferred as bool
config.set("timeout", 30.5)?;                 // T inferred as f64

// Set multiple values (type auto-inference)
config.set("ports", vec![8080, 8081, 8082])?; // T inferred as i32
config.set("hosts", &["host1", "host2"])?;     // T inferred as &str (auto-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 (for multi-value configuration).

§Type Parameters
  • T - Element type, automatically inferred from the values parameter
§Parameters
  • name - Configuration item name
  • values - Values to add, supports T, Vec<T>, &[T], and other types
§Returns

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

§Examples
use qubit_config::Config;

let mut config = Config::new();
config.set("port", 8080)?;                    // Set initial value
config.add("port", 8081)?;                    // Add single value
config.add("port", vec![8082, 8083])?;        // Add multiple values
config.add("port", &[8084, 8085])?;          // Add slice

let ports: Vec<i32> = config.get_list("port")?;
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, automatically replaces variables in ${var_name} format.

§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")?;
config.set("api_url", "${base_url}/api")?;

let api_url = config.get_string("api_url")?;
assert_eq!(api_url, "http://localhost/api");
Source

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

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

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

Returns the string value or default value

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, automatically replaces variables in ${var_name} format for each string in the list.

§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")?;
config.set("paths", vec!["${base_path}/bin", "${base_path}/lib"])?;

let paths = config.get_string_list("paths")?;
assert_eq!(paths, vec!["/opt/app/bin", "/opt/app/lib"]);
Source

pub fn get_string_list_or(&self, name: &str, default: &[&str]) -> 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

§Examples
use qubit_config::Config;

let config = Config::new();

// Using array slice
let paths = config.get_string_list_or("paths", &["/default/path"]);
assert_eq!(paths, vec!["/default/path"]);

// Using vec
let paths = config.get_string_list_or("paths", &vec!["path1", "path2"]);
assert_eq!(paths, vec!["path1", "path2"]);

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