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
impl Config
Sourcepub fn from_string(source: &str, format: Option<&str>) -> Result<Self>
pub fn from_string(source: &str, format: Option<&str>) -> Result<Self>
Load configuration from a string
Sourcepub fn get_mut(&mut self, path: &str) -> Result<&mut Value>
pub fn get_mut(&mut self, path: &str) -> Result<&mut Value>
Get a mutable reference to a value by path
Sourcepub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()>
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)
Sourcepub fn remove(&mut self, path: &str) -> Result<Option<Value>>
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:
- The configuration was constructed with
ConfigOptions::read_only - The path is malformed
Sourcepub fn contains_key(&self, path: &str) -> bool
pub fn contains_key(&self, path: &str) -> bool
Check if a path exists
Sourcepub fn is_modified(&self) -> bool
pub fn is_modified(&self) -> bool
Check if the configuration has been modified
Sourcepub fn mark_clean(&mut self)
pub fn mark_clean(&mut self)
Mark the configuration as unmodified
Sourcepub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()>
pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()>
Save the configuration to a specific file
Sourcepub fn merge(&mut self, other: &Config) -> Result<()>
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.
Sourcepub fn key(&self, path: &str) -> ConfigValue<'_>
pub fn key(&self, path: &str) -> ConfigValue<'_>
Get a value by path with a more ergonomic API
Source§impl Config
impl Config
Sourcepub fn with_options(options: ConfigOptions) -> Self
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.
Sourcepub fn options(&self) -> &ConfigOptions
pub fn options(&self) -> &ConfigOptions
Return the ConfigOptions currently in effect on this config.
Sourcepub fn is_read_only(&self) -> bool
pub fn is_read_only(&self) -> bool
Returns true if this configuration was constructed read-only
(see ConfigOptions::read_only).
Sourcepub fn cache_stats(&self) -> CacheStats
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.
Sourcepub fn get_arc(&self, path: &str) -> Option<Arc<Value>>
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>isSend + Syncand 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>.
Sourcepub fn clear_cache(&self)
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.
Sourcepub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()>
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.
Sourcepub fn get_or_default(&self, path: &str) -> Option<Value>
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.
Sourcepub fn make_read_only(&mut self)
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.