Skip to main content

Config

Struct Config 

Source
pub struct Config { /* private fields */ }
Expand description

High-level configuration manager with format preservation and change tracking

Config provides a comprehensive API for managing configurations throughout their lifecycle. It maintains both the resolved values (for fast access) and format-specific preservation data (for round-trip editing).

§Key Features

  • Format Preservation: Maintains comments, whitespace, and original formatting
  • Change Tracking: Automatic detection of modifications
  • Type Safety: Rich type conversion with comprehensive error handling
  • Path-based Access: Dot notation for nested value access
  • Multi-format Support: CONF, TOML, JSON, NOML formats
  • Schema Validation: Optional schema validation and enforcement
  • Async Support: Non-blocking file operations (with feature flag)

§Examples

use config_lib::Config;

// Load from string
let mut config = Config::from_string("port = 8080\nname = \"MyApp\"", None)?;

// Access values
let port = config.get("port").unwrap().as_integer()?;
let name = config.get("name").unwrap().as_string()?;

// Modify values
config.set("port", 9000)?;

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create a new empty configuration

Source

pub fn from_string(source: &str, format: Option<&str>) -> Result<Self>

Load configuration from a string

Source

pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>

Load configuration from a file

Source

pub fn get(&self, path: &str) -> Option<&Value>

Get a value by path

Source

pub fn get_mut(&mut self, path: &str) -> Result<&mut Value>

Get a mutable reference to a value by path

Source

pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()>

Set a value by path

Invalidates the entire resolved-path cache (writes are rare in the design envelope; a per-prefix invalidation strategy is post-1.0 backlog).

§Errors

Returns an error if:

  • The configuration was constructed with ConfigOptions::read_only
  • The path is invalid (e.g. attempts to insert into a non-table value)
Source

pub fn remove(&mut self, path: &str) -> Result<Option<Value>>

Remove a value by path

Invalidates the entire resolved-path cache on success.

§Errors

Returns an error if:

Source

pub fn contains_key(&self, path: &str) -> bool

Check if a path exists

Source

pub fn keys(&self) -> Result<Vec<&str>>

Get all keys in the configuration

Source

pub fn is_modified(&self) -> bool

Check if the configuration has been modified

Source

pub fn mark_clean(&mut self)

Mark the configuration as unmodified

Source

pub fn format(&self) -> &str

Get the configuration format

Source

pub fn file_path(&self) -> Option<&Path>

Get the file path (if loaded from file)

Source

pub fn save(&mut self) -> Result<()>

Save the configuration to its original file

Source

pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()>

Save the configuration to a specific file

Source

pub fn serialize(&self) -> Result<String>

Serialize the configuration to string format

Source

pub fn as_value(&self) -> &Value

Get the underlying Value

Source

pub fn merge(&mut self, other: &Config) -> Result<()>

Merge another configuration into this one

Invalidates the entire resolved-path cache.

§Errors

Returns an error if the configuration was constructed with ConfigOptions::read_only.

Source

pub fn key(&self, path: &str) -> ConfigValue<'_>

Get a value by path with a more ergonomic API

Source

pub fn has(&self, path: &str) -> bool

Check if configuration has any value at the given path

Source

pub fn get_or<V>(&self, path: &str, default: V) -> V
where V: TryFrom<Value> + Clone, V::Error: Debug,

Get a value with a default fallback

Source§

impl Config

Source

pub fn with_options(options: ConfigOptions) -> Self

Construct a new empty Config with the supplied ConfigOptions.

This is the explicit opt-out constructor. For the canonical defaults (caching on, writes allowed), prefer Config::new.

Source

pub fn options(&self) -> &ConfigOptions

Return the ConfigOptions currently in effect on this config.

Source

pub fn is_read_only(&self) -> bool

Returns true if this configuration was constructed read-only (see ConfigOptions::read_only).

Source

pub fn cache_stats(&self) -> CacheStats

Return a snapshot of the cache-hit / cache-miss counters.

Counters are loaded with Ordering::Relaxed — the values are statistics, not synchronisation primitives, and the hit/miss classification is best-effort under concurrent reads.

Source

pub fn get_arc(&self, path: &str) -> Option<Arc<Value>>

Resolve a dotted path to a cached Arc<Value>.

get_arc is the cache-backed thread-safe accessor introduced in v0.9.9. The first lookup of a given path walks the value tree, allocates an Arc<Value> containing a clone of the resolved node, and inserts it into the resolved-path cache. Subsequent lookups of the same path hit the cache and return a cheap refcount-bump clone of the Arc<Value>.

This is the recommended accessor for:

  • Multi-threaded reads. Arc<Value> is Send + Sync and independent of &self’s lifetime, so the value can be handed off to other threads.
  • Hot loops. Cache hits avoid the tree walk; the refcount bump is a single relaxed atomic.

The existing Config::get(&self, path) -> Option<&Value> is still the right choice for single-threaded reads that just peek and drop the borrow — no clone, no Arc bump.

The cache is invalidated wholesale on any set / remove / merge. The runtime knob ConfigOptions::cache_enabled (default true) toggles the cache layer; with it disabled, every get_arc call walks the tree and allocates a fresh Arc<Value>.

Source

pub fn clear_cache(&self)

Clear the resolved-path cache.

Idempotent; safe to call from any thread. Useful when an out-of-band actor (e.g. a hot-reload watcher) has changed the underlying value tree and the cache snapshot is now stale.

Source

pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()>

Set a default value for the given path.

Defaults are an operator-supplied fallback table consulted by Config::get_or_default when the requested path is missing from the main value tree. Defaults are independent of the read_only flag — a read-only configuration can still have its defaults table populated (defaults are deployment-time declarations, not user-supplied data).

Calls to set_default do not invalidate the cache; the cache is keyed on observed value-tree resolutions, not on defaults-table membership.

§Errors

Returns an error if the defaults-table lock has been poisoned.

Source

pub fn get_or_default(&self, path: &str) -> Option<Value>

Resolve a path against the main value tree, falling back to the defaults table when not found.

Returns None only when neither the value tree nor the defaults table contains an entry for path. The return type is owned (Option<Value>) because the defaults table sits behind an Arc<RwLock<_>> and producing a borrowed reference would require holding the lock guard across the caller’s use.

Source

pub fn make_read_only(&mut self)

Toggle this configuration into read-only mode at runtime.

Equivalent to constructing with ConfigOptions::new().read_only(true) but available as a post-construction switch. Subsequent calls to set / remove / merge return Err(Error::general("Configuration is read-only")).

The toggle is one-way by design — there is no make_writable() companion. A configuration that has been declared immutable should not become mutable again; if you need that flexibility, keep two Config handles instead.

Trait Implementations§

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

Returns the “default value” for a type. Read more
Source§

impl From<Value> for Config

Convert Value to Config

Source§

fn from(value: Value) -> Self

Converts to this type from the input type.

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