Skip to main content

config_lib/
config.rs

1//! # High-Level Configuration Management
2//!
3//! Advanced configuration management API providing intuitive interfaces for
4//! loading, modifying, validating, and saving configurations with format preservation.
5
6use crate::error::{Error, Result};
7use crate::load::{self, LoadOptions};
8use crate::parsers;
9use crate::value::Value;
10use dashmap::DashMap;
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::{Arc, RwLock};
15
16#[cfg(feature = "schema")]
17use crate::schema::Schema;
18
19#[cfg(feature = "validation")]
20use crate::validation::{ValidationError, ValidationRuleSet};
21
22/// High-level configuration manager with format preservation and change tracking
23///
24/// [`Config`] provides a comprehensive API for managing configurations
25/// throughout their lifecycle. It maintains both the resolved values (for fast access)
26/// and format-specific preservation data (for round-trip editing).
27///
28/// ## Key Features
29///
30/// - **Format Preservation**: Maintains comments, whitespace, and original formatting
31/// - **Change Tracking**: Automatic detection of modifications
32/// - **Type Safety**: Rich type conversion with comprehensive error handling
33/// - **Path-based Access**: Dot notation for nested value access
34/// - **Multi-format Support**: CONF, TOML, JSON, NOML formats
35/// - **Schema Validation**: Optional schema validation and enforcement
36/// - **Async Support**: Non-blocking file operations (with feature flag)
37///
38/// ## Examples
39///
40/// ```rust
41/// use config_lib::Config;
42///
43/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
44/// // Load from string
45/// let mut config = Config::from_string("port = 8080\nname = \"MyApp\"", None)?;
46///
47/// // Access values
48/// let port = config.get("port").unwrap().as_integer()?;
49/// let name = config.get("name").unwrap().as_string()?;
50///
51/// // Modify values
52/// config.set("port", 9000)?;
53///
54/// # Ok(())
55/// # }
56/// ```
57#[derive(Debug)]
58pub struct Config {
59    /// The resolved configuration values
60    values: Value,
61
62    /// Path to the source file (if loaded from file)
63    file_path: Option<PathBuf>,
64
65    /// Detected or specified format
66    format: String,
67
68    /// Change tracking - has the config been modified?
69    modified: bool,
70
71    /// Opt-out behavior knobs (read-only, cache sizing, etc.).
72    /// See [`ConfigOptions`].
73    options: ConfigOptions,
74
75    /// Cache hit counter (loaded via `Ordering::Relaxed` from
76    /// [`Config::cache_stats`]). Wired in v0.9.9 — populated by
77    /// [`Config::get_arc`] when the cache layer is enabled.
78    cache_hits: AtomicU64,
79
80    /// Cache miss counter. See [`Config::cache_stats`].
81    cache_misses: AtomicU64,
82
83    /// Resolved-path cache. `DashMap` is sharded so reads hold a
84    /// short shard-local lock rather than a global lock; under
85    /// typical config workloads (read-mostly, infrequent writes)
86    /// this provides effectively-lock-free reads. Storing
87    /// `Arc<Value>` keeps clones cheap on hit (refcount bump only).
88    ///
89    /// Population is lazy — only paths actually requested through
90    /// [`Config::get_arc`] enter the cache. `set` / `remove` /
91    /// `merge` clear the cache entirely (writes are rare in the
92    /// design envelope; a per-prefix invalidation strategy is
93    /// post-1.0 backlog).
94    cache: DashMap<Box<str>, Arc<Value>>,
95
96    /// Per-path defaults table consulted by [`Config::get_or_default`]
97    /// when the requested path is missing from `values`. Wrapped in
98    /// `Arc<RwLock<_>>` so defaults can be updated independently of
99    /// the main value tree, including under `read_only` mode (defaults
100    /// are operator-provided fallbacks, not user-supplied data).
101    defaults: Arc<RwLock<BTreeMap<String, Value>>>,
102
103    /// Format-specific preservation data
104    #[cfg(feature = "noml")]
105    noml_document: Option<noml::Document>,
106
107    /// Validation rules for this configuration
108    #[cfg(feature = "validation")]
109    validation_rules: Option<ValidationRuleSet>,
110}
111
112impl Config {
113    /// Create a new empty configuration
114    pub fn new() -> Self {
115        Self {
116            values: Value::table(BTreeMap::new()),
117            file_path: None,
118            format: "conf".to_string(),
119            modified: false,
120            options: ConfigOptions::default(),
121            cache_hits: AtomicU64::new(0),
122            cache_misses: AtomicU64::new(0),
123            cache: new_cache(),
124            defaults: Arc::new(RwLock::new(BTreeMap::new())),
125            #[cfg(feature = "noml")]
126            noml_document: None,
127            #[cfg(feature = "validation")]
128            validation_rules: None,
129        }
130    }
131
132    /// Load configuration from a string
133    ///
134    /// Applies the default [`LoadOptions`]. With no format the text is
135    /// read as CONF unless it is clearly XML, JSON or INI (see
136    /// [`parsers::detect_format`]); pass the format when you know it.
137    pub fn from_string(source: &str, format: Option<&str>) -> Result<Self> {
138        Self::from_string_with(source, format, &LoadOptions::default())
139    }
140
141    /// Load configuration from a string with the given [`LoadOptions`]
142    ///
143    /// NOML includes in the text resolve against the current directory and
144    /// may only read files inside it (or the directories the options
145    /// allow).
146    ///
147    /// Since v1.4.0.
148    pub fn from_string_with(
149        source: &str,
150        format: Option<&str>,
151        options: &LoadOptions,
152    ) -> Result<Self> {
153        let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
154        let values = parsers::parse_string_with(source, Some(detected_format), None, options)?;
155        Ok(Self::from_parsed(source, detected_format, values))
156    }
157
158    /// Load configuration from a string without reading anything outside it
159    ///
160    /// The same as [`Config::from_string`] for every format except NOML
161    /// (feature `noml`): `include` and every function call (`env()`
162    /// included) are refused with [`Error::Parse`] carrying the line and
163    /// column of the first one, and the message does not quote the input.
164    /// NOML native types (`@size("10MB")`) and `${...}` references to other
165    /// values in the same document still work.
166    ///
167    /// Use it when the caller has checked the configuration file itself
168    /// (owner, mode, size, file type) before handing its text over: an
169    /// include would read a second file without those checks, and `env()`
170    /// would copy an environment variable into the configuration.
171    ///
172    /// TOML, JSON, CONF and the other formats read only the text in both
173    /// entry points (TOML refuses NOML's `include` and `env()` everywhere
174    /// since v1.3.0). With no format hint the text is never read as NOML
175    /// (since v1.4.0).
176    ///
177    /// Since v1.3.0.
178    ///
179    /// # Examples
180    ///
181    /// ```rust
182    /// use config_lib::Config;
183    ///
184    /// let config = Config::from_string_strict("port = 8080", Some("conf"))?;
185    /// assert_eq!(config.get("port").map(|v| v.as_integer()).transpose()?, Some(8080));
186    /// # Ok::<(), config_lib::Error>(())
187    /// ```
188    pub fn from_string_strict(source: &str, format: Option<&str>) -> Result<Self> {
189        Self::from_string_with(source, format, &LoadOptions::strict_defaults())
190    }
191
192    /// Build a `Config` from values already parsed out of `source`
193    fn from_parsed(source: &str, detected_format: &str, values: Value) -> Self {
194        #[cfg(not(feature = "noml"))]
195        let _ = source;
196
197        #[cfg(feature = "noml")]
198        let mut config = Self {
199            values,
200            file_path: None,
201            format: detected_format.to_string(),
202            modified: false,
203            options: ConfigOptions::default(),
204            cache_hits: AtomicU64::new(0),
205            cache_misses: AtomicU64::new(0),
206            cache: new_cache(),
207            defaults: Arc::new(RwLock::new(BTreeMap::new())),
208            noml_document: None,
209            #[cfg(feature = "validation")]
210            validation_rules: None,
211        };
212
213        #[cfg(not(feature = "noml"))]
214        let config = Self {
215            values,
216            file_path: None,
217            format: detected_format.to_string(),
218            modified: false,
219            options: ConfigOptions::default(),
220            cache_hits: AtomicU64::new(0),
221            cache_misses: AtomicU64::new(0),
222            cache: new_cache(),
223            defaults: Arc::new(RwLock::new(BTreeMap::new())),
224            #[cfg(feature = "validation")]
225            validation_rules: None,
226        };
227
228        // Store format-specific preservation data (parsed only, never
229        // resolved, so nothing outside `source` is read here)
230        #[cfg(feature = "noml")]
231        if detected_format == "noml" || detected_format == "toml" {
232            if let Ok(document) = noml::parse_string(source, None) {
233                config.noml_document = Some(document);
234            }
235        }
236
237        config
238    }
239
240    /// Load configuration from a file
241    ///
242    /// The format comes from the file extension (an unknown extension is
243    /// CONF; a file with none is detected from its text). Applies the
244    /// default [`LoadOptions`]: the file must be a regular file of at most
245    /// 16 MiB, and NOML includes may only read files inside the file's own
246    /// directory.
247    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
248        Self::from_file_with(path, &LoadOptions::default())
249    }
250
251    /// Load configuration from a file with strict NOML
252    ///
253    /// The file counterpart of [`Config::from_string_strict`]: a NOML file
254    /// may not use `include` or call `env()`. Other formats load as with
255    /// [`Config::from_file`].
256    ///
257    /// Since v1.4.0.
258    pub fn from_file_strict<P: AsRef<Path>>(path: P) -> Result<Self> {
259        Self::from_file_with(path, &LoadOptions::strict_defaults())
260    }
261
262    /// Load configuration from a file with the given [`LoadOptions`]
263    ///
264    /// Since v1.4.0.
265    pub fn from_file_with<P: AsRef<Path>>(path: P, options: &LoadOptions) -> Result<Self> {
266        let path = path.as_ref();
267        let content = load::read_file(path, options.max_file_size)?;
268        Self::from_file_content(path, &content, options)
269    }
270
271    fn from_file_content(path: &Path, content: &str, options: &LoadOptions) -> Result<Self> {
272        let format = parsers::file_format(path, content);
273        let values = parsers::parse_string_with(content, Some(format), Some(path), options)?;
274        let mut config = Self::from_parsed(content, format, values);
275        config.file_path = Some(path.to_path_buf());
276        Ok(config)
277    }
278
279    /// Async version of from_file
280    #[cfg(feature = "async")]
281    pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
282        let path = path.as_ref();
283        let options = LoadOptions::default();
284        let content = load::read_file_async(path, options.max_file_size).await?;
285        Self::from_file_content(path, &content, &options)
286    }
287
288    /// Get a value by path
289    pub fn get(&self, path: &str) -> Option<&Value> {
290        self.values.get(path)
291    }
292
293    /// Get a mutable reference to a value by path
294    ///
295    /// Counts as a change: refused on a read-only configuration (since
296    /// v1.4.0), and clears the resolved-path cache so [`Config::get_arc`]
297    /// does not return the old value.
298    pub fn get_mut(&mut self, path: &str) -> Result<&mut Value> {
299        self.ensure_writable()?;
300        let value = self.values.get_mut_nested(path)?;
301        self.modified = true;
302        self.cache.clear();
303        Ok(value)
304    }
305
306    /// Set a value by path
307    ///
308    /// Invalidates the entire resolved-path cache (writes are rare in
309    /// the design envelope; a per-prefix invalidation strategy is
310    /// post-1.0 backlog).
311    ///
312    /// # Errors
313    ///
314    /// Returns an error if:
315    /// - The configuration was constructed with [`ConfigOptions::read_only`]
316    /// - The path is invalid (e.g. attempts to insert into a non-table value)
317    pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()> {
318        self.ensure_writable()?;
319        self.values.set_nested(path, value.into())?;
320        self.modified = true;
321        self.cache.clear();
322        Ok(())
323    }
324
325    /// Remove a value by path
326    ///
327    /// Invalidates the entire resolved-path cache on success.
328    ///
329    /// # Errors
330    ///
331    /// Returns an error if:
332    /// - The configuration was constructed with [`ConfigOptions::read_only`]
333    /// - The path is malformed
334    pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
335        self.ensure_writable()?;
336        let result = self.values.remove(path)?;
337        if result.is_some() {
338            self.modified = true;
339            self.cache.clear();
340        }
341        Ok(result)
342    }
343
344    /// Check if a path exists
345    pub fn contains_key(&self, path: &str) -> bool {
346        self.values.contains_key(path)
347    }
348
349    /// Get all keys in the configuration
350    pub fn keys(&self) -> Result<Vec<&str>> {
351        self.values.keys()
352    }
353
354    /// Check if the configuration has been modified
355    pub fn is_modified(&self) -> bool {
356        self.modified
357    }
358
359    /// Mark the configuration as unmodified
360    pub fn mark_clean(&mut self) {
361        self.modified = false;
362    }
363
364    /// Get the configuration format
365    pub fn format(&self) -> &str {
366        &self.format
367    }
368
369    /// Get the file path (if loaded from file)
370    pub fn file_path(&self) -> Option<&Path> {
371        self.file_path.as_deref()
372    }
373
374    /// Save the configuration to its original file
375    pub fn save(&mut self) -> Result<()> {
376        match &self.file_path {
377            Some(path) => {
378                self.save_to_file(path.clone())?;
379                self.modified = false;
380                Ok(())
381            }
382            None => Err(Error::internal(
383                "Cannot save configuration that wasn't loaded from a file",
384            )),
385        }
386    }
387
388    /// Save the configuration to a specific file
389    ///
390    /// Since v1.4.0 the file is replaced atomically: the text is written to
391    /// a temporary file in the same directory, flushed to disk, and renamed
392    /// over the target, so a reader (a hot-reload watcher, for one) never
393    /// sees a half-written file. The new file keeps the old one's
394    /// permissions. When `path` is a symbolic link, the file it points to is
395    /// replaced and the link is kept.
396    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
397        let serialized = self.serialize()?;
398        atomic_write(path.as_ref(), serialized.as_bytes())
399    }
400
401    /// Async version of save
402    #[cfg(feature = "async")]
403    pub async fn save_async(&mut self) -> Result<()> {
404        match &self.file_path {
405            Some(path) => {
406                self.save_to_file_async(path.clone()).await?;
407                self.modified = false;
408                Ok(())
409            }
410            None => Err(Error::internal(
411                "Cannot save configuration that wasn't loaded from a file",
412            )),
413        }
414    }
415
416    /// Async version of save_to_file
417    #[cfg(feature = "async")]
418    pub async fn save_to_file_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
419        let serialized = self.serialize()?;
420        let path = path.as_ref().to_path_buf();
421        tokio::task::spawn_blocking(move || atomic_write(&path, serialized.as_bytes()))
422            .await
423            .map_err(|_| Error::internal("save task failed"))?
424    }
425
426    /// Serialize the configuration to string format
427    pub fn serialize(&self) -> Result<String> {
428        match self.format.as_str() {
429            "json" => {
430                #[cfg(any(feature = "json", feature = "jsonx"))]
431                return crate::parsers::json_parser::serialize(&self.values);
432                #[cfg(not(any(feature = "json", feature = "jsonx")))]
433                return Err(Error::feature_not_enabled("json"));
434            }
435            "toml" => {
436                #[cfg(feature = "toml")]
437                {
438                    // The preserved document keeps comments and formatting,
439                    // but only matches the values until they are changed
440                    #[cfg(feature = "noml")]
441                    if !self.modified {
442                        if let Some(ref document) = self.noml_document {
443                            return Ok(noml::serialize_document(document)?);
444                        }
445                    }
446                    self.serialize_as_toml(false)
447                }
448                #[cfg(not(feature = "toml"))]
449                return Err(Error::feature_not_enabled("toml"));
450            }
451            "noml" => {
452                #[cfg(feature = "noml")]
453                {
454                    if !self.modified {
455                        if let Some(ref document) = self.noml_document {
456                            return Ok(noml::serialize_document(document)?);
457                        }
458                    }
459                    self.serialize_as_toml(true)
460                }
461                #[cfg(not(feature = "noml"))]
462                return Err(Error::feature_not_enabled("noml"));
463            }
464            "conf" => self.serialize_as_conf(),
465            _ => Err(Error::unknown_format(&self.format)),
466        }
467    }
468
469    /// Serialize as CONF format
470    ///
471    /// The text reads back to the same values (since v1.4.0): strings are
472    /// always quoted and escaped, arrays are written as `[a, b]`, and a
473    /// nested table becomes a `[parent.child]` section. Comments and the
474    /// original layout are not kept, and an empty table is not written.
475    /// Values CONF cannot hold (NaN and infinite floats, tables inside
476    /// arrays, keys with characters outside letters, digits, `_`, `-` and
477    /// `.`) are an error rather than text that reads back differently.
478    fn serialize_as_conf(&self) -> Result<String> {
479        let mut output = String::new();
480        if let Value::Table(table) = &self.values {
481            conf_writer::write_table(&mut output, table, &mut Vec::new())?;
482        }
483        Ok(output)
484    }
485
486    /// Serialize the values as TOML text.
487    ///
488    /// Writes the current values as TOML. With `noml` set, a literal `${` in
489    /// a string is written as `$${` so NOML does not treat it as
490    /// interpolation when the file is read back. TOML has no null, so a null
491    /// value is an error unless writing NOML.
492    #[cfg(any(feature = "toml", feature = "noml"))]
493    fn serialize_as_toml(&self, noml: bool) -> Result<String> {
494        let mut out = String::new();
495        if let Value::Table(table) = &self.values {
496            toml_writer::write_table(&mut out, table, &mut Vec::new(), noml)?;
497        }
498        Ok(out)
499    }
500
501    /// Validate the configuration against a schema
502    #[cfg(feature = "schema")]
503    pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
504        schema.validate(&self.values)
505    }
506
507    /// Get the underlying Value
508    pub fn as_value(&self) -> &Value {
509        &self.values
510    }
511
512    /// Merge another configuration into this one
513    ///
514    /// Invalidates the entire resolved-path cache.
515    ///
516    /// # Errors
517    ///
518    /// Returns an error if the configuration was constructed with
519    /// [`ConfigOptions::read_only`].
520    pub fn merge(&mut self, other: &Config) -> Result<()> {
521        self.ensure_writable()?;
522        self.merge_value(&other.values)?;
523        self.modified = true;
524        self.cache.clear();
525        Ok(())
526    }
527
528    /// Helper to merge values recursively
529    fn merge_value(&mut self, other: &Value) -> Result<()> {
530        merge_in_place(&mut self.values, other);
531        Ok(())
532    }
533
534    /// Take over the runtime state of `old`: options (read-only mode and
535    /// the cache knobs), the shared defaults table, and the validation
536    /// rules. Used by hot reload so that a reload changes only the values.
537    pub(crate) fn inherit_runtime_state(&mut self, old: &mut Config) {
538        self.options = old.options.clone();
539        self.defaults = Arc::clone(&old.defaults);
540        #[cfg(feature = "validation")]
541        {
542            self.validation_rules = old.validation_rules.take();
543        }
544    }
545
546    /// Give the validation rules back to `old` (a reload was refused)
547    #[cfg(feature = "validation")]
548    pub(crate) fn return_validation_rules(&mut self, old: &mut Config) {
549        old.validation_rules = self.validation_rules.take();
550    }
551
552    /// True when the configuration holds no values at all
553    pub(crate) fn is_empty(&self) -> bool {
554        match &self.values {
555            Value::Table(table) => table.is_empty(),
556            Value::Null => true,
557            _ => false,
558        }
559    }
560
561    // =====================================================================
562    // Validation Methods (Feature-gated)
563    // =====================================================================
564
565    // --- CONVENIENCE METHODS & BUILDER PATTERN ---
566
567    /// Get a value by path with a more ergonomic API
568    pub fn key(&self, path: &str) -> ConfigValue<'_> {
569        ConfigValue::new(self.get(path))
570    }
571
572    /// Check if configuration has any value at the given path
573    pub fn has(&self, path: &str) -> bool {
574        self.contains_key(path)
575    }
576
577    /// Get a value converted to `V`, or `default` when the path is missing
578    /// or the value does not convert.
579    ///
580    /// `V` can be `bool`, `String`, `f64`, any integer type from `i8`/`u8`
581    /// to `i64`/`u64`, `isize`, `usize`, or `Value` itself. Integer reads
582    /// are range-checked, so `70000` read as `u16` returns the default. See
583    /// the `TryFrom<Value>` impls on [`Value`] for the conversion rules.
584    ///
585    /// # Examples
586    ///
587    /// ```rust
588    /// use config_lib::Config;
589    ///
590    /// let config = Config::from_string(
591    ///     r#"
592    /// [server]
593    /// port = 8080
594    /// host = "0.0.0.0"
595    /// "#,
596    ///     Some("conf"),
597    /// )?;
598    ///
599    /// let port: u16 = config.get_or("server.port", 3000);
600    /// let host: String = config.get_or("server.host", "localhost".to_string());
601    /// let tls = config.get_or("server.tls", false); // missing, so the default
602    ///
603    /// assert_eq!(port, 8080);
604    /// assert_eq!(host, "0.0.0.0");
605    /// assert!(!tls);
606    /// # Ok::<(), config_lib::Error>(())
607    /// ```
608    pub fn get_or<V>(&self, path: &str, default: V) -> V
609    where
610        V: TryFrom<Value> + Clone,
611        V::Error: std::fmt::Debug,
612    {
613        self.get(path)
614            .and_then(|v| V::try_from(v.clone()).ok())
615            .unwrap_or(default)
616    }
617
618    // --- VALIDATION SUPPORT ---
619
620    /// Set validation rules for this configuration
621    #[cfg(feature = "validation")]
622    pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
623        self.validation_rules = Some(rules);
624    }
625
626    /// Validate the current configuration against all registered rules
627    ///
628    /// Every value is checked, at every level, with its full dotted path
629    /// (`server.port`) as the path. Before v1.4.0 only top-level values
630    /// were checked, so keys inside sections were never validated.
631    #[cfg(feature = "validation")]
632    pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
633        fn walk(
634            rules: &mut ValidationRuleSet,
635            table: &BTreeMap<String, Value>,
636            prefix: &str,
637            errors: &mut Vec<ValidationError>,
638        ) {
639            for (key, value) in table {
640                let path = if prefix.is_empty() {
641                    key.clone()
642                } else {
643                    format!("{prefix}.{key}")
644                };
645                errors.extend(rules.validate(&path, value));
646                if let Value::Table(inner) = value {
647                    walk(rules, inner, &path, errors);
648                }
649            }
650        }
651
652        match &mut self.validation_rules {
653            Some(rules) => {
654                if let Value::Table(table) = &self.values {
655                    let mut errors = Vec::new();
656                    walk(rules, table, "", &mut errors);
657                    Ok(errors)
658                } else {
659                    Err(Error::validation(
660                        "Configuration root must be a table for validation",
661                    ))
662                }
663            }
664            None => Ok(Vec::new()), // No rules = no errors
665        }
666    }
667
668    /// Validate and return only critical errors
669    #[cfg(feature = "validation")]
670    pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
671        let all_errors = self.validate()?;
672        Ok(all_errors
673            .into_iter()
674            .filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
675            .collect())
676    }
677
678    /// Check if configuration is valid (has no critical errors)
679    #[cfg(feature = "validation")]
680    pub fn is_valid(&mut self) -> Result<bool> {
681        let critical_errors = self.validate_critical_only()?;
682        Ok(critical_errors.is_empty())
683    }
684
685    /// Validate a specific value at a path
686    #[cfg(feature = "validation")]
687    pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
688        // Get the value first to avoid borrowing conflicts, clone to own it
689        let value = self
690            .get(path)
691            .ok_or_else(|| Error::key_not_found(path))?
692            .clone();
693
694        match &mut self.validation_rules {
695            Some(rules) => Ok(rules.validate(path, &value)),
696            None => Ok(Vec::new()),
697        }
698    }
699}
700
701impl Default for Config {
702    fn default() -> Self {
703        Self::new()
704    }
705}
706
707// =========================================================================
708// ConfigOptions — opt-out behavior knobs (foundation for v0.9.5)
709// =========================================================================
710
711/// Opt-out behavior knobs for [`Config`].
712///
713/// `ConfigOptions` carries the small set of toggles that should not be
714/// enabled by default: making a `Config` read-only, sizing the cache,
715/// and so on. The struct is `#[non_exhaustive]` so v0.9.x can add new
716/// knobs without breaking SemVer. Users construct it via
717/// [`ConfigOptions::new`] or [`ConfigOptions::default`] and apply
718/// individual toggles through the consuming builder methods.
719///
720/// The field set lays the groundwork for the lock-free caching work
721/// landing in v0.9.5. In v0.9.4 the only knob that has runtime effect
722/// is [`ConfigOptions::read_only`]; the cache-related knobs are
723/// accepted today so that the public API surface does not change
724/// again when v0.9.5 switches the cache on.
725///
726/// # Examples
727///
728/// ```rust
729/// use config_lib::{Config, ConfigOptions};
730///
731/// // Default options — caching on, writes allowed.
732/// let _cfg = Config::with_options(ConfigOptions::default());
733///
734/// // Read-only configuration for a hot path that must never be mutated.
735/// let opts = ConfigOptions::new().read_only(true);
736/// let _cfg = Config::with_options(opts);
737/// ```
738#[derive(Debug, Clone)]
739#[non_exhaustive]
740pub struct ConfigOptions {
741    /// Reject every `set` / `remove` / `merge` call with
742    /// [`Error::general`] instead of mutating. Useful for once-loaded
743    /// configurations that must never change at runtime.
744    pub read_only: bool,
745
746    /// Whether the internal caching layer is active. **Reserved** — the
747    /// caching layer ships in v0.9.5; in v0.9.4 this field is accepted
748    /// for forward compatibility but does not yet change runtime
749    /// behavior (every `get` already hits an in-memory `Value`).
750    pub cache_enabled: bool,
751
752    /// Maximum number of resolved-key entries the cache will hold
753    /// before evicting. **Reserved for v0.9.5.**
754    pub cache_capacity: usize,
755}
756
757impl Default for ConfigOptions {
758    /// The canonical options for the Hive DB use case:
759    /// caching enabled, writes allowed, capacity tuned for typical
760    /// server config size.
761    fn default() -> Self {
762        Self {
763            read_only: false,
764            cache_enabled: true,
765            cache_capacity: 1024,
766        }
767    }
768}
769
770impl ConfigOptions {
771    /// Construct a `ConfigOptions` with default values
772    /// ([`ConfigOptions::default`]).
773    pub fn new() -> Self {
774        Self::default()
775    }
776
777    /// Set the read-only flag. See [`ConfigOptions::read_only`].
778    pub fn read_only(mut self, read_only: bool) -> Self {
779        self.read_only = read_only;
780        self
781    }
782
783    /// Toggle the caching layer. **Reserved for v0.9.5** — currently
784    /// a no-op at runtime; the setter exists so call-sites compile
785    /// against the same shape they will use after the cache lands.
786    pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
787        self.cache_enabled = cache_enabled;
788        self
789    }
790
791    /// Set the cache capacity. **Reserved for v0.9.5** — see
792    /// [`ConfigOptions::cache_enabled`].
793    pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
794        self.cache_capacity = cache_capacity;
795        self
796    }
797}
798
799impl Config {
800    /// Construct a new empty [`Config`] with the supplied
801    /// [`ConfigOptions`].
802    ///
803    /// This is the explicit opt-out constructor. For the canonical
804    /// defaults (caching on, writes allowed), prefer [`Config::new`].
805    pub fn with_options(options: ConfigOptions) -> Self {
806        let mut config = Self::new();
807        config.options = options;
808        config
809    }
810
811    /// Return the [`ConfigOptions`] currently in effect on this config.
812    pub fn options(&self) -> &ConfigOptions {
813        &self.options
814    }
815
816    /// Returns `true` if this configuration was constructed read-only
817    /// (see [`ConfigOptions::read_only`]).
818    pub fn is_read_only(&self) -> bool {
819        self.options.read_only
820    }
821
822    /// Helper used by mutating methods to short-circuit when the
823    /// configuration is in read-only mode.
824    fn ensure_writable(&self) -> Result<()> {
825        if self.options.read_only {
826            Err(Error::general("Configuration is read-only"))
827        } else {
828            Ok(())
829        }
830    }
831
832    /// Return a snapshot of the cache-hit / cache-miss counters.
833    ///
834    /// Counters are loaded with `Ordering::Relaxed` — the values are
835    /// statistics, not synchronisation primitives, and the hit/miss
836    /// classification is best-effort under concurrent reads.
837    pub fn cache_stats(&self) -> CacheStats {
838        let hits = self.cache_hits.load(Ordering::Relaxed);
839        let misses = self.cache_misses.load(Ordering::Relaxed);
840        let total = hits.saturating_add(misses);
841        let hit_ratio = if total == 0 {
842            0.0
843        } else {
844            hits as f64 / total as f64
845        };
846        CacheStats {
847            hits,
848            misses,
849            hit_ratio,
850        }
851    }
852
853    /// Resolve a dotted path to a cached `Arc<Value>`.
854    ///
855    /// `get_arc` is the cache-backed thread-safe accessor introduced
856    /// in v0.9.9. The first lookup of a given path walks the value
857    /// tree, allocates an `Arc<Value>` containing a clone of the
858    /// resolved node, and inserts it into the resolved-path cache.
859    /// Subsequent lookups of the same path hit the cache and return
860    /// a cheap refcount-bump clone of the `Arc<Value>`.
861    ///
862    /// This is the recommended accessor for:
863    ///
864    /// - **Multi-threaded reads.** `Arc<Value>` is `Send + Sync` and
865    ///   independent of `&self`'s lifetime, so the value can be
866    ///   handed off to other threads.
867    /// - **Hot loops.** Cache hits avoid the tree walk; the
868    ///   refcount bump is a single relaxed atomic.
869    ///
870    /// The existing `Config::get(&self, path) -> Option<&Value>` is
871    /// still the right choice for single-threaded reads that just
872    /// peek and drop the borrow — no clone, no Arc bump.
873    ///
874    /// The cache is invalidated wholesale on any `set` / `remove` /
875    /// `merge`. The runtime knob [`ConfigOptions::cache_enabled`]
876    /// (default `true`) toggles the cache layer; with it disabled,
877    /// every `get_arc` call walks the tree and allocates a fresh
878    /// `Arc<Value>`.
879    pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
880        if self.options.cache_enabled {
881            if let Some(entry) = self.cache.get(path) {
882                self.cache_hits.fetch_add(1, Ordering::Relaxed);
883                return Some(Arc::clone(entry.value()));
884            }
885            self.cache_misses.fetch_add(1, Ordering::Relaxed);
886            let resolved = self.values.get(path)?.clone();
887            let arc = Arc::new(resolved);
888            self.cache.insert(path.into(), Arc::clone(&arc));
889            Some(arc)
890        } else {
891            self.cache_misses.fetch_add(1, Ordering::Relaxed);
892            Some(Arc::new(self.values.get(path)?.clone()))
893        }
894    }
895
896    /// Clear the resolved-path cache.
897    ///
898    /// Idempotent; safe to call from any thread. Useful when an
899    /// out-of-band actor (e.g. a hot-reload watcher) has changed
900    /// the underlying value tree and the cache snapshot is now stale.
901    pub fn clear_cache(&self) {
902        self.cache.clear();
903    }
904
905    /// Set a default value for the given path.
906    ///
907    /// Defaults are an operator-supplied fallback table consulted by
908    /// [`Config::get_or_default`] when the requested path is missing
909    /// from the main value tree. Defaults are independent of the
910    /// `read_only` flag — a read-only configuration can still have
911    /// its defaults table populated (defaults are deployment-time
912    /// declarations, not user-supplied data).
913    ///
914    /// Calls to `set_default` do **not** invalidate the cache; the
915    /// cache is keyed on observed value-tree resolutions, not on
916    /// defaults-table membership.
917    ///
918    /// # Errors
919    ///
920    /// Returns an error if the defaults-table lock has been poisoned.
921    pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
922        let mut defaults = self
923            .defaults
924            .write()
925            .map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
926        defaults.insert(path.to_string(), value.into());
927        Ok(())
928    }
929
930    /// Resolve a path against the main value tree, falling back to the
931    /// defaults table when not found.
932    ///
933    /// Returns `None` only when neither the value tree nor the defaults
934    /// table contains an entry for `path`. The return type is owned
935    /// (`Option<Value>`) because the defaults table sits behind an
936    /// `Arc<RwLock<_>>` and producing a borrowed reference would
937    /// require holding the lock guard across the caller's use.
938    pub fn get_or_default(&self, path: &str) -> Option<Value> {
939        if let Some(v) = self.values.get(path) {
940            return Some(v.clone());
941        }
942        let defaults = self.defaults.read().ok()?;
943        defaults.get(path).cloned()
944    }
945
946    /// Toggle this configuration into read-only mode at runtime.
947    ///
948    /// Equivalent to constructing with
949    /// `ConfigOptions::new().read_only(true)` but available as a
950    /// post-construction switch. Subsequent calls to `set` / `remove`
951    /// / `merge` return `Err(Error::general("Configuration is
952    /// read-only"))`.
953    ///
954    /// The toggle is **one-way** by design — there is no
955    /// `make_writable()` companion. A configuration that has been
956    /// declared immutable should not become mutable again; if you
957    /// need that flexibility, keep two `Config` handles instead.
958    pub fn make_read_only(&mut self) {
959        self.options.read_only = true;
960    }
961}
962
963// =========================================================================
964// CacheStats — read-only snapshot of cache performance counters
965// =========================================================================
966
967/// Snapshot of a [`Config`]'s cache-hit / cache-miss counters.
968///
969/// Returned by [`Config::cache_stats`]. The struct is `#[non_exhaustive]`
970/// so the v1.x SemVer contract can add new counter fields (e.g.
971/// `evictions`, `insertions`, per-shard breakdowns) in MINOR releases
972/// without breaking user code.
973///
974/// # Stability note for v0.9.5
975///
976/// In v0.9.5 every `CacheStats` returned by [`Config::cache_stats`]
977/// has `hits = 0`, `misses = 0`, `hit_ratio = 0.0`. The lock-free
978/// cache layer that populates these counters lands in a follow-up
979/// v0.9.5 implementation release. The struct is shipping now so the
980/// API surface is locked in ahead of the implementation.
981///
982/// # Examples
983///
984/// ```rust
985/// use config_lib::Config;
986///
987/// let cfg = Config::new();
988/// let stats = cfg.cache_stats();
989/// assert_eq!(stats.hits, 0);
990/// assert_eq!(stats.misses, 0);
991/// assert_eq!(stats.hit_ratio, 0.0);
992/// ```
993#[derive(Debug, Clone, Copy)]
994#[non_exhaustive]
995pub struct CacheStats {
996    /// Number of cache lookups that resolved to a cached value.
997    pub hits: u64,
998    /// Number of cache lookups that did not find a cached value and
999    /// fell through to the canonical storage.
1000    pub misses: u64,
1001    /// `hits / (hits + misses)` as an f64 in `[0.0, 1.0]`. Returns
1002    /// `0.0` when no lookups have happened yet.
1003    pub hit_ratio: f64,
1004}
1005
1006/// Ergonomic wrapper for accessing configuration values
1007pub struct ConfigValue<'a> {
1008    value: Option<&'a Value>,
1009}
1010
1011impl<'a> ConfigValue<'a> {
1012    fn new(value: Option<&'a Value>) -> Self {
1013        Self { value }
1014    }
1015
1016    /// Get as string with default fallback
1017    pub fn as_string(&self) -> Result<String> {
1018        match self.value {
1019            Some(v) => v.as_string().map(|s| s.to_string()),
1020            None => Err(Error::key_not_found("value not found")),
1021        }
1022    }
1023
1024    /// Get as string with custom default
1025    pub fn as_string_or(&self, default: &str) -> String {
1026        self.value
1027            .and_then(|v| v.as_string().ok())
1028            .map(|s| s.to_string())
1029            .unwrap_or_else(|| default.to_string())
1030    }
1031
1032    /// Get as integer with default fallback
1033    pub fn as_integer(&self) -> Result<i64> {
1034        match self.value {
1035            Some(v) => v.as_integer(),
1036            None => Err(Error::key_not_found("value not found")),
1037        }
1038    }
1039
1040    /// Get as integer with custom default
1041    pub fn as_integer_or(&self, default: i64) -> i64 {
1042        self.value
1043            .and_then(|v| v.as_integer().ok())
1044            .unwrap_or(default)
1045    }
1046
1047    /// Get as boolean with default fallback
1048    pub fn as_bool(&self) -> Result<bool> {
1049        match self.value {
1050            Some(v) => v.as_bool(),
1051            None => Err(Error::key_not_found("value not found")),
1052        }
1053    }
1054
1055    /// Get as boolean with custom default
1056    pub fn as_bool_or(&self, default: bool) -> bool {
1057        self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
1058    }
1059
1060    /// Check if the value exists
1061    pub fn exists(&self) -> bool {
1062        self.value.is_some()
1063    }
1064
1065    /// Get the underlying Value reference if it exists
1066    pub fn value(&self) -> Option<&'a Value> {
1067        self.value
1068    }
1069}
1070
1071/// Builder pattern for Config creation
1072pub struct ConfigBuilder {
1073    format: Option<String>,
1074    load: LoadOptions,
1075    #[cfg(feature = "validation")]
1076    validation_rules: Option<ValidationRuleSet>,
1077}
1078
1079impl ConfigBuilder {
1080    /// Create a new ConfigBuilder
1081    pub fn new() -> Self {
1082        Self {
1083            format: None,
1084            load: LoadOptions::default(),
1085            #[cfg(feature = "validation")]
1086            validation_rules: None,
1087        }
1088    }
1089
1090    /// Set the [`LoadOptions`] the build reads with (limits, include
1091    /// policy, strict NOML). Since v1.4.0.
1092    pub fn load_options(mut self, options: LoadOptions) -> Self {
1093        self.load = options;
1094        self
1095    }
1096
1097    /// Set the configuration format
1098    pub fn format<S: Into<String>>(mut self, format: S) -> Self {
1099        self.format = Some(format.into());
1100        self
1101    }
1102
1103    /// Set validation rules
1104    #[cfg(feature = "validation")]
1105    pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
1106        self.validation_rules = Some(rules);
1107        self
1108    }
1109
1110    /// Build Config from string
1111    pub fn from_string(self, source: &str) -> Result<Config> {
1112        #[cfg(feature = "validation")]
1113        let mut config = Config::from_string_with(source, self.format.as_deref(), &self.load)?;
1114        #[cfg(not(feature = "validation"))]
1115        let config = Config::from_string_with(source, self.format.as_deref(), &self.load)?;
1116
1117        #[cfg(feature = "validation")]
1118        if let Some(rules) = self.validation_rules {
1119            config.set_validation_rules(rules);
1120        }
1121
1122        Ok(config)
1123    }
1124
1125    /// Build Config from file
1126    pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
1127        #[cfg(feature = "validation")]
1128        let mut config = Config::from_file_with(path, &self.load)?;
1129        #[cfg(not(feature = "validation"))]
1130        let config = Config::from_file_with(path, &self.load)?;
1131
1132        #[cfg(feature = "validation")]
1133        if let Some(rules) = self.validation_rules {
1134            config.set_validation_rules(rules);
1135        }
1136
1137        Ok(config)
1138    }
1139}
1140
1141impl Default for ConfigBuilder {
1142    fn default() -> Self {
1143        Self::new()
1144    }
1145}
1146
1147/// Convert Value to Config
1148impl From<Value> for Config {
1149    fn from(value: Value) -> Self {
1150        Self {
1151            values: value,
1152            file_path: None,
1153            format: "conf".to_string(),
1154            modified: false,
1155            options: ConfigOptions::default(),
1156            cache_hits: AtomicU64::new(0),
1157            cache_misses: AtomicU64::new(0),
1158            cache: new_cache(),
1159            defaults: Arc::new(RwLock::new(BTreeMap::new())),
1160            #[cfg(feature = "noml")]
1161            noml_document: None,
1162            #[cfg(feature = "validation")]
1163            validation_rules: None,
1164        }
1165    }
1166}
1167
1168/// Merge `other` into `target`: tables merge key by key at every level,
1169/// anything else replaces. Works in place, with no temporary `Config`.
1170fn merge_in_place(target: &mut Value, other: &Value) {
1171    match (target, other) {
1172        (Value::Table(target_table), Value::Table(other_table)) => {
1173            for (key, other_value) in other_table {
1174                match target_table.get_mut(key) {
1175                    Some(existing) if existing.is_table() && other_value.is_table() => {
1176                        merge_in_place(existing, other_value);
1177                    }
1178                    Some(existing) => *existing = other_value.clone(),
1179                    None => {
1180                        target_table.insert(key.clone(), other_value.clone());
1181                    }
1182                }
1183            }
1184        }
1185        (target, other) => *target = other.clone(),
1186    }
1187}
1188
1189/// The resolved-path cache with a fixed, small shard count.
1190///
1191/// `DashMap::new` sizes its shard array from the CPU count (about 16 KiB on
1192/// a 32-thread host) before holding a single key; eight shards keep an
1193/// empty `Config` small at configuration-scale load.
1194fn new_cache() -> DashMap<Box<str>, Arc<Value>> {
1195    DashMap::with_shard_amount(8)
1196}
1197
1198/// Replace `path` with `bytes` so that no reader sees a partial file.
1199///
1200/// Writes a temporary file next to the target, flushes it to disk, copies
1201/// the old file's permissions, and renames it over the target. A symbolic
1202/// link is followed, so the file it points to is replaced.
1203fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
1204    use std::io::Write;
1205    use std::sync::atomic::AtomicUsize;
1206    static COUNTER: AtomicUsize = AtomicUsize::new(0);
1207
1208    let io_err = |e| Error::io(path.display().to_string(), e);
1209    let target = match std::fs::symlink_metadata(path) {
1210        Ok(meta) if meta.file_type().is_symlink() => std::fs::canonicalize(path).map_err(io_err)?,
1211        _ => path.to_path_buf(),
1212    };
1213    let dir = match target.parent() {
1214        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
1215        _ => PathBuf::from("."),
1216    };
1217    let name = target
1218        .file_name()
1219        .map(|n| n.to_string_lossy().into_owned())
1220        .unwrap_or_else(|| "config".to_string());
1221    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1222    let tmp = dir.join(format!(".{name}.{}.{n}.tmp", std::process::id()));
1223
1224    let result = (|| -> std::io::Result<()> {
1225        let mut file = std::fs::OpenOptions::new()
1226            .write(true)
1227            .create_new(true)
1228            .open(&tmp)?;
1229        if let Ok(meta) = std::fs::metadata(&target) {
1230            file.set_permissions(meta.permissions())?;
1231        }
1232        file.write_all(bytes)?;
1233        file.sync_all()?;
1234        drop(file);
1235        std::fs::rename(&tmp, &target)
1236    })();
1237    if result.is_err() {
1238        let _ = std::fs::remove_file(&tmp);
1239    }
1240    result.map_err(io_err)
1241}
1242
1243/// CONF text output that reads back to the same values
1244mod conf_writer {
1245    use crate::error::{Error, Result};
1246    use crate::value::Value;
1247    use std::collections::BTreeMap;
1248    use std::fmt::Write;
1249
1250    fn key_ok(key: &str) -> bool {
1251        !key.is_empty()
1252            && key
1253                .chars()
1254                .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
1255    }
1256
1257    fn bad_key() -> Error {
1258        Error::serialize("a key holds characters CONF cannot write")
1259    }
1260
1261    /// Plain keys first, then one `[a.b]` section per nested table
1262    pub(super) fn write_table(
1263        out: &mut String,
1264        table: &BTreeMap<String, Value>,
1265        path: &mut Vec<String>,
1266    ) -> Result<()> {
1267        let has_plain = table.values().any(|v| !v.is_table());
1268        if !path.is_empty() && (has_plain || table.is_empty()) {
1269            if !out.is_empty() {
1270                out.push('\n');
1271            }
1272            out.push('[');
1273            out.push_str(&path.join("."));
1274            out.push_str("]\n");
1275        }
1276        for (key, value) in table {
1277            if value.is_table() {
1278                continue;
1279            }
1280            if !key_ok(key) {
1281                return Err(bad_key());
1282            }
1283            out.push_str(key);
1284            out.push_str(" = ");
1285            write_value(out, value)?;
1286            out.push('\n');
1287        }
1288        for (key, value) in table {
1289            if let Value::Table(inner) = value {
1290                // A section name is split at dots when read back
1291                if !key_ok(key) || key.contains('.') {
1292                    return Err(bad_key());
1293                }
1294                path.push(key.clone());
1295                write_table(out, inner, path)?;
1296                path.pop();
1297            }
1298        }
1299        Ok(())
1300    }
1301
1302    fn write_value(out: &mut String, value: &Value) -> Result<()> {
1303        match value {
1304            Value::Null => out.push_str("null"),
1305            Value::Bool(b) => {
1306                let _ = write!(out, "{b}");
1307            }
1308            Value::Integer(i) => {
1309                let _ = write!(out, "{i}");
1310            }
1311            Value::Float(f) if f.is_finite() => {
1312                // Debug keeps a '.' or an exponent, so it reads back as a float
1313                let _ = write!(out, "{f:?}");
1314            }
1315            Value::Float(_) => {
1316                return Err(Error::serialize("CONF cannot hold NaN or infinity"));
1317            }
1318            Value::String(s) => write_string(out, s),
1319            Value::Array(items) => {
1320                out.push('[');
1321                for (i, item) in items.iter().enumerate() {
1322                    if i > 0 {
1323                        out.push_str(", ");
1324                    }
1325                    if item.is_table() {
1326                        return Err(Error::serialize("CONF cannot hold a table in an array"));
1327                    }
1328                    write_value(out, item)?;
1329                }
1330                out.push(']');
1331            }
1332            Value::Table(_) => {
1333                return Err(Error::serialize("CONF cannot hold a table as a value"));
1334            }
1335            #[cfg(feature = "chrono")]
1336            Value::DateTime(dt) => write_string(out, &dt.to_rfc3339()),
1337        }
1338        Ok(())
1339    }
1340
1341    fn write_string(out: &mut String, s: &str) {
1342        out.push('"');
1343        for c in s.chars() {
1344            match c {
1345                '"' => out.push_str("\\\""),
1346                '\\' => out.push_str("\\\\"),
1347                '\n' => out.push_str("\\n"),
1348                '\t' => out.push_str("\\t"),
1349                '\r' => out.push_str("\\r"),
1350                c => out.push(c),
1351            }
1352        }
1353        out.push('"');
1354    }
1355}
1356
1357/// TOML text output for TOML and modified NOML configurations
1358#[cfg(any(feature = "toml", feature = "noml"))]
1359mod toml_writer {
1360    use crate::error::{Error, Result};
1361    use crate::value::Value;
1362    use std::collections::BTreeMap;
1363    use std::fmt::Write;
1364
1365    fn is_table_array(value: &Value) -> bool {
1366        matches!(value, Value::Array(items)
1367            if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
1368    }
1369
1370    /// Write plain keys first, then `[table]` and `[[array]]` sections
1371    pub(super) fn write_table(
1372        out: &mut String,
1373        table: &BTreeMap<String, Value>,
1374        path: &mut Vec<String>,
1375        noml: bool,
1376    ) -> Result<()> {
1377        for (key, value) in table {
1378            if !matches!(value, Value::Table(_)) && !is_table_array(value) {
1379                write_key(out, key);
1380                out.push_str(" = ");
1381                write_value(out, value, path, key, noml)?;
1382                out.push('\n');
1383            }
1384        }
1385        for (key, value) in table {
1386            path.push(key.clone());
1387            match value {
1388                Value::Table(inner) => {
1389                    header(out, path, false);
1390                    write_table(out, inner, path, noml)?;
1391                }
1392                Value::Array(items) if is_table_array(value) => {
1393                    for item in items {
1394                        header(out, path, true);
1395                        if let Value::Table(inner) = item {
1396                            write_table(out, inner, path, noml)?;
1397                        }
1398                    }
1399                }
1400                _ => {}
1401            }
1402            path.pop();
1403        }
1404        Ok(())
1405    }
1406
1407    fn header(out: &mut String, path: &[String], array: bool) {
1408        if !out.is_empty() {
1409            out.push('\n');
1410        }
1411        out.push_str(if array { "[[" } else { "[" });
1412        for (i, key) in path.iter().enumerate() {
1413            if i > 0 {
1414                out.push('.');
1415            }
1416            write_key(out, key);
1417        }
1418        out.push_str(if array { "]]\n" } else { "]\n" });
1419    }
1420
1421    fn write_key(out: &mut String, key: &str) {
1422        let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1423            && key
1424                .bytes()
1425                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
1426        if bare {
1427            out.push_str(key);
1428        } else {
1429            write_string(out, key, false);
1430        }
1431    }
1432
1433    fn write_string(out: &mut String, s: &str, noml: bool) {
1434        out.push('"');
1435        let mut chars = s.chars().peekable();
1436        while let Some(c) = chars.next() {
1437            match c {
1438                '"' => out.push_str("\\\""),
1439                '\\' => out.push_str("\\\\"),
1440                '\n' => out.push_str("\\n"),
1441                '\t' => out.push_str("\\t"),
1442                '\r' => out.push_str("\\r"),
1443                '$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
1444                c if c.is_control() => {
1445                    let _ = write!(out, "\\u{:04X}", c as u32);
1446                }
1447                c => out.push(c),
1448            }
1449        }
1450        out.push('"');
1451    }
1452
1453    fn write_value(
1454        out: &mut String,
1455        value: &Value,
1456        path: &[String],
1457        key: &str,
1458        noml: bool,
1459    ) -> Result<()> {
1460        match value {
1461            Value::Null if noml => out.push_str("null"),
1462            Value::Null => {
1463                let mut full = path.join(".");
1464                if !full.is_empty() {
1465                    full.push('.');
1466                }
1467                full.push_str(key);
1468                return Err(Error::serialize(format!(
1469                    "TOML has no null value; cannot write '{full}'"
1470                )));
1471            }
1472            Value::Bool(b) => {
1473                let _ = write!(out, "{b}");
1474            }
1475            Value::Integer(i) => {
1476                let _ = write!(out, "{i}");
1477            }
1478            Value::Float(f) => {
1479                if f.is_nan() {
1480                    out.push_str("nan");
1481                } else if f.is_infinite() {
1482                    out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
1483                } else {
1484                    // Debug always keeps a '.' or exponent, so it reads back as a float
1485                    let _ = write!(out, "{f:?}");
1486                }
1487            }
1488            Value::String(s) => write_string(out, s, noml),
1489            Value::Array(items) => {
1490                out.push('[');
1491                for (i, item) in items.iter().enumerate() {
1492                    if i > 0 {
1493                        out.push_str(", ");
1494                    }
1495                    write_value(out, item, path, key, noml)?;
1496                }
1497                out.push(']');
1498            }
1499            Value::Table(table) => {
1500                out.push('{');
1501                for (i, (k, v)) in table.iter().enumerate() {
1502                    out.push_str(if i > 0 { ", " } else { " " });
1503                    write_key(out, k);
1504                    out.push_str(" = ");
1505                    write_value(out, v, path, key, noml)?;
1506                }
1507                out.push_str(if table.is_empty() { "}" } else { " }" });
1508            }
1509            #[cfg(feature = "chrono")]
1510            Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
1511        }
1512        Ok(())
1513    }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518    use super::*;
1519
1520    #[test]
1521    fn test_config_creation() {
1522        let config = Config::new();
1523        assert!(!config.is_modified());
1524        assert_eq!(config.format(), "conf");
1525    }
1526
1527    #[test]
1528    fn test_config_from_string() {
1529        let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
1530
1531        assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
1532        assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
1533    }
1534
1535    #[test]
1536    fn test_config_modification() {
1537        let mut config = Config::new();
1538        assert!(!config.is_modified());
1539
1540        config.set("key", "value").unwrap();
1541        assert!(config.is_modified());
1542
1543        config.mark_clean();
1544        assert!(!config.is_modified());
1545    }
1546
1547    #[test]
1548    fn test_config_merge() {
1549        let mut config1 = Config::new();
1550        config1.set("a", 1).unwrap();
1551        config1.set("b.x", 2).unwrap();
1552
1553        let mut config2 = Config::new();
1554        config2.set("b.y", 3).unwrap();
1555        config2.set("c", 4).unwrap();
1556
1557        config1.merge(&config2).unwrap();
1558
1559        assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
1560        assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
1561        assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
1562        assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
1563    }
1564
1565    #[cfg(feature = "toml")]
1566    #[test]
1567    fn modified_toml_serializes_current_values() {
1568        let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
1569        let mut config = Config::from_string(source, Some("toml")).unwrap();
1570
1571        // Unchanged: the original text is kept when the document is preserved
1572        #[cfg(feature = "noml")]
1573        assert_eq!(config.serialize().unwrap(), source);
1574
1575        config.set("server.port", 8080).unwrap();
1576        config.set("path", "C:\\dir \"q\"").unwrap();
1577        let text = config.serialize().unwrap();
1578        let reloaded = Config::from_string(&text, Some("toml")).unwrap();
1579        assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1580
1581        config.set("nothing", Value::Null).unwrap();
1582        assert!(config.serialize().is_err(), "TOML has no null");
1583    }
1584
1585    #[cfg(feature = "noml")]
1586    #[test]
1587    fn modified_noml_serializes_current_values() {
1588        let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
1589        let mut config = Config::from_string(source, Some("noml")).unwrap();
1590        assert_eq!(
1591            config.get("log").unwrap().as_string().unwrap(),
1592            "/var/log/app.log"
1593        );
1594
1595        config.set("template", "${not_a_reference}").unwrap();
1596        config.set("nothing", Value::Null).unwrap();
1597        let text = config.serialize().unwrap();
1598        let reloaded = Config::from_string(&text, Some("noml")).unwrap();
1599        assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1600    }
1601}