Skip to main content

Config

Struct Config 

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

High-level configuration manager with change tracking and validation

Config provides a comprehensive API for managing NOML configurations throughout their lifecycle. It maintains both the raw AST (for preserving comments and formatting) and resolved values (for fast access).

§Key Features

  • 🔄 Change Tracking - Automatic detection of modifications
  • 💾 Source Preservation - Comments and formatting maintained
  • 🎯 Path Access - Dot-notation for nested value access
  • ✅ Type Safety - Built-in conversion with error handling
  • 📁 File Management - Load, modify, and save operations
  • 🔗 Schema Validation - Ensure configuration correctness

§Lifecycle Management

use noml::Config;

// 1. Load configuration
let mut config = Config::from_file("app.noml")?;

// 2. Check if modifications are needed
if !config.contains_key("version") {
    config.set("version", "1.0.0")?;
}

// 3. Save only if modified
if config.is_modified() {
    config.save()?;
    config.mark_clean();
}

§Thread Safety

Config implements Clone for sharing across threads. Each clone maintains independent modification tracking but shares the underlying data.

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create a new empty configuration

Source

pub fn from_string(content: &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 builder() -> ConfigBuilder

Create a configuration builder

Source

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

Get a value by key path

Returns None if the key doesn’t exist.

§Example
let config = Config::from_string(r#"
[database]
host = "localhost"
port = 5432
"#)?;

let host = config.get("database.host").unwrap();
assert_eq!(host.as_string().unwrap(), "localhost");

let port = config.get("database.port").unwrap();
assert_eq!(port.as_integer().unwrap(), 5432);
Source

pub fn get_or<T>(&self, key: &str, _default: T) -> Result<&Value>
where T: Into<Value>,

Get a value by key path with a default

Returns the default value if the key doesn’t exist or cannot be converted to the target type.

§Example
let config = Config::from_string(r#"
[server]
port = 8080
"#)?;

// Key exists
let port = config.get_or("server.port", 3000)?;
assert_eq!(port.as_integer().unwrap(), 8080);
Source

pub fn get_or_insert<T>(&mut self, key: &str, default: T) -> Result<&Value>
where T: Into<Value>,

Get a value or insert a default if it doesn’t exist

Source

pub fn set<T>(&mut self, key: &str, value: T) -> Result<()>
where T: Into<Value>,

Set a value by key path

Creates intermediate tables as needed and marks the configuration as modified.

§Example
let mut config = Config::new();

config.set("database.host", "localhost")?;
config.set("database.port", 5432)?;
config.set("server.debug", true)?;

assert_eq!(config.get("database.host").unwrap().as_string().unwrap(), "localhost");
assert_eq!(config.get("database.port").unwrap().as_integer().unwrap(), 5432);
assert_eq!(config.get("server.debug").unwrap().as_bool().unwrap(), true);
Source

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

Remove a value by key path

Source

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

Check if a key exists

Source

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

Get all keys at the root level

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 source_path(&self) -> Option<&Path>

Get the source file path (if loaded from file)

Source

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

Save the configuration to its source file

Only works if the configuration was loaded from a file.

§Example
let mut config = Config::from_file("app.noml")?;
config.set("version", "2.0.0")?;
config.save()?; // Saves back to app.noml
Source

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

Save the configuration to a specific file

§Example
let config = Config::from_string("name = \"MyApp\"")?;
config.save_to_file("output.noml")?;
Source

pub fn as_value(&self) -> &Value

Get the underlying Value

Source

pub fn into_value(self) -> Value

Convert to owned Value

Source

pub fn validate_schema(&self, schema: &Schema) -> Result<()>

Validate configuration against a schema

§Example
use noml::{Config, Schema, FieldType, SchemaBuilder};

let config = Config::from_string(r#"
app_name = "MyApp"
port = 8080
debug = true
"#)?;

let schema = SchemaBuilder::new()
    .require_string("app_name")
    .require_integer("port")
    .optional_bool("debug")
    .build();

config.validate_schema(&schema)?;
Source

pub fn as_document(&self) -> &Document

Get the underlying Document

Source

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

Merge another configuration into this one

Values from the other configuration will overwrite values in this one.

Source

pub fn stats(&self) -> ConfigStats

Get configuration statistics

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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

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

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.