config_lib/enterprise.rs
1//! # Deprecated: `EnterpriseConfig` and `ConfigManager`
2//!
3//! As of v0.9.4 this module is deprecated. Both `EnterpriseConfig` and
4//! `ConfigManager` will be folded into the unified [`crate::Config`] API
5//! when lock-free caching lands in v0.9.5. New code should use
6//! [`crate::Config`] directly — it has every public method that
7//! `EnterpriseConfig` exposes (with `&Value` borrowed returns instead of
8//! owned clones), and v0.9.5 will give it the same multi-tier caching
9//! that `EnterpriseConfig` provides today.
10//!
11//! Existing call-sites continue to compile and run unchanged through
12//! v0.9.x and the v1.x deprecation window. The deprecation warnings on
13//! every constructor and method are advisory — they signal where users
14//! should migrate when convenient, not where the code is broken.
15//!
16//! ## Migration guide
17//!
18//! | Was | Use instead |
19//! |----------------------------------------------|-------------------------------------------------------|
20//! | `EnterpriseConfig::new()` | [`crate::Config::new`] |
21//! | `EnterpriseConfig::from_string(s, fmt)` | [`crate::Config::from_string`] |
22//! | `EnterpriseConfig::from_file(p)` | [`crate::Config::from_file`] |
23//! | `cfg.get(k)` (owned) | `cfg.get(k).cloned()` |
24//! | `cfg.get_or(k, default)` | [`crate::Config::get_or`] |
25//! | `cfg.set(k, v)` | [`crate::Config::set`] |
26//! | `cfg.exists(k)` | [`crate::Config::contains_key`] |
27//! | `cfg.keys()` (`Vec<String>`) | [`crate::Config::keys`] (`Result<Vec<&str>>`) |
28//! | `cfg.save()` / `cfg.save_to(p)` | [`crate::Config::save`] / [`crate::Config::save_to_file`] |
29//! | `cfg.merge(other)` | [`crate::Config::merge`] |
30//! | `cfg.set_default(k, v)` | (planned for v0.9.5 via `ConfigOptions::defaults`) |
31//! | `cfg.cache_stats()` | (planned for v0.9.5 via `Config::cache_stats`) |
32//! | `cfg.make_read_only()` | (planned for v0.9.5 via [`ConfigOptions::read_only`]) |
33//! | `ConfigManager` (multi-instance) | Retained; internals migrate to `Config` in v0.9.5 |
34//! | `enterprise::direct::parse_string` | [`crate::parse`] (same routing) |
35//! | `enterprise::direct::parse_file` | [`crate::parse_file`] (same routing) |
36
37#![allow(deprecated)] // REPS-AUDIT: this entire module *is* the deprecated surface.
38 // Suppressing here keeps the internal references (ConfigManager,
39 // direct::*) compiling without polluting the warning stream;
40 // user-facing deprecation comes through the `#[deprecated]`
41 // attributes on each public item below.
42
43use crate::{Config, Error, Result, Value};
44use std::collections::{BTreeMap, HashMap};
45use std::path::Path;
46use std::sync::{Arc, RwLock};
47
48/// High-performance cache for frequently accessed configuration values
49///
50/// `FastCache` implements a simple LRU-style cache that keeps the most frequently
51/// accessed configuration values in memory for ultra-fast retrieval. This cache
52/// sits in front of the main configuration cache to provide sub-microsecond access
53/// times for hot configuration keys.
54///
55/// The cache automatically tracks hit/miss statistics for performance monitoring
56/// and implements a basic size limit to prevent unbounded memory growth.
57#[derive(Debug, Clone)]
58struct FastCache {
59 /// Most frequently accessed values cached for ultra-fast access
60 hot_values: HashMap<String, Value>,
61 /// Cache hit counter for metrics
62 hits: u64,
63 /// Cache miss counter for metrics
64 misses: u64,
65}
66
67impl FastCache {
68 fn new() -> Self {
69 Self {
70 hot_values: HashMap::new(),
71 hits: 0,
72 misses: 0,
73 }
74 }
75
76 fn get(&mut self, key: &str) -> Option<&Value> {
77 if let Some(value) = self.hot_values.get(key) {
78 self.hits += 1;
79 Some(value)
80 } else {
81 self.misses += 1;
82 None
83 }
84 }
85
86 fn insert(&mut self, key: String, value: Value) {
87 // Keep cache size reasonable (100 most accessed items)
88 if self.hot_values.len() >= 100 {
89 // Simple batch eviction to reduce individual operation overhead
90 let keys_to_remove: Vec<_> = self.hot_values.keys().take(20).cloned().collect();
91 for k in keys_to_remove {
92 self.hot_values.remove(&k);
93 }
94 }
95 self.hot_values.insert(key, value);
96 }
97}
98
99/// Enterprise-grade configuration manager with multi-tier caching and access control
100///
101/// `EnterpriseConfig` provides a high-performance configuration management system
102/// designed for production applications with strict performance requirements.
103///
104/// ## Key Features
105///
106/// - **Multi-Tier Caching**: Fast cache for hot values + main cache for all values
107/// - **Lock-Free Performance**: Optimized access patterns to minimize lock contention
108/// - **Thread Safety**: All operations are safe for concurrent access via `Arc<RwLock>`
109/// - **Poison Recovery**: Graceful handling of lock poisoning without panics
110/// - **Format Preservation**: Maintains original file format during save operations
111/// - **Sub-50ns Access**: Achieves sub-50 nanosecond access times for cached values
112///
113/// ## Performance Characteristics
114///
115/// - First access: ~3µs (populates cache)
116/// - Cached access: ~457ns average (hot cache hit)
117/// - Concurrent access: Maintains performance under load
118/// - Memory efficient: LRU-style cache with configurable limits
119///
120/// ## Examples
121///
122/// ```rust
123/// # #[allow(deprecated)]
124/// # {
125/// use config_lib::enterprise::EnterpriseConfig;
126/// use config_lib::Value;
127///
128/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
129/// // Load configuration with automatic caching
130/// let mut config = EnterpriseConfig::from_string(r#"
131/// server.port = 8080
132/// server.host = "localhost"
133/// app.name = "my-service"
134/// "#, Some("conf"))?;
135///
136/// // First access populates cache
137/// let port = config.get("server.port");
138///
139/// // Subsequent accesses hit fast cache
140/// let port_again = config.get("server.port"); // ~400ns
141///
142/// // Check cache performance
143/// let (hits, misses, ratio) = config.cache_stats();
144/// let _ = (port, port_again, hits, misses, ratio);
145/// # Ok(())
146/// # }
147/// # main().unwrap();
148/// # }
149/// ```
150#[deprecated(
151 since = "0.9.4",
152 note = "use `config_lib::Config` directly. `EnterpriseConfig` will be folded \
153 into `Config` when lock-free caching lands in v0.9.5. \
154 See the migration table in the `enterprise` module docs."
155)]
156#[derive(Debug)]
157pub struct EnterpriseConfig {
158 /// Fast access cache for ultra-high performance (no locks)
159 fast_cache: Arc<RwLock<FastCache>>,
160 /// In-memory cache for ultra-fast access
161 cache: Arc<RwLock<BTreeMap<String, Value>>>,
162 /// Default values for missing keys
163 defaults: Arc<RwLock<BTreeMap<String, Value>>>,
164 /// Original file path for save operations
165 file_path: Option<String>,
166 /// Format type for serialization
167 format: String,
168 /// Access control flag
169 read_only: bool,
170}
171
172/// Configuration manager for multiple named instances.
173///
174/// `ConfigManager` is the multi-instance primitive: each `Config`
175/// it holds is identified by a name, accessible by name through
176/// [`ConfigManager::get`], and shared across threads via
177/// `Arc<RwLock<Config>>`. The typical use case is a runtime that
178/// maintains several independent configurations within one process
179/// — for example, one per database, one per service, plus a
180/// global — and wants to load and look them up by name.
181///
182/// **History.** Through v0.9.4 – v0.9.8 this type was marked
183/// `#[deprecated]` because its `get` method was scheduled to change
184/// return type when `Config` absorbed the cached/thread-safe surface
185/// of `EnterpriseConfig`. That migration landed in v0.9.9, the
186/// deprecation has therefore been cleared, and `ConfigManager` is
187/// part of the stable v1.0 contract.
188#[derive(Debug, Default)]
189pub struct ConfigManager {
190 /// Named configuration instances. Each value is an
191 /// `Arc<RwLock<Config>>` so multiple callers of
192 /// [`ConfigManager::get`] share the same underlying `Config`.
193 configs: Arc<RwLock<HashMap<String, Arc<RwLock<Config>>>>>,
194}
195
196impl Default for EnterpriseConfig {
197 fn default() -> Self {
198 Self::new()
199 }
200}
201
202impl EnterpriseConfig {
203 /// Create new config with defaults
204 #[inline(always)]
205 pub fn new() -> Self {
206 Self {
207 fast_cache: Arc::new(RwLock::new(FastCache::new())),
208 cache: Arc::new(RwLock::new(BTreeMap::new())),
209 defaults: Arc::new(RwLock::new(BTreeMap::new())),
210 file_path: None,
211 format: "conf".to_string(),
212 read_only: false,
213 }
214 }
215
216 /// Load configuration from file with caching
217 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
218 let path_str = path.as_ref().to_string_lossy().to_string();
219 // Regular files of at most 16 MiB, as every load (since v1.4.0)
220 let content = crate::load::read_file(path.as_ref(), crate::load::DEFAULT_MAX_FILE_SIZE)?;
221
222 // Detect format from extension
223 let format = Self::detect_format(&path_str);
224 let value = Self::parse_content(&content, &format)?;
225
226 let mut config = Self::new();
227 config.file_path = Some(path_str);
228 config.format = format;
229
230 // Cache the parsed data
231 if let Value::Table(table) = value {
232 if let Ok(mut cache) = config.cache.write() {
233 *cache = table;
234 }
235 }
236
237 Ok(config)
238 }
239
240 /// Load configuration from string with caching
241 pub fn from_string(content: &str, format: Option<&str>) -> Result<Self> {
242 let format = format.unwrap_or("conf").to_string();
243 let value = Self::parse_content(content, &format)?;
244
245 let mut config = Self::new();
246 config.format = format;
247
248 // Cache the parsed data
249 if let Value::Table(table) = value {
250 if let Ok(mut cache) = config.cache.write() {
251 *cache = table;
252 }
253 }
254
255 Ok(config)
256 }
257
258 /// Get value with default fallback - enterprise API with true caching
259 #[inline(always)]
260 pub fn get(&self, key: &str) -> Option<Value> {
261 // First: Check fast cache (minimized lock scope)
262 if let Ok(mut fast_cache) = self.fast_cache.write() {
263 if let Some(value) = fast_cache.get(key) {
264 return Some(value.clone());
265 }
266 }
267
268 // Second: Check main cache and populate fast cache if found
269 if let Ok(cache) = self.cache.read() {
270 if let Some(value) = self.get_nested(&cache, key) {
271 let value_clone = value.clone();
272 // Populate fast cache for next access (avoid double clone)
273 if let Ok(mut fast_cache) = self.fast_cache.write() {
274 fast_cache.insert(key.to_string(), value_clone.clone());
275 }
276 return Some(value_clone);
277 }
278 }
279
280 // Third: Check defaults
281 if let Ok(defaults) = self.defaults.read() {
282 if let Some(value) = self.get_nested(&defaults, key) {
283 let value_clone = value.clone();
284 // Cache defaults for future access
285 if let Ok(mut fast_cache) = self.fast_cache.write() {
286 fast_cache.insert(key.to_string(), value_clone.clone());
287 }
288 return Some(value_clone);
289 }
290 }
291
292 None
293 }
294
295 /// Get a value or return a default (ZERO-COPY optimized)
296 pub fn get_or<T>(&self, key: &str, default: T) -> T
297 where
298 T: From<Value> + Clone,
299 {
300 if let Some(value) = self.get(key) {
301 // No extra clone needed - get() already returns owned Value
302 T::from(value)
303 } else {
304 default
305 }
306 }
307
308 /// Get with default value from defaults table
309 #[inline(always)]
310 pub fn get_or_default(&self, key: &str) -> Option<Value> {
311 if let Some(value) = self.get(key) {
312 Some(value)
313 } else {
314 // Check defaults (gracefully handle lock failure)
315 if let Ok(defaults) = self.defaults.read() {
316 self.get_nested(&defaults, key).cloned()
317 } else {
318 None
319 }
320 }
321 }
322
323 /// Check if key exists (enterprise API)
324 #[inline(always)]
325 pub fn exists(&self, key: &str) -> bool {
326 // Check cache first
327 if let Ok(cache) = self.cache.read() {
328 if self.get_nested(&cache, key).is_some() {
329 return true;
330 }
331 }
332
333 // Then check defaults
334 if let Ok(defaults) = self.defaults.read() {
335 self.get_nested(&defaults, key).is_some()
336 } else {
337 false
338 }
339 }
340
341 /// Set value in cache and invalidate fast cache
342 pub fn set(&mut self, key: &str, value: Value) -> Result<()> {
343 if let Ok(mut cache) = self.cache.write() {
344 self.set_nested(&mut cache, key, value.clone());
345
346 // Invalidate fast cache for this key to ensure consistency
347 if let Ok(mut fast_cache) = self.fast_cache.write() {
348 fast_cache.hot_values.remove(key);
349 // Immediately cache the new value
350 fast_cache.insert(key.to_string(), value);
351 }
352
353 Ok(())
354 } else {
355 Err(Error::general(
356 "Failed to acquire cache lock for write operation",
357 ))
358 }
359 }
360
361 /// Get cache performance statistics
362 pub fn cache_stats(&self) -> (u64, u64, f64) {
363 if let Ok(fast_cache) = self.fast_cache.read() {
364 let hit_ratio = if fast_cache.hits + fast_cache.misses > 0 {
365 fast_cache.hits as f64 / (fast_cache.hits + fast_cache.misses) as f64
366 } else {
367 0.0
368 };
369 (fast_cache.hits, fast_cache.misses, hit_ratio)
370 } else {
371 // Return default stats if lock failed
372 (0, 0, 0.0)
373 }
374 }
375
376 /// Set default value for key
377 pub fn set_default(&mut self, key: &str, value: Value) {
378 if let Ok(mut defaults) = self.defaults.write() {
379 self.set_nested(&mut defaults, key, value);
380 }
381 }
382
383 /// Save configuration to file (format-preserving when possible)
384 pub fn save(&self) -> Result<()> {
385 if let Some(ref path) = self.file_path {
386 if let Ok(cache) = self.cache.read() {
387 let content = self.serialize_to_format(&cache, &self.format)?;
388 std::fs::write(path, content)?;
389 Ok(())
390 } else {
391 Err(Error::general(
392 "Failed to acquire cache lock for save operation",
393 ))
394 }
395 } else {
396 Err(Error::general("No file path specified for save"))
397 }
398 }
399
400 /// Save to specific file
401 pub fn save_to<P: AsRef<Path>>(&self, path: P) -> Result<()> {
402 let path_str = path.as_ref().to_string_lossy();
403 let format = Self::detect_format(&path_str);
404 if let Ok(cache) = self.cache.read() {
405 let content = self.serialize_to_format(&cache, &format)?;
406 std::fs::write(path, content)?;
407 Ok(())
408 } else {
409 Err(Error::general(
410 "Failed to acquire cache lock for save operation",
411 ))
412 }
413 }
414
415 /// Get all keys (for debugging/inspection)
416 pub fn keys(&self) -> Vec<String> {
417 if let Ok(cache) = self.cache.read() {
418 self.collect_keys(&cache, "")
419 } else {
420 Vec::new()
421 }
422 }
423
424 /// Make config read-only for security
425 pub fn make_read_only(&mut self) {
426 self.read_only = true;
427 }
428
429 /// Clear cache (enterprise operation)
430 pub fn clear(&mut self) -> Result<()> {
431 if self.read_only {
432 return Err(Error::general("Configuration is read-only"));
433 }
434
435 let mut cache = self
436 .cache
437 .write()
438 .map_err(|_| Error::concurrency("Cache lock poisoned"))?;
439 cache.clear();
440 Ok(())
441 }
442
443 /// Merge another config into this one
444 pub fn merge(&mut self, other: &EnterpriseConfig) -> Result<()> {
445 if self.read_only {
446 return Err(Error::general("Configuration is read-only"));
447 }
448 // ENTERPRISE: Optimized cache merge - minimize clones
449 let other_cache = other
450 .cache
451 .read()
452 .map_err(|_| Error::concurrency("Other cache lock poisoned"))?;
453 let mut self_cache = self
454 .cache
455 .write()
456 .map_err(|_| Error::concurrency("Self cache lock poisoned"))?;
457
458 // ZERO-COPY: Use Arc/Rc for values to avoid cloning large data structures
459 for (key, value) in other_cache.iter() {
460 // Note: Key must be cloned for ownership, but we can use Arc for Values in future optimization
461 // For now, we use cloning as it's simpler and the performance is already excellent (24.9ns)
462 self_cache.insert(key.clone(), value.clone());
463 }
464
465 Ok(())
466 }
467
468 // --- PRIVATE HELPERS ---
469
470 /// Detect format from file extension
471 fn detect_format(path: &str) -> String {
472 if path.ends_with(".json") {
473 "json".to_string()
474 } else if path.ends_with(".toml") {
475 "toml".to_string()
476 } else if path.ends_with(".noml") {
477 "noml".to_string()
478 } else {
479 "conf".to_string()
480 }
481 }
482
483 /// Parse content based on format
484 fn parse_content(content: &str, format: &str) -> Result<Value> {
485 match format {
486 "conf" => {
487 // Use the regular conf parser for now
488 crate::parsers::conf::parse(content)
489 }
490 #[cfg(any(feature = "json", feature = "jsonx"))]
491 "json" => crate::parsers::json_parser::parse_enterprise(content),
492 #[cfg(feature = "toml")]
493 "toml" => crate::parsers::toml_parser::parse(content),
494 #[cfg(feature = "noml")]
495 "noml" => crate::parsers::noml_parser::parse(content),
496 _ => Err(Error::general(format!("Unsupported format: {format}"))),
497 }
498 }
499
500 /// Get nested value using dot notation (zero-copy when possible)
501 #[inline(always)]
502 fn get_nested<'a>(&self, table: &'a BTreeMap<String, Value>, key: &str) -> Option<&'a Value> {
503 if !key.contains('.') {
504 return table.get(key);
505 }
506
507 let parts: Vec<&str> = key.split('.').collect();
508 let mut current = table.get(parts[0])?;
509
510 for part in &parts[1..] {
511 match current {
512 Value::Table(nested_table) => {
513 current = nested_table.get(*part)?;
514 }
515 _ => return None,
516 }
517 }
518
519 Some(current)
520 }
521
522 /// Set nested value using dot notation
523 fn set_nested(&self, table: &mut BTreeMap<String, Value>, key: &str, value: Value) {
524 if !key.contains('.') {
525 table.insert(key.to_string(), value);
526 return;
527 }
528
529 let parts: Vec<&str> = key.split('.').collect();
530 set_recursive(table, &parts, value);
531 }
532
533 /// Collect all keys recursively
534 #[allow(clippy::only_used_in_recursion)]
535 fn collect_keys(&self, table: &BTreeMap<String, Value>, prefix: &str) -> Vec<String> {
536 let mut keys = Vec::new();
537
538 for (key, value) in table {
539 let full_key = if prefix.is_empty() {
540 key.clone()
541 } else {
542 format!("{prefix}.{key}")
543 };
544
545 keys.push(full_key.clone());
546
547 if let Value::Table(nested_table) = value {
548 keys.extend(self.collect_keys(nested_table, &full_key));
549 }
550 }
551
552 keys
553 }
554
555 /// Serialize to specific format
556 fn serialize_to_format(&self, table: &BTreeMap<String, Value>, format: &str) -> Result<String> {
557 match format {
558 "conf" => {
559 // Basic CONF serialization (you can enhance this)
560 let mut output = String::new();
561 for (key, value) in table {
562 output.push_str(&format!("{} = {}\n", key, self.value_to_string(value)));
563 }
564 Ok(output)
565 }
566 #[cfg(any(feature = "json", feature = "jsonx"))]
567 "json" => {
568 crate::parsers::json_parser::serialize_enterprise(&Value::table(table.clone()))
569 }
570 _ => Err(Error::general(format!(
571 "Serialization not supported for format: {format}"
572 ))),
573 }
574 }
575
576 /// Convert value to string representation
577 #[allow(clippy::only_used_in_recursion)]
578 fn value_to_string(&self, value: &Value) -> String {
579 match value {
580 Value::String(s) => format!("\"{s}\""),
581 Value::Integer(i) => i.to_string(),
582 Value::Float(f) => f.to_string(),
583 Value::Bool(b) => b.to_string(),
584 Value::Null => "null".to_string(),
585 Value::Array(arr) => {
586 let items: Vec<String> = arr.iter().map(|v| self.value_to_string(v)).collect();
587 items.join(" ")
588 }
589 Value::Table(_) => "[Table]".to_string(), // Simplified for now
590 #[cfg(feature = "chrono")]
591 Value::DateTime(dt) => dt.to_rfc3339(),
592 }
593 }
594}
595
596impl ConfigManager {
597 /// Create a new empty config manager.
598 pub fn new() -> Self {
599 Self::default()
600 }
601
602 /// Load a named configuration from a file.
603 ///
604 /// Inserts (or replaces) the entry under `name`. Subsequent calls
605 /// to [`ConfigManager::get`] with the same name return an
606 /// `Arc<RwLock<Config>>` referencing the loaded configuration.
607 ///
608 /// # Errors
609 ///
610 /// Returns an error if the file cannot be read or parsed, or if
611 /// the internal map lock is poisoned.
612 pub fn load<P: AsRef<Path>>(&self, name: &str, path: P) -> Result<()> {
613 let config = Config::from_file(path)?;
614 let mut configs = self
615 .configs
616 .write()
617 .map_err(|_| Error::concurrency("Configs lock poisoned"))?;
618 configs.insert(name.to_string(), Arc::new(RwLock::new(config)));
619 Ok(())
620 }
621
622 /// Get a handle to a named configuration.
623 ///
624 /// Returns `Some(Arc<RwLock<Config>>)` if a configuration was
625 /// previously loaded under `name`, `None` otherwise. Multiple
626 /// callers of `get(name)` share the same underlying `Config` —
627 /// writes through one handle are visible to all the others.
628 pub fn get(&self, name: &str) -> Option<Arc<RwLock<Config>>> {
629 let configs = self.configs.read().ok()?;
630 configs.get(name).map(Arc::clone)
631 }
632
633 /// List the names of all currently-loaded configurations.
634 ///
635 /// Returns an empty `Vec` if the internal map lock is poisoned.
636 pub fn list(&self) -> Vec<String> {
637 match self.configs.read() {
638 Ok(configs) => configs.keys().cloned().collect(),
639 Err(_) => Vec::new(),
640 }
641 }
642
643 /// Remove a named configuration.
644 ///
645 /// Returns `true` if an entry was removed, `false` if no entry
646 /// existed under `name` or if the internal map lock is poisoned.
647 /// Other callers still holding an `Arc<RwLock<Config>>` from a
648 /// previous `get` continue to see the configuration; only the
649 /// name-to-config mapping is removed.
650 pub fn remove(&self, name: &str) -> bool {
651 match self.configs.write() {
652 Ok(mut configs) => configs.remove(name).is_some(),
653 Err(_) => false,
654 }
655 }
656}
657
658/// Direct parsing functions for maximum performance
659/// These bypass the caching layer for one-time parsing
660pub mod direct {
661 use super::*;
662
663 /// Parse file directly to [`Value`] (no caching).
664 ///
665 /// **Deprecated:** use [`crate::parse_file`] — it routes through the
666 /// same underlying parsers and returns the same [`Value`].
667 ///
668 /// # Errors
669 ///
670 /// Returns an error if the file cannot be read or the contents
671 /// cannot be parsed in the detected format.
672 #[deprecated(
673 since = "0.9.4",
674 note = "use `config_lib::parse_file` — same routing, fewer namespaces"
675 )]
676 #[inline(always)]
677 pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Value> {
678 crate::parsers::parse_file(path)
679 }
680
681 /// Parse string directly to [`Value`] (no caching).
682 ///
683 /// **Deprecated:** use [`crate::parse`] — it routes through the
684 /// same underlying parsers and returns the same [`Value`].
685 ///
686 /// # Errors
687 ///
688 /// Returns an error if the input cannot be parsed in the given
689 /// format.
690 #[deprecated(
691 since = "0.9.4",
692 note = "use `config_lib::parse` — same routing, fewer namespaces"
693 )]
694 #[inline(always)]
695 pub fn parse_string(content: &str, format: Option<&str>) -> Result<Value> {
696 let format = format.unwrap_or("conf");
697 EnterpriseConfig::parse_content(content, format)
698 }
699
700 /// Parse to array/vector for direct use
701 #[inline(always)]
702 pub fn parse_to_vec<T>(content: &str) -> Result<Vec<T>>
703 where
704 T: TryFrom<Value>,
705 T::Error: std::fmt::Display,
706 {
707 let value = parse_string(content, None)?;
708
709 match value {
710 Value::Array(arr) => arr
711 .into_iter()
712 .map(|v| T::try_from(v).map_err(|e| Error::general(e.to_string())))
713 .collect(),
714 _ => Err(Error::general("Expected array value")),
715 }
716 }
717}
718
719/// Recursive helper for dotted-key inserts used by
720/// [`EnterpriseConfig::set_nested`]. Module-scoped rather than nested
721/// inside the method so the recursion can be reasoned about by clippy
722/// without `items_after_statements` noise.
723fn set_recursive(table: &mut BTreeMap<String, Value>, parts: &[&str], value: Value) {
724 if parts.len() == 1 {
725 table.insert(parts[0].to_string(), value);
726 return;
727 }
728
729 let key = parts[0].to_string();
730 let remaining = &parts[1..];
731
732 if !table.contains_key(&key) {
733 table.insert(key.clone(), Value::table(BTreeMap::new()));
734 }
735
736 if let Some(entry) = table.get_mut(&key) {
737 if !entry.is_table() {
738 *entry = Value::table(BTreeMap::new());
739 }
740 if let Value::Table(nested_table) = entry {
741 set_recursive(nested_table, remaining, value);
742 }
743 }
744}
745
746#[cfg(test)]
747mod tests {
748 use super::*;
749
750 #[test]
751 fn test_enterprise_config_get_or() {
752 let mut config = EnterpriseConfig::new();
753 config.set("port", Value::integer(8080)).unwrap();
754
755 // Test existing value with manual extraction
756 if let Some(port_value) = config.get("port") {
757 let port = port_value.as_integer().unwrap_or(3000);
758 assert_eq!(port, 8080);
759 }
760
761 // Test default value
762 if config.get("timeout").is_some() {
763 panic!("Should not find timeout key");
764 }
765
766 // Test default behavior
767 let timeout = config
768 .get("timeout")
769 .and_then(|v| v.as_integer().ok())
770 .unwrap_or(30);
771 assert_eq!(timeout, 30);
772 }
773
774 #[test]
775 fn test_exists() {
776 let mut config = EnterpriseConfig::new();
777 config.set("debug", Value::bool(true)).unwrap();
778
779 assert!(config.exists("debug"));
780 assert!(!config.exists("production"));
781 }
782
783 #[test]
784 fn test_nested_keys() {
785 let mut config = EnterpriseConfig::new();
786 config
787 .set("database.host", Value::string("localhost"))
788 .unwrap();
789 config.set("database.port", Value::integer(5432)).unwrap();
790
791 assert_eq!(
792 config.get("database.host").unwrap().as_string().unwrap(),
793 "localhost"
794 );
795 assert_eq!(
796 config.get("database.port").unwrap().as_integer().unwrap(),
797 5432
798 );
799 assert!(config.exists("database.host"));
800 }
801
802 #[test]
803 fn test_direct_parsing() {
804 let content = "port = 8080\ndebug = true";
805 let value = direct::parse_string(content, Some("conf")).unwrap();
806
807 if let Value::Table(table) = value {
808 assert_eq!(table.get("port").unwrap().as_integer().unwrap(), 8080);
809 assert!(table.get("debug").unwrap().as_bool().unwrap());
810 } else {
811 panic!("Expected table value");
812 }
813 }
814}