1use crate::error::{Error, Result};
7use crate::parsers;
8use crate::value::Value;
9use dashmap::DashMap;
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, RwLock};
14
15#[cfg(feature = "schema")]
16use crate::schema::Schema;
17
18#[cfg(feature = "validation")]
19use crate::validation::{ValidationError, ValidationRuleSet};
20
21#[derive(Debug)]
57pub struct Config {
58 values: Value,
60
61 file_path: Option<PathBuf>,
63
64 format: String,
66
67 modified: bool,
69
70 options: ConfigOptions,
73
74 cache_hits: AtomicU64,
78
79 cache_misses: AtomicU64,
81
82 cache: DashMap<Box<str>, Arc<Value>>,
94
95 defaults: Arc<RwLock<BTreeMap<String, Value>>>,
101
102 #[cfg(feature = "noml")]
104 noml_document: Option<noml::Document>,
105
106 #[cfg(feature = "validation")]
108 validation_rules: Option<ValidationRuleSet>,
109}
110
111impl Config {
112 pub fn new() -> Self {
114 Self {
115 values: Value::table(BTreeMap::new()),
116 file_path: None,
117 format: "conf".to_string(),
118 modified: false,
119 options: ConfigOptions::default(),
120 cache_hits: AtomicU64::new(0),
121 cache_misses: AtomicU64::new(0),
122 cache: DashMap::new(),
123 defaults: Arc::new(RwLock::new(BTreeMap::new())),
124 #[cfg(feature = "noml")]
125 noml_document: None,
126 #[cfg(feature = "validation")]
127 validation_rules: None,
128 }
129 }
130
131 pub fn from_string(source: &str, format: Option<&str>) -> Result<Self> {
133 let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
134
135 let values = parsers::parse_string(source, Some(detected_format))?;
136
137 #[cfg(feature = "noml")]
138 let mut config = Self {
139 values,
140 file_path: None,
141 format: detected_format.to_string(),
142 modified: false,
143 options: ConfigOptions::default(),
144 cache_hits: AtomicU64::new(0),
145 cache_misses: AtomicU64::new(0),
146 cache: DashMap::new(),
147 defaults: Arc::new(RwLock::new(BTreeMap::new())),
148 noml_document: None,
149 #[cfg(feature = "validation")]
150 validation_rules: None,
151 };
152
153 #[cfg(not(feature = "noml"))]
154 let config = Self {
155 values,
156 file_path: None,
157 format: detected_format.to_string(),
158 modified: false,
159 options: ConfigOptions::default(),
160 cache_hits: AtomicU64::new(0),
161 cache_misses: AtomicU64::new(0),
162 cache: DashMap::new(),
163 defaults: Arc::new(RwLock::new(BTreeMap::new())),
164 #[cfg(feature = "validation")]
165 validation_rules: None,
166 };
167
168 #[cfg(feature = "noml")]
170 if detected_format == "noml" || detected_format == "toml" {
171 if let Ok(document) = noml::parse_string(source, None) {
172 config.noml_document = Some(document);
173 }
174 }
175
176 Ok(config)
177 }
178
179 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
181 let path = path.as_ref();
182 let content =
183 std::fs::read_to_string(path).map_err(|e| Error::io(path.display().to_string(), e))?;
184
185 let format = parsers::detect_format_from_path(path)
186 .unwrap_or_else(|| parsers::detect_format(&content));
187
188 let mut config = Self::from_string(&content, Some(format))?;
189 config.file_path = Some(path.to_path_buf());
190
191 Ok(config)
192 }
193
194 #[cfg(feature = "async")]
196 pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
197 let path = path.as_ref();
198 let content = tokio::fs::read_to_string(path)
199 .await
200 .map_err(|e| Error::io(path.display().to_string(), e))?;
201
202 let format = parsers::detect_format_from_path(path)
203 .unwrap_or_else(|| parsers::detect_format(&content));
204
205 let mut config = Self::from_string(&content, Some(format))?;
206 config.file_path = Some(path.to_path_buf());
207
208 Ok(config)
209 }
210
211 pub fn get(&self, path: &str) -> Option<&Value> {
213 self.values.get(path)
214 }
215
216 pub fn get_mut(&mut self, path: &str) -> Result<&mut Value> {
218 self.values.get_mut_nested(path)
219 }
220
221 pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()> {
233 self.ensure_writable()?;
234 self.values.set_nested(path, value.into())?;
235 self.modified = true;
236 self.cache.clear();
237 Ok(())
238 }
239
240 pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
250 self.ensure_writable()?;
251 let result = self.values.remove(path)?;
252 if result.is_some() {
253 self.modified = true;
254 self.cache.clear();
255 }
256 Ok(result)
257 }
258
259 pub fn contains_key(&self, path: &str) -> bool {
261 self.values.contains_key(path)
262 }
263
264 pub fn keys(&self) -> Result<Vec<&str>> {
266 self.values.keys()
267 }
268
269 pub fn is_modified(&self) -> bool {
271 self.modified
272 }
273
274 pub fn mark_clean(&mut self) {
276 self.modified = false;
277 }
278
279 pub fn format(&self) -> &str {
281 &self.format
282 }
283
284 pub fn file_path(&self) -> Option<&Path> {
286 self.file_path.as_deref()
287 }
288
289 pub fn save(&mut self) -> Result<()> {
291 match &self.file_path {
292 Some(path) => {
293 self.save_to_file(path.clone())?;
294 self.modified = false;
295 Ok(())
296 }
297 None => Err(Error::internal(
298 "Cannot save configuration that wasn't loaded from a file",
299 )),
300 }
301 }
302
303 pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
305 let serialized = self.serialize()?;
306 std::fs::write(path, serialized).map_err(|e| Error::io("save".to_string(), e))?;
307 Ok(())
308 }
309
310 #[cfg(feature = "async")]
312 pub async fn save_async(&mut self) -> Result<()> {
313 match &self.file_path {
314 Some(path) => {
315 self.save_to_file_async(path.clone()).await?;
316 self.modified = false;
317 Ok(())
318 }
319 None => Err(Error::internal(
320 "Cannot save configuration that wasn't loaded from a file",
321 )),
322 }
323 }
324
325 #[cfg(feature = "async")]
327 pub async fn save_to_file_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
328 let serialized = self.serialize()?;
329 tokio::fs::write(path, serialized)
330 .await
331 .map_err(|e| Error::io("save".to_string(), e))?;
332 Ok(())
333 }
334
335 pub fn serialize(&self) -> Result<String> {
337 match self.format.as_str() {
338 "json" => {
339 #[cfg(feature = "json")]
340 return crate::parsers::json_parser::serialize(&self.values);
341 #[cfg(not(feature = "json"))]
342 return Err(Error::feature_not_enabled("json"));
343 }
344 "toml" => {
345 #[cfg(feature = "toml")]
346 {
347 #[cfg(feature = "noml")]
350 if !self.modified {
351 if let Some(ref document) = self.noml_document {
352 return Ok(noml::serialize_document(document)?);
353 }
354 }
355 self.serialize_as_toml(false)
356 }
357 #[cfg(not(feature = "toml"))]
358 return Err(Error::feature_not_enabled("toml"));
359 }
360 "noml" => {
361 #[cfg(feature = "noml")]
362 {
363 if !self.modified {
364 if let Some(ref document) = self.noml_document {
365 return Ok(noml::serialize_document(document)?);
366 }
367 }
368 self.serialize_as_toml(true)
369 }
370 #[cfg(not(feature = "noml"))]
371 return Err(Error::feature_not_enabled("noml"));
372 }
373 "conf" => self.serialize_as_conf(),
374 _ => Err(Error::unknown_format(&self.format)),
375 }
376 }
377
378 fn serialize_as_conf(&self) -> Result<String> {
380 let mut output = String::new();
381 if let Value::Table(table) = &self.values {
382 self.write_conf_table(&mut output, table, "")?;
383 }
384 Ok(output)
385 }
386
387 fn write_conf_table(
389 &self,
390 output: &mut String,
391 table: &BTreeMap<String, Value>,
392 section_prefix: &str,
393 ) -> Result<()> {
394 for (key, value) in table {
396 if !value.is_table() {
397 let formatted_value = self.format_conf_value(value)?;
398 output.push_str(&format!("{key} = {formatted_value}\n"));
399 }
400 }
401
402 for (key, value) in table {
404 if let Value::Table(nested_table) = value {
405 let section_name = if section_prefix.is_empty() {
406 key.clone()
407 } else {
408 format!("{section_prefix}.{key}")
409 };
410
411 output.push_str(&format!("\n[{section_name}]\n"));
412 self.write_conf_table(output, nested_table, §ion_name)?;
413 }
414 }
415
416 Ok(())
417 }
418
419 #[allow(clippy::only_used_in_recursion)]
421 fn format_conf_value(&self, value: &Value) -> Result<String> {
422 match value {
423 Value::Null => Ok("null".to_string()),
424 Value::Bool(b) => Ok(b.to_string()),
425 Value::Integer(i) => Ok(i.to_string()),
426 Value::Float(f) => Ok(f.to_string()),
427 Value::String(s) => {
428 if s.contains(' ') || s.contains('\t') || s.contains('\n') {
429 Ok(format!("\"{}\"", s.replace('"', "\\\"")))
430 } else {
431 Ok(s.clone())
432 }
433 }
434 Value::Array(arr) => {
435 let items: Result<Vec<String>> =
436 arr.iter().map(|v| self.format_conf_value(v)).collect();
437 Ok(items?.join(" "))
438 }
439 Value::Table(_) => Err(Error::type_error(
440 "Cannot serialize nested table as value",
441 "primitive",
442 "table",
443 )),
444 #[cfg(feature = "chrono")]
445 Value::DateTime(dt) => Ok(dt.to_rfc3339()),
446 }
447 }
448
449 #[cfg(any(feature = "toml", feature = "noml"))]
456 fn serialize_as_toml(&self, noml: bool) -> Result<String> {
457 let mut out = String::new();
458 if let Value::Table(table) = &self.values {
459 toml_writer::write_table(&mut out, table, &mut Vec::new(), noml)?;
460 }
461 Ok(out)
462 }
463
464 #[cfg(feature = "schema")]
466 pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
467 schema.validate(&self.values)
468 }
469
470 pub fn as_value(&self) -> &Value {
472 &self.values
473 }
474
475 pub fn merge(&mut self, other: &Config) -> Result<()> {
484 self.ensure_writable()?;
485 self.merge_value(&other.values)?;
486 self.modified = true;
487 self.cache.clear();
488 Ok(())
489 }
490
491 fn merge_value(&mut self, other: &Value) -> Result<()> {
493 match (&mut self.values, other) {
494 (Value::Table(self_table), Value::Table(other_table)) => {
495 for (key, other_value) in other_table {
496 match self_table.get_mut(key) {
497 Some(self_value) => {
498 if let (Value::Table(_), Value::Table(_)) = (&*self_value, other_value)
499 {
500 let mut temp_config = Config::new();
502 temp_config.values = self_value.clone();
503 temp_config.merge_value(other_value)?;
504 *self_value = temp_config.values;
505 } else {
506 *self_value = other_value.clone();
508 }
509 }
510 None => {
511 self_table.insert(key.clone(), other_value.clone());
513 }
514 }
515 }
516 }
517 _ => {
518 self.values = other.clone();
520 }
521 }
522 Ok(())
523 }
524
525 pub fn key(&self, path: &str) -> ConfigValue<'_> {
533 ConfigValue::new(self.get(path))
534 }
535
536 pub fn has(&self, path: &str) -> bool {
538 self.contains_key(path)
539 }
540
541 pub fn get_or<V>(&self, path: &str, default: V) -> V
543 where
544 V: TryFrom<Value> + Clone,
545 V::Error: std::fmt::Debug,
546 {
547 self.get(path)
548 .and_then(|v| V::try_from(v.clone()).ok())
549 .unwrap_or(default)
550 }
551
552 #[cfg(feature = "validation")]
556 pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
557 self.validation_rules = Some(rules);
558 }
559
560 #[cfg(feature = "validation")]
562 pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
563 match &mut self.validation_rules {
564 Some(rules) => {
565 if let Value::Table(table) = &self.values {
566 let mut errors = Vec::new();
567
568 for (key, value) in table {
570 errors.extend(rules.validate(key, value));
571 }
572
573 Ok(errors)
577 } else {
578 Err(Error::validation(
579 "Configuration root must be a table for validation",
580 ))
581 }
582 }
583 None => Ok(Vec::new()), }
585 }
586
587 #[cfg(feature = "validation")]
589 pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
590 let all_errors = self.validate()?;
591 Ok(all_errors
592 .into_iter()
593 .filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
594 .collect())
595 }
596
597 #[cfg(feature = "validation")]
599 pub fn is_valid(&mut self) -> Result<bool> {
600 let critical_errors = self.validate_critical_only()?;
601 Ok(critical_errors.is_empty())
602 }
603
604 #[cfg(feature = "validation")]
606 pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
607 let value = self
609 .get(path)
610 .ok_or_else(|| Error::key_not_found(path))?
611 .clone();
612
613 match &mut self.validation_rules {
614 Some(rules) => Ok(rules.validate(path, &value)),
615 None => Ok(Vec::new()),
616 }
617 }
618}
619
620impl Default for Config {
621 fn default() -> Self {
622 Self::new()
623 }
624}
625
626#[derive(Debug, Clone)]
658#[non_exhaustive]
659pub struct ConfigOptions {
660 pub read_only: bool,
664
665 pub cache_enabled: bool,
670
671 pub cache_capacity: usize,
674}
675
676impl Default for ConfigOptions {
677 fn default() -> Self {
681 Self {
682 read_only: false,
683 cache_enabled: true,
684 cache_capacity: 1024,
685 }
686 }
687}
688
689impl ConfigOptions {
690 pub fn new() -> Self {
693 Self::default()
694 }
695
696 pub fn read_only(mut self, read_only: bool) -> Self {
698 self.read_only = read_only;
699 self
700 }
701
702 pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
706 self.cache_enabled = cache_enabled;
707 self
708 }
709
710 pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
713 self.cache_capacity = cache_capacity;
714 self
715 }
716}
717
718impl Config {
719 pub fn with_options(options: ConfigOptions) -> Self {
725 let mut config = Self::new();
726 config.options = options;
727 config
728 }
729
730 pub fn options(&self) -> &ConfigOptions {
732 &self.options
733 }
734
735 pub fn is_read_only(&self) -> bool {
738 self.options.read_only
739 }
740
741 fn ensure_writable(&self) -> Result<()> {
744 if self.options.read_only {
745 Err(Error::general("Configuration is read-only"))
746 } else {
747 Ok(())
748 }
749 }
750
751 pub fn cache_stats(&self) -> CacheStats {
757 let hits = self.cache_hits.load(Ordering::Relaxed);
758 let misses = self.cache_misses.load(Ordering::Relaxed);
759 let total = hits.saturating_add(misses);
760 let hit_ratio = if total == 0 {
761 0.0
762 } else {
763 hits as f64 / total as f64
764 };
765 CacheStats {
766 hits,
767 misses,
768 hit_ratio,
769 }
770 }
771
772 pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
799 if self.options.cache_enabled {
800 if let Some(entry) = self.cache.get(path) {
801 self.cache_hits.fetch_add(1, Ordering::Relaxed);
802 return Some(Arc::clone(entry.value()));
803 }
804 self.cache_misses.fetch_add(1, Ordering::Relaxed);
805 let resolved = self.values.get(path)?.clone();
806 let arc = Arc::new(resolved);
807 self.cache.insert(path.into(), Arc::clone(&arc));
808 Some(arc)
809 } else {
810 self.cache_misses.fetch_add(1, Ordering::Relaxed);
811 Some(Arc::new(self.values.get(path)?.clone()))
812 }
813 }
814
815 pub fn clear_cache(&self) {
821 self.cache.clear();
822 }
823
824 pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
841 let mut defaults = self
842 .defaults
843 .write()
844 .map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
845 defaults.insert(path.to_string(), value.into());
846 Ok(())
847 }
848
849 pub fn get_or_default(&self, path: &str) -> Option<Value> {
858 if let Some(v) = self.values.get(path) {
859 return Some(v.clone());
860 }
861 let defaults = self.defaults.read().ok()?;
862 defaults.get(path).cloned()
863 }
864
865 pub fn make_read_only(&mut self) {
878 self.options.read_only = true;
879 }
880}
881
882#[derive(Debug, Clone, Copy)]
913#[non_exhaustive]
914pub struct CacheStats {
915 pub hits: u64,
917 pub misses: u64,
920 pub hit_ratio: f64,
923}
924
925pub struct ConfigValue<'a> {
927 value: Option<&'a Value>,
928}
929
930impl<'a> ConfigValue<'a> {
931 fn new(value: Option<&'a Value>) -> Self {
932 Self { value }
933 }
934
935 pub fn as_string(&self) -> Result<String> {
937 match self.value {
938 Some(v) => v.as_string().map(|s| s.to_string()),
939 None => Err(Error::key_not_found("value not found")),
940 }
941 }
942
943 pub fn as_string_or(&self, default: &str) -> String {
945 self.value
946 .and_then(|v| v.as_string().ok())
947 .map(|s| s.to_string())
948 .unwrap_or_else(|| default.to_string())
949 }
950
951 pub fn as_integer(&self) -> Result<i64> {
953 match self.value {
954 Some(v) => v.as_integer(),
955 None => Err(Error::key_not_found("value not found")),
956 }
957 }
958
959 pub fn as_integer_or(&self, default: i64) -> i64 {
961 self.value
962 .and_then(|v| v.as_integer().ok())
963 .unwrap_or(default)
964 }
965
966 pub fn as_bool(&self) -> Result<bool> {
968 match self.value {
969 Some(v) => v.as_bool(),
970 None => Err(Error::key_not_found("value not found")),
971 }
972 }
973
974 pub fn as_bool_or(&self, default: bool) -> bool {
976 self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
977 }
978
979 pub fn exists(&self) -> bool {
981 self.value.is_some()
982 }
983
984 pub fn value(&self) -> Option<&'a Value> {
986 self.value
987 }
988}
989
990pub struct ConfigBuilder {
992 format: Option<String>,
993 #[cfg(feature = "validation")]
994 validation_rules: Option<ValidationRuleSet>,
995}
996
997impl ConfigBuilder {
998 pub fn new() -> Self {
1000 Self {
1001 format: None,
1002 #[cfg(feature = "validation")]
1003 validation_rules: None,
1004 }
1005 }
1006
1007 pub fn format<S: Into<String>>(mut self, format: S) -> Self {
1009 self.format = Some(format.into());
1010 self
1011 }
1012
1013 #[cfg(feature = "validation")]
1015 pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
1016 self.validation_rules = Some(rules);
1017 self
1018 }
1019
1020 pub fn from_string(self, source: &str) -> Result<Config> {
1022 #[cfg(feature = "validation")]
1023 let mut config = Config::from_string(source, self.format.as_deref())?;
1024 #[cfg(not(feature = "validation"))]
1025 let config = Config::from_string(source, self.format.as_deref())?;
1026
1027 #[cfg(feature = "validation")]
1028 if let Some(rules) = self.validation_rules {
1029 config.set_validation_rules(rules);
1030 }
1031
1032 Ok(config)
1033 }
1034
1035 pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
1037 #[cfg(feature = "validation")]
1038 let mut config = Config::from_file(path)?;
1039 #[cfg(not(feature = "validation"))]
1040 let config = Config::from_file(path)?;
1041
1042 #[cfg(feature = "validation")]
1043 if let Some(rules) = self.validation_rules {
1044 config.set_validation_rules(rules);
1045 }
1046
1047 Ok(config)
1048 }
1049}
1050
1051impl Default for ConfigBuilder {
1052 fn default() -> Self {
1053 Self::new()
1054 }
1055}
1056
1057impl From<Value> for Config {
1059 fn from(value: Value) -> Self {
1060 Self {
1061 values: value,
1062 file_path: None,
1063 format: "conf".to_string(),
1064 modified: false,
1065 options: ConfigOptions::default(),
1066 cache_hits: AtomicU64::new(0),
1067 cache_misses: AtomicU64::new(0),
1068 cache: DashMap::new(),
1069 defaults: Arc::new(RwLock::new(BTreeMap::new())),
1070 #[cfg(feature = "noml")]
1071 noml_document: None,
1072 #[cfg(feature = "validation")]
1073 validation_rules: None,
1074 }
1075 }
1076}
1077
1078#[cfg(any(feature = "toml", feature = "noml"))]
1080mod toml_writer {
1081 use crate::error::{Error, Result};
1082 use crate::value::Value;
1083 use std::collections::BTreeMap;
1084 use std::fmt::Write;
1085
1086 fn is_table_array(value: &Value) -> bool {
1087 matches!(value, Value::Array(items)
1088 if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
1089 }
1090
1091 pub(super) fn write_table(
1093 out: &mut String,
1094 table: &BTreeMap<String, Value>,
1095 path: &mut Vec<String>,
1096 noml: bool,
1097 ) -> Result<()> {
1098 for (key, value) in table {
1099 if !matches!(value, Value::Table(_)) && !is_table_array(value) {
1100 write_key(out, key);
1101 out.push_str(" = ");
1102 write_value(out, value, path, key, noml)?;
1103 out.push('\n');
1104 }
1105 }
1106 for (key, value) in table {
1107 path.push(key.clone());
1108 match value {
1109 Value::Table(inner) => {
1110 header(out, path, false);
1111 write_table(out, inner, path, noml)?;
1112 }
1113 Value::Array(items) if is_table_array(value) => {
1114 for item in items {
1115 header(out, path, true);
1116 if let Value::Table(inner) = item {
1117 write_table(out, inner, path, noml)?;
1118 }
1119 }
1120 }
1121 _ => {}
1122 }
1123 path.pop();
1124 }
1125 Ok(())
1126 }
1127
1128 fn header(out: &mut String, path: &[String], array: bool) {
1129 if !out.is_empty() {
1130 out.push('\n');
1131 }
1132 out.push_str(if array { "[[" } else { "[" });
1133 for (i, key) in path.iter().enumerate() {
1134 if i > 0 {
1135 out.push('.');
1136 }
1137 write_key(out, key);
1138 }
1139 out.push_str(if array { "]]\n" } else { "]\n" });
1140 }
1141
1142 fn write_key(out: &mut String, key: &str) {
1143 let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1144 && key
1145 .bytes()
1146 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
1147 if bare {
1148 out.push_str(key);
1149 } else {
1150 write_string(out, key, false);
1151 }
1152 }
1153
1154 fn write_string(out: &mut String, s: &str, noml: bool) {
1155 out.push('"');
1156 let mut chars = s.chars().peekable();
1157 while let Some(c) = chars.next() {
1158 match c {
1159 '"' => out.push_str("\\\""),
1160 '\\' => out.push_str("\\\\"),
1161 '\n' => out.push_str("\\n"),
1162 '\t' => out.push_str("\\t"),
1163 '\r' => out.push_str("\\r"),
1164 '$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
1165 c if c.is_control() => {
1166 let _ = write!(out, "\\u{:04X}", c as u32);
1167 }
1168 c => out.push(c),
1169 }
1170 }
1171 out.push('"');
1172 }
1173
1174 fn write_value(
1175 out: &mut String,
1176 value: &Value,
1177 path: &[String],
1178 key: &str,
1179 noml: bool,
1180 ) -> Result<()> {
1181 match value {
1182 Value::Null if noml => out.push_str("null"),
1183 Value::Null => {
1184 let mut full = path.join(".");
1185 if !full.is_empty() {
1186 full.push('.');
1187 }
1188 full.push_str(key);
1189 return Err(Error::serialize(format!(
1190 "TOML has no null value; cannot write '{full}'"
1191 )));
1192 }
1193 Value::Bool(b) => {
1194 let _ = write!(out, "{b}");
1195 }
1196 Value::Integer(i) => {
1197 let _ = write!(out, "{i}");
1198 }
1199 Value::Float(f) => {
1200 if f.is_nan() {
1201 out.push_str("nan");
1202 } else if f.is_infinite() {
1203 out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
1204 } else {
1205 let _ = write!(out, "{f:?}");
1207 }
1208 }
1209 Value::String(s) => write_string(out, s, noml),
1210 Value::Array(items) => {
1211 out.push('[');
1212 for (i, item) in items.iter().enumerate() {
1213 if i > 0 {
1214 out.push_str(", ");
1215 }
1216 write_value(out, item, path, key, noml)?;
1217 }
1218 out.push(']');
1219 }
1220 Value::Table(table) => {
1221 out.push('{');
1222 for (i, (k, v)) in table.iter().enumerate() {
1223 out.push_str(if i > 0 { ", " } else { " " });
1224 write_key(out, k);
1225 out.push_str(" = ");
1226 write_value(out, v, path, key, noml)?;
1227 }
1228 out.push_str(if table.is_empty() { "}" } else { " }" });
1229 }
1230 #[cfg(feature = "chrono")]
1231 Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
1232 }
1233 Ok(())
1234 }
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239 use super::*;
1240
1241 #[test]
1242 fn test_config_creation() {
1243 let config = Config::new();
1244 assert!(!config.is_modified());
1245 assert_eq!(config.format(), "conf");
1246 }
1247
1248 #[test]
1249 fn test_config_from_string() {
1250 let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
1251
1252 assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
1253 assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
1254 }
1255
1256 #[test]
1257 fn test_config_modification() {
1258 let mut config = Config::new();
1259 assert!(!config.is_modified());
1260
1261 config.set("key", "value").unwrap();
1262 assert!(config.is_modified());
1263
1264 config.mark_clean();
1265 assert!(!config.is_modified());
1266 }
1267
1268 #[test]
1269 fn test_config_merge() {
1270 let mut config1 = Config::new();
1271 config1.set("a", 1).unwrap();
1272 config1.set("b.x", 2).unwrap();
1273
1274 let mut config2 = Config::new();
1275 config2.set("b.y", 3).unwrap();
1276 config2.set("c", 4).unwrap();
1277
1278 config1.merge(&config2).unwrap();
1279
1280 assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
1281 assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
1282 assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
1283 assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
1284 }
1285
1286 #[cfg(feature = "toml")]
1287 #[test]
1288 fn modified_toml_serializes_current_values() {
1289 let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
1290 let mut config = Config::from_string(source, Some("toml")).unwrap();
1291
1292 #[cfg(feature = "noml")]
1294 assert_eq!(config.serialize().unwrap(), source);
1295
1296 config.set("server.port", 8080).unwrap();
1297 config.set("path", "C:\\dir \"q\"").unwrap();
1298 let text = config.serialize().unwrap();
1299 let reloaded = Config::from_string(&text, Some("toml")).unwrap();
1300 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1301
1302 config.set("nothing", Value::Null).unwrap();
1303 assert!(config.serialize().is_err(), "TOML has no null");
1304 }
1305
1306 #[cfg(feature = "noml")]
1307 #[test]
1308 fn modified_noml_serializes_current_values() {
1309 let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
1310 let mut config = Config::from_string(source, Some("noml")).unwrap();
1311 assert_eq!(
1312 config.get("log").unwrap().as_string().unwrap(),
1313 "/var/log/app.log"
1314 );
1315
1316 config.set("template", "${not_a_reference}").unwrap();
1317 config.set("nothing", Value::Null).unwrap();
1318 let text = config.serialize().unwrap();
1319 let reloaded = Config::from_string(&text, Some("noml")).unwrap();
1320 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1321 }
1322}