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 let values = parsers::parse_string(source, Some(detected_format))?;
135 Ok(Self::from_parsed(source, detected_format, values))
136 }
137
138 pub fn from_string_strict(source: &str, format: Option<&str>) -> Result<Self> {
169 let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
170 let values = parsers::parse_string_strict(source, Some(detected_format))?;
171 Ok(Self::from_parsed(source, detected_format, values))
172 }
173
174 fn from_parsed(source: &str, detected_format: &str, values: Value) -> Self {
176 #[cfg(not(feature = "noml"))]
177 let _ = source;
178
179 #[cfg(feature = "noml")]
180 let mut config = Self {
181 values,
182 file_path: None,
183 format: detected_format.to_string(),
184 modified: false,
185 options: ConfigOptions::default(),
186 cache_hits: AtomicU64::new(0),
187 cache_misses: AtomicU64::new(0),
188 cache: DashMap::new(),
189 defaults: Arc::new(RwLock::new(BTreeMap::new())),
190 noml_document: None,
191 #[cfg(feature = "validation")]
192 validation_rules: None,
193 };
194
195 #[cfg(not(feature = "noml"))]
196 let config = Self {
197 values,
198 file_path: None,
199 format: detected_format.to_string(),
200 modified: false,
201 options: ConfigOptions::default(),
202 cache_hits: AtomicU64::new(0),
203 cache_misses: AtomicU64::new(0),
204 cache: DashMap::new(),
205 defaults: Arc::new(RwLock::new(BTreeMap::new())),
206 #[cfg(feature = "validation")]
207 validation_rules: None,
208 };
209
210 #[cfg(feature = "noml")]
213 if detected_format == "noml" || detected_format == "toml" {
214 if let Ok(document) = noml::parse_string(source, None) {
215 config.noml_document = Some(document);
216 }
217 }
218
219 config
220 }
221
222 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
224 let path = path.as_ref();
225 let content =
226 std::fs::read_to_string(path).map_err(|e| Error::io(path.display().to_string(), e))?;
227
228 let format = parsers::detect_format_from_path(path)
229 .unwrap_or_else(|| parsers::detect_format(&content));
230
231 let mut config = Self::from_string(&content, Some(format))?;
232 config.file_path = Some(path.to_path_buf());
233
234 Ok(config)
235 }
236
237 #[cfg(feature = "async")]
239 pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
240 let path = path.as_ref();
241 let content = tokio::fs::read_to_string(path)
242 .await
243 .map_err(|e| Error::io(path.display().to_string(), e))?;
244
245 let format = parsers::detect_format_from_path(path)
246 .unwrap_or_else(|| parsers::detect_format(&content));
247
248 let mut config = Self::from_string(&content, Some(format))?;
249 config.file_path = Some(path.to_path_buf());
250
251 Ok(config)
252 }
253
254 pub fn get(&self, path: &str) -> Option<&Value> {
256 self.values.get(path)
257 }
258
259 pub fn get_mut(&mut self, path: &str) -> Result<&mut Value> {
261 self.values.get_mut_nested(path)
262 }
263
264 pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()> {
276 self.ensure_writable()?;
277 self.values.set_nested(path, value.into())?;
278 self.modified = true;
279 self.cache.clear();
280 Ok(())
281 }
282
283 pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
293 self.ensure_writable()?;
294 let result = self.values.remove(path)?;
295 if result.is_some() {
296 self.modified = true;
297 self.cache.clear();
298 }
299 Ok(result)
300 }
301
302 pub fn contains_key(&self, path: &str) -> bool {
304 self.values.contains_key(path)
305 }
306
307 pub fn keys(&self) -> Result<Vec<&str>> {
309 self.values.keys()
310 }
311
312 pub fn is_modified(&self) -> bool {
314 self.modified
315 }
316
317 pub fn mark_clean(&mut self) {
319 self.modified = false;
320 }
321
322 pub fn format(&self) -> &str {
324 &self.format
325 }
326
327 pub fn file_path(&self) -> Option<&Path> {
329 self.file_path.as_deref()
330 }
331
332 pub fn save(&mut self) -> Result<()> {
334 match &self.file_path {
335 Some(path) => {
336 self.save_to_file(path.clone())?;
337 self.modified = false;
338 Ok(())
339 }
340 None => Err(Error::internal(
341 "Cannot save configuration that wasn't loaded from a file",
342 )),
343 }
344 }
345
346 pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
348 let serialized = self.serialize()?;
349 std::fs::write(path, serialized).map_err(|e| Error::io("save".to_string(), e))?;
350 Ok(())
351 }
352
353 #[cfg(feature = "async")]
355 pub async fn save_async(&mut self) -> Result<()> {
356 match &self.file_path {
357 Some(path) => {
358 self.save_to_file_async(path.clone()).await?;
359 self.modified = false;
360 Ok(())
361 }
362 None => Err(Error::internal(
363 "Cannot save configuration that wasn't loaded from a file",
364 )),
365 }
366 }
367
368 #[cfg(feature = "async")]
370 pub async fn save_to_file_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
371 let serialized = self.serialize()?;
372 tokio::fs::write(path, serialized)
373 .await
374 .map_err(|e| Error::io("save".to_string(), e))?;
375 Ok(())
376 }
377
378 pub fn serialize(&self) -> Result<String> {
380 match self.format.as_str() {
381 "json" => {
382 #[cfg(any(feature = "json", feature = "jsonx"))]
383 return crate::parsers::json_parser::serialize(&self.values);
384 #[cfg(not(any(feature = "json", feature = "jsonx")))]
385 return Err(Error::feature_not_enabled("json"));
386 }
387 "toml" => {
388 #[cfg(feature = "toml")]
389 {
390 #[cfg(feature = "noml")]
393 if !self.modified {
394 if let Some(ref document) = self.noml_document {
395 return Ok(noml::serialize_document(document)?);
396 }
397 }
398 self.serialize_as_toml(false)
399 }
400 #[cfg(not(feature = "toml"))]
401 return Err(Error::feature_not_enabled("toml"));
402 }
403 "noml" => {
404 #[cfg(feature = "noml")]
405 {
406 if !self.modified {
407 if let Some(ref document) = self.noml_document {
408 return Ok(noml::serialize_document(document)?);
409 }
410 }
411 self.serialize_as_toml(true)
412 }
413 #[cfg(not(feature = "noml"))]
414 return Err(Error::feature_not_enabled("noml"));
415 }
416 "conf" => self.serialize_as_conf(),
417 _ => Err(Error::unknown_format(&self.format)),
418 }
419 }
420
421 fn serialize_as_conf(&self) -> Result<String> {
423 let mut output = String::new();
424 if let Value::Table(table) = &self.values {
425 self.write_conf_table(&mut output, table, "")?;
426 }
427 Ok(output)
428 }
429
430 fn write_conf_table(
432 &self,
433 output: &mut String,
434 table: &BTreeMap<String, Value>,
435 section_prefix: &str,
436 ) -> Result<()> {
437 for (key, value) in table {
439 if !value.is_table() {
440 let formatted_value = self.format_conf_value(value)?;
441 output.push_str(&format!("{key} = {formatted_value}\n"));
442 }
443 }
444
445 for (key, value) in table {
447 if let Value::Table(nested_table) = value {
448 let section_name = if section_prefix.is_empty() {
449 key.clone()
450 } else {
451 format!("{section_prefix}.{key}")
452 };
453
454 output.push_str(&format!("\n[{section_name}]\n"));
455 self.write_conf_table(output, nested_table, §ion_name)?;
456 }
457 }
458
459 Ok(())
460 }
461
462 #[allow(clippy::only_used_in_recursion)]
464 fn format_conf_value(&self, value: &Value) -> Result<String> {
465 match value {
466 Value::Null => Ok("null".to_string()),
467 Value::Bool(b) => Ok(b.to_string()),
468 Value::Integer(i) => Ok(i.to_string()),
469 Value::Float(f) => Ok(f.to_string()),
470 Value::String(s) => {
471 if s.contains(' ') || s.contains('\t') || s.contains('\n') {
472 Ok(format!("\"{}\"", s.replace('"', "\\\"")))
473 } else {
474 Ok(s.clone())
475 }
476 }
477 Value::Array(arr) => {
478 let items: Result<Vec<String>> =
479 arr.iter().map(|v| self.format_conf_value(v)).collect();
480 Ok(items?.join(" "))
481 }
482 Value::Table(_) => Err(Error::type_error(
483 "Cannot serialize nested table as value",
484 "primitive",
485 "table",
486 )),
487 #[cfg(feature = "chrono")]
488 Value::DateTime(dt) => Ok(dt.to_rfc3339()),
489 }
490 }
491
492 #[cfg(any(feature = "toml", feature = "noml"))]
499 fn serialize_as_toml(&self, noml: bool) -> Result<String> {
500 let mut out = String::new();
501 if let Value::Table(table) = &self.values {
502 toml_writer::write_table(&mut out, table, &mut Vec::new(), noml)?;
503 }
504 Ok(out)
505 }
506
507 #[cfg(feature = "schema")]
509 pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
510 schema.validate(&self.values)
511 }
512
513 pub fn as_value(&self) -> &Value {
515 &self.values
516 }
517
518 pub fn merge(&mut self, other: &Config) -> Result<()> {
527 self.ensure_writable()?;
528 self.merge_value(&other.values)?;
529 self.modified = true;
530 self.cache.clear();
531 Ok(())
532 }
533
534 fn merge_value(&mut self, other: &Value) -> Result<()> {
536 match (&mut self.values, other) {
537 (Value::Table(self_table), Value::Table(other_table)) => {
538 for (key, other_value) in other_table {
539 match self_table.get_mut(key) {
540 Some(self_value) => {
541 if let (Value::Table(_), Value::Table(_)) = (&*self_value, other_value)
542 {
543 let mut temp_config = Config::new();
545 temp_config.values = self_value.clone();
546 temp_config.merge_value(other_value)?;
547 *self_value = temp_config.values;
548 } else {
549 *self_value = other_value.clone();
551 }
552 }
553 None => {
554 self_table.insert(key.clone(), other_value.clone());
556 }
557 }
558 }
559 }
560 _ => {
561 self.values = other.clone();
563 }
564 }
565 Ok(())
566 }
567
568 pub fn key(&self, path: &str) -> ConfigValue<'_> {
576 ConfigValue::new(self.get(path))
577 }
578
579 pub fn has(&self, path: &str) -> bool {
581 self.contains_key(path)
582 }
583
584 pub fn get_or<V>(&self, path: &str, default: V) -> V
586 where
587 V: TryFrom<Value> + Clone,
588 V::Error: std::fmt::Debug,
589 {
590 self.get(path)
591 .and_then(|v| V::try_from(v.clone()).ok())
592 .unwrap_or(default)
593 }
594
595 #[cfg(feature = "validation")]
599 pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
600 self.validation_rules = Some(rules);
601 }
602
603 #[cfg(feature = "validation")]
605 pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
606 match &mut self.validation_rules {
607 Some(rules) => {
608 if let Value::Table(table) = &self.values {
609 let mut errors = Vec::new();
610
611 for (key, value) in table {
613 errors.extend(rules.validate(key, value));
614 }
615
616 Ok(errors)
620 } else {
621 Err(Error::validation(
622 "Configuration root must be a table for validation",
623 ))
624 }
625 }
626 None => Ok(Vec::new()), }
628 }
629
630 #[cfg(feature = "validation")]
632 pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
633 let all_errors = self.validate()?;
634 Ok(all_errors
635 .into_iter()
636 .filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
637 .collect())
638 }
639
640 #[cfg(feature = "validation")]
642 pub fn is_valid(&mut self) -> Result<bool> {
643 let critical_errors = self.validate_critical_only()?;
644 Ok(critical_errors.is_empty())
645 }
646
647 #[cfg(feature = "validation")]
649 pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
650 let value = self
652 .get(path)
653 .ok_or_else(|| Error::key_not_found(path))?
654 .clone();
655
656 match &mut self.validation_rules {
657 Some(rules) => Ok(rules.validate(path, &value)),
658 None => Ok(Vec::new()),
659 }
660 }
661}
662
663impl Default for Config {
664 fn default() -> Self {
665 Self::new()
666 }
667}
668
669#[derive(Debug, Clone)]
701#[non_exhaustive]
702pub struct ConfigOptions {
703 pub read_only: bool,
707
708 pub cache_enabled: bool,
713
714 pub cache_capacity: usize,
717}
718
719impl Default for ConfigOptions {
720 fn default() -> Self {
724 Self {
725 read_only: false,
726 cache_enabled: true,
727 cache_capacity: 1024,
728 }
729 }
730}
731
732impl ConfigOptions {
733 pub fn new() -> Self {
736 Self::default()
737 }
738
739 pub fn read_only(mut self, read_only: bool) -> Self {
741 self.read_only = read_only;
742 self
743 }
744
745 pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
749 self.cache_enabled = cache_enabled;
750 self
751 }
752
753 pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
756 self.cache_capacity = cache_capacity;
757 self
758 }
759}
760
761impl Config {
762 pub fn with_options(options: ConfigOptions) -> Self {
768 let mut config = Self::new();
769 config.options = options;
770 config
771 }
772
773 pub fn options(&self) -> &ConfigOptions {
775 &self.options
776 }
777
778 pub fn is_read_only(&self) -> bool {
781 self.options.read_only
782 }
783
784 fn ensure_writable(&self) -> Result<()> {
787 if self.options.read_only {
788 Err(Error::general("Configuration is read-only"))
789 } else {
790 Ok(())
791 }
792 }
793
794 pub fn cache_stats(&self) -> CacheStats {
800 let hits = self.cache_hits.load(Ordering::Relaxed);
801 let misses = self.cache_misses.load(Ordering::Relaxed);
802 let total = hits.saturating_add(misses);
803 let hit_ratio = if total == 0 {
804 0.0
805 } else {
806 hits as f64 / total as f64
807 };
808 CacheStats {
809 hits,
810 misses,
811 hit_ratio,
812 }
813 }
814
815 pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
842 if self.options.cache_enabled {
843 if let Some(entry) = self.cache.get(path) {
844 self.cache_hits.fetch_add(1, Ordering::Relaxed);
845 return Some(Arc::clone(entry.value()));
846 }
847 self.cache_misses.fetch_add(1, Ordering::Relaxed);
848 let resolved = self.values.get(path)?.clone();
849 let arc = Arc::new(resolved);
850 self.cache.insert(path.into(), Arc::clone(&arc));
851 Some(arc)
852 } else {
853 self.cache_misses.fetch_add(1, Ordering::Relaxed);
854 Some(Arc::new(self.values.get(path)?.clone()))
855 }
856 }
857
858 pub fn clear_cache(&self) {
864 self.cache.clear();
865 }
866
867 pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
884 let mut defaults = self
885 .defaults
886 .write()
887 .map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
888 defaults.insert(path.to_string(), value.into());
889 Ok(())
890 }
891
892 pub fn get_or_default(&self, path: &str) -> Option<Value> {
901 if let Some(v) = self.values.get(path) {
902 return Some(v.clone());
903 }
904 let defaults = self.defaults.read().ok()?;
905 defaults.get(path).cloned()
906 }
907
908 pub fn make_read_only(&mut self) {
921 self.options.read_only = true;
922 }
923}
924
925#[derive(Debug, Clone, Copy)]
956#[non_exhaustive]
957pub struct CacheStats {
958 pub hits: u64,
960 pub misses: u64,
963 pub hit_ratio: f64,
966}
967
968pub struct ConfigValue<'a> {
970 value: Option<&'a Value>,
971}
972
973impl<'a> ConfigValue<'a> {
974 fn new(value: Option<&'a Value>) -> Self {
975 Self { value }
976 }
977
978 pub fn as_string(&self) -> Result<String> {
980 match self.value {
981 Some(v) => v.as_string().map(|s| s.to_string()),
982 None => Err(Error::key_not_found("value not found")),
983 }
984 }
985
986 pub fn as_string_or(&self, default: &str) -> String {
988 self.value
989 .and_then(|v| v.as_string().ok())
990 .map(|s| s.to_string())
991 .unwrap_or_else(|| default.to_string())
992 }
993
994 pub fn as_integer(&self) -> Result<i64> {
996 match self.value {
997 Some(v) => v.as_integer(),
998 None => Err(Error::key_not_found("value not found")),
999 }
1000 }
1001
1002 pub fn as_integer_or(&self, default: i64) -> i64 {
1004 self.value
1005 .and_then(|v| v.as_integer().ok())
1006 .unwrap_or(default)
1007 }
1008
1009 pub fn as_bool(&self) -> Result<bool> {
1011 match self.value {
1012 Some(v) => v.as_bool(),
1013 None => Err(Error::key_not_found("value not found")),
1014 }
1015 }
1016
1017 pub fn as_bool_or(&self, default: bool) -> bool {
1019 self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
1020 }
1021
1022 pub fn exists(&self) -> bool {
1024 self.value.is_some()
1025 }
1026
1027 pub fn value(&self) -> Option<&'a Value> {
1029 self.value
1030 }
1031}
1032
1033pub struct ConfigBuilder {
1035 format: Option<String>,
1036 #[cfg(feature = "validation")]
1037 validation_rules: Option<ValidationRuleSet>,
1038}
1039
1040impl ConfigBuilder {
1041 pub fn new() -> Self {
1043 Self {
1044 format: None,
1045 #[cfg(feature = "validation")]
1046 validation_rules: None,
1047 }
1048 }
1049
1050 pub fn format<S: Into<String>>(mut self, format: S) -> Self {
1052 self.format = Some(format.into());
1053 self
1054 }
1055
1056 #[cfg(feature = "validation")]
1058 pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
1059 self.validation_rules = Some(rules);
1060 self
1061 }
1062
1063 pub fn from_string(self, source: &str) -> Result<Config> {
1065 #[cfg(feature = "validation")]
1066 let mut config = Config::from_string(source, self.format.as_deref())?;
1067 #[cfg(not(feature = "validation"))]
1068 let config = Config::from_string(source, self.format.as_deref())?;
1069
1070 #[cfg(feature = "validation")]
1071 if let Some(rules) = self.validation_rules {
1072 config.set_validation_rules(rules);
1073 }
1074
1075 Ok(config)
1076 }
1077
1078 pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
1080 #[cfg(feature = "validation")]
1081 let mut config = Config::from_file(path)?;
1082 #[cfg(not(feature = "validation"))]
1083 let config = Config::from_file(path)?;
1084
1085 #[cfg(feature = "validation")]
1086 if let Some(rules) = self.validation_rules {
1087 config.set_validation_rules(rules);
1088 }
1089
1090 Ok(config)
1091 }
1092}
1093
1094impl Default for ConfigBuilder {
1095 fn default() -> Self {
1096 Self::new()
1097 }
1098}
1099
1100impl From<Value> for Config {
1102 fn from(value: Value) -> Self {
1103 Self {
1104 values: value,
1105 file_path: None,
1106 format: "conf".to_string(),
1107 modified: false,
1108 options: ConfigOptions::default(),
1109 cache_hits: AtomicU64::new(0),
1110 cache_misses: AtomicU64::new(0),
1111 cache: DashMap::new(),
1112 defaults: Arc::new(RwLock::new(BTreeMap::new())),
1113 #[cfg(feature = "noml")]
1114 noml_document: None,
1115 #[cfg(feature = "validation")]
1116 validation_rules: None,
1117 }
1118 }
1119}
1120
1121#[cfg(any(feature = "toml", feature = "noml"))]
1123mod toml_writer {
1124 use crate::error::{Error, Result};
1125 use crate::value::Value;
1126 use std::collections::BTreeMap;
1127 use std::fmt::Write;
1128
1129 fn is_table_array(value: &Value) -> bool {
1130 matches!(value, Value::Array(items)
1131 if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
1132 }
1133
1134 pub(super) fn write_table(
1136 out: &mut String,
1137 table: &BTreeMap<String, Value>,
1138 path: &mut Vec<String>,
1139 noml: bool,
1140 ) -> Result<()> {
1141 for (key, value) in table {
1142 if !matches!(value, Value::Table(_)) && !is_table_array(value) {
1143 write_key(out, key);
1144 out.push_str(" = ");
1145 write_value(out, value, path, key, noml)?;
1146 out.push('\n');
1147 }
1148 }
1149 for (key, value) in table {
1150 path.push(key.clone());
1151 match value {
1152 Value::Table(inner) => {
1153 header(out, path, false);
1154 write_table(out, inner, path, noml)?;
1155 }
1156 Value::Array(items) if is_table_array(value) => {
1157 for item in items {
1158 header(out, path, true);
1159 if let Value::Table(inner) = item {
1160 write_table(out, inner, path, noml)?;
1161 }
1162 }
1163 }
1164 _ => {}
1165 }
1166 path.pop();
1167 }
1168 Ok(())
1169 }
1170
1171 fn header(out: &mut String, path: &[String], array: bool) {
1172 if !out.is_empty() {
1173 out.push('\n');
1174 }
1175 out.push_str(if array { "[[" } else { "[" });
1176 for (i, key) in path.iter().enumerate() {
1177 if i > 0 {
1178 out.push('.');
1179 }
1180 write_key(out, key);
1181 }
1182 out.push_str(if array { "]]\n" } else { "]\n" });
1183 }
1184
1185 fn write_key(out: &mut String, key: &str) {
1186 let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1187 && key
1188 .bytes()
1189 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
1190 if bare {
1191 out.push_str(key);
1192 } else {
1193 write_string(out, key, false);
1194 }
1195 }
1196
1197 fn write_string(out: &mut String, s: &str, noml: bool) {
1198 out.push('"');
1199 let mut chars = s.chars().peekable();
1200 while let Some(c) = chars.next() {
1201 match c {
1202 '"' => out.push_str("\\\""),
1203 '\\' => out.push_str("\\\\"),
1204 '\n' => out.push_str("\\n"),
1205 '\t' => out.push_str("\\t"),
1206 '\r' => out.push_str("\\r"),
1207 '$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
1208 c if c.is_control() => {
1209 let _ = write!(out, "\\u{:04X}", c as u32);
1210 }
1211 c => out.push(c),
1212 }
1213 }
1214 out.push('"');
1215 }
1216
1217 fn write_value(
1218 out: &mut String,
1219 value: &Value,
1220 path: &[String],
1221 key: &str,
1222 noml: bool,
1223 ) -> Result<()> {
1224 match value {
1225 Value::Null if noml => out.push_str("null"),
1226 Value::Null => {
1227 let mut full = path.join(".");
1228 if !full.is_empty() {
1229 full.push('.');
1230 }
1231 full.push_str(key);
1232 return Err(Error::serialize(format!(
1233 "TOML has no null value; cannot write '{full}'"
1234 )));
1235 }
1236 Value::Bool(b) => {
1237 let _ = write!(out, "{b}");
1238 }
1239 Value::Integer(i) => {
1240 let _ = write!(out, "{i}");
1241 }
1242 Value::Float(f) => {
1243 if f.is_nan() {
1244 out.push_str("nan");
1245 } else if f.is_infinite() {
1246 out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
1247 } else {
1248 let _ = write!(out, "{f:?}");
1250 }
1251 }
1252 Value::String(s) => write_string(out, s, noml),
1253 Value::Array(items) => {
1254 out.push('[');
1255 for (i, item) in items.iter().enumerate() {
1256 if i > 0 {
1257 out.push_str(", ");
1258 }
1259 write_value(out, item, path, key, noml)?;
1260 }
1261 out.push(']');
1262 }
1263 Value::Table(table) => {
1264 out.push('{');
1265 for (i, (k, v)) in table.iter().enumerate() {
1266 out.push_str(if i > 0 { ", " } else { " " });
1267 write_key(out, k);
1268 out.push_str(" = ");
1269 write_value(out, v, path, key, noml)?;
1270 }
1271 out.push_str(if table.is_empty() { "}" } else { " }" });
1272 }
1273 #[cfg(feature = "chrono")]
1274 Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
1275 }
1276 Ok(())
1277 }
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282 use super::*;
1283
1284 #[test]
1285 fn test_config_creation() {
1286 let config = Config::new();
1287 assert!(!config.is_modified());
1288 assert_eq!(config.format(), "conf");
1289 }
1290
1291 #[test]
1292 fn test_config_from_string() {
1293 let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
1294
1295 assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
1296 assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
1297 }
1298
1299 #[test]
1300 fn test_config_modification() {
1301 let mut config = Config::new();
1302 assert!(!config.is_modified());
1303
1304 config.set("key", "value").unwrap();
1305 assert!(config.is_modified());
1306
1307 config.mark_clean();
1308 assert!(!config.is_modified());
1309 }
1310
1311 #[test]
1312 fn test_config_merge() {
1313 let mut config1 = Config::new();
1314 config1.set("a", 1).unwrap();
1315 config1.set("b.x", 2).unwrap();
1316
1317 let mut config2 = Config::new();
1318 config2.set("b.y", 3).unwrap();
1319 config2.set("c", 4).unwrap();
1320
1321 config1.merge(&config2).unwrap();
1322
1323 assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
1324 assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
1325 assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
1326 assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
1327 }
1328
1329 #[cfg(feature = "toml")]
1330 #[test]
1331 fn modified_toml_serializes_current_values() {
1332 let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
1333 let mut config = Config::from_string(source, Some("toml")).unwrap();
1334
1335 #[cfg(feature = "noml")]
1337 assert_eq!(config.serialize().unwrap(), source);
1338
1339 config.set("server.port", 8080).unwrap();
1340 config.set("path", "C:\\dir \"q\"").unwrap();
1341 let text = config.serialize().unwrap();
1342 let reloaded = Config::from_string(&text, Some("toml")).unwrap();
1343 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1344
1345 config.set("nothing", Value::Null).unwrap();
1346 assert!(config.serialize().is_err(), "TOML has no null");
1347 }
1348
1349 #[cfg(feature = "noml")]
1350 #[test]
1351 fn modified_noml_serializes_current_values() {
1352 let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
1353 let mut config = Config::from_string(source, Some("noml")).unwrap();
1354 assert_eq!(
1355 config.get("log").unwrap().as_string().unwrap(),
1356 "/var/log/app.log"
1357 );
1358
1359 config.set("template", "${not_a_reference}").unwrap();
1360 config.set("nothing", Value::Null).unwrap();
1361 let text = config.serialize().unwrap();
1362 let reloaded = Config::from_string(&text, Some("noml")).unwrap();
1363 assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
1364 }
1365}