use crate::error::{Error, Result};
use crate::load::{self, LoadOptions};
use crate::parsers;
use crate::value::Value;
use dashmap::DashMap;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
#[cfg(feature = "schema")]
use crate::schema::Schema;
#[cfg(feature = "validation")]
use crate::validation::{ValidationError, ValidationRuleSet};
#[derive(Debug)]
pub struct Config {
values: Value,
file_path: Option<PathBuf>,
format: String,
modified: bool,
options: ConfigOptions,
cache_hits: AtomicU64,
cache_misses: AtomicU64,
cache: DashMap<Box<str>, Arc<Value>>,
defaults: Arc<RwLock<BTreeMap<String, Value>>>,
#[cfg(feature = "noml")]
noml_document: Option<noml::Document>,
#[cfg(feature = "validation")]
validation_rules: Option<ValidationRuleSet>,
}
impl Config {
pub fn new() -> Self {
Self {
values: Value::table(BTreeMap::new()),
file_path: None,
format: "conf".to_string(),
modified: false,
options: ConfigOptions::default(),
cache_hits: AtomicU64::new(0),
cache_misses: AtomicU64::new(0),
cache: new_cache(),
defaults: Arc::new(RwLock::new(BTreeMap::new())),
#[cfg(feature = "noml")]
noml_document: None,
#[cfg(feature = "validation")]
validation_rules: None,
}
}
pub fn from_string(source: &str, format: Option<&str>) -> Result<Self> {
Self::from_string_with(source, format, &LoadOptions::default())
}
pub fn from_string_with(
source: &str,
format: Option<&str>,
options: &LoadOptions,
) -> Result<Self> {
let detected_format = format.unwrap_or_else(|| parsers::detect_format(source));
let values = parsers::parse_string_with(source, Some(detected_format), None, options)?;
Ok(Self::from_parsed(source, detected_format, values))
}
pub fn from_string_strict(source: &str, format: Option<&str>) -> Result<Self> {
Self::from_string_with(source, format, &LoadOptions::strict_defaults())
}
fn from_parsed(source: &str, detected_format: &str, values: Value) -> Self {
#[cfg(not(feature = "noml"))]
let _ = source;
#[cfg(feature = "noml")]
let mut config = Self {
values,
file_path: None,
format: detected_format.to_string(),
modified: false,
options: ConfigOptions::default(),
cache_hits: AtomicU64::new(0),
cache_misses: AtomicU64::new(0),
cache: new_cache(),
defaults: Arc::new(RwLock::new(BTreeMap::new())),
noml_document: None,
#[cfg(feature = "validation")]
validation_rules: None,
};
#[cfg(not(feature = "noml"))]
let config = Self {
values,
file_path: None,
format: detected_format.to_string(),
modified: false,
options: ConfigOptions::default(),
cache_hits: AtomicU64::new(0),
cache_misses: AtomicU64::new(0),
cache: new_cache(),
defaults: Arc::new(RwLock::new(BTreeMap::new())),
#[cfg(feature = "validation")]
validation_rules: None,
};
#[cfg(feature = "noml")]
if detected_format == "noml" || detected_format == "toml" {
if let Ok(document) = noml::parse_string(source, None) {
config.noml_document = Some(document);
}
}
config
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::from_file_with(path, &LoadOptions::default())
}
pub fn from_file_strict<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::from_file_with(path, &LoadOptions::strict_defaults())
}
pub fn from_file_with<P: AsRef<Path>>(path: P, options: &LoadOptions) -> Result<Self> {
let path = path.as_ref();
let content = load::read_file(path, options.max_file_size)?;
Self::from_file_content(path, &content, options)
}
fn from_file_content(path: &Path, content: &str, options: &LoadOptions) -> Result<Self> {
let format = parsers::file_format(path, content);
let values = parsers::parse_string_with(content, Some(format), Some(path), options)?;
let mut config = Self::from_parsed(content, format, values);
config.file_path = Some(path.to_path_buf());
Ok(config)
}
#[cfg(feature = "async")]
pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let options = LoadOptions::default();
let content = load::read_file_async(path, options.max_file_size).await?;
Self::from_file_content(path, &content, &options)
}
pub fn get(&self, path: &str) -> Option<&Value> {
self.values.get(path)
}
pub fn get_mut(&mut self, path: &str) -> Result<&mut Value> {
self.ensure_writable()?;
let value = self.values.get_mut_nested(path)?;
self.modified = true;
self.cache.clear();
Ok(value)
}
pub fn set<V: Into<Value>>(&mut self, path: &str, value: V) -> Result<()> {
self.ensure_writable()?;
self.values.set_nested(path, value.into())?;
self.modified = true;
self.cache.clear();
Ok(())
}
pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
self.ensure_writable()?;
let result = self.values.remove(path)?;
if result.is_some() {
self.modified = true;
self.cache.clear();
}
Ok(result)
}
pub fn contains_key(&self, path: &str) -> bool {
self.values.contains_key(path)
}
pub fn keys(&self) -> Result<Vec<&str>> {
self.values.keys()
}
pub fn is_modified(&self) -> bool {
self.modified
}
pub fn mark_clean(&mut self) {
self.modified = false;
}
pub fn format(&self) -> &str {
&self.format
}
pub fn file_path(&self) -> Option<&Path> {
self.file_path.as_deref()
}
pub fn save(&mut self) -> Result<()> {
match &self.file_path {
Some(path) => {
self.save_to_file(path.clone())?;
self.modified = false;
Ok(())
}
None => Err(Error::internal(
"Cannot save configuration that wasn't loaded from a file",
)),
}
}
pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let serialized = self.serialize()?;
atomic_write(path.as_ref(), serialized.as_bytes())
}
#[cfg(feature = "async")]
pub async fn save_async(&mut self) -> Result<()> {
match &self.file_path {
Some(path) => {
self.save_to_file_async(path.clone()).await?;
self.modified = false;
Ok(())
}
None => Err(Error::internal(
"Cannot save configuration that wasn't loaded from a file",
)),
}
}
#[cfg(feature = "async")]
pub async fn save_to_file_async<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let serialized = self.serialize()?;
let path = path.as_ref().to_path_buf();
tokio::task::spawn_blocking(move || atomic_write(&path, serialized.as_bytes()))
.await
.map_err(|_| Error::internal("save task failed"))?
}
pub fn serialize(&self) -> Result<String> {
match self.format.as_str() {
"json" => {
#[cfg(any(feature = "json", feature = "jsonx"))]
return crate::parsers::json_parser::serialize(&self.values);
#[cfg(not(any(feature = "json", feature = "jsonx")))]
return Err(Error::feature_not_enabled("json"));
}
"toml" => {
#[cfg(feature = "toml")]
{
#[cfg(feature = "noml")]
if !self.modified {
if let Some(ref document) = self.noml_document {
return Ok(noml::serialize_document(document)?);
}
}
self.serialize_as_toml(false)
}
#[cfg(not(feature = "toml"))]
return Err(Error::feature_not_enabled("toml"));
}
"noml" => {
#[cfg(feature = "noml")]
{
if !self.modified {
if let Some(ref document) = self.noml_document {
return Ok(noml::serialize_document(document)?);
}
}
self.serialize_as_toml(true)
}
#[cfg(not(feature = "noml"))]
return Err(Error::feature_not_enabled("noml"));
}
"conf" => self.serialize_as_conf(),
_ => Err(Error::unknown_format(&self.format)),
}
}
fn serialize_as_conf(&self) -> Result<String> {
let mut output = String::new();
if let Value::Table(table) = &self.values {
conf_writer::write_table(&mut output, table, &mut Vec::new())?;
}
Ok(output)
}
#[cfg(any(feature = "toml", feature = "noml"))]
fn serialize_as_toml(&self, noml: bool) -> Result<String> {
let mut out = String::new();
if let Value::Table(table) = &self.values {
toml_writer::write_table(&mut out, table, &mut Vec::new(), noml)?;
}
Ok(out)
}
#[cfg(feature = "schema")]
pub fn validate_schema(&self, schema: &Schema) -> Result<()> {
schema.validate(&self.values)
}
pub fn as_value(&self) -> &Value {
&self.values
}
pub fn merge(&mut self, other: &Config) -> Result<()> {
self.ensure_writable()?;
self.merge_value(&other.values)?;
self.modified = true;
self.cache.clear();
Ok(())
}
fn merge_value(&mut self, other: &Value) -> Result<()> {
merge_in_place(&mut self.values, other);
Ok(())
}
pub(crate) fn inherit_runtime_state(&mut self, old: &mut Config) {
self.options = old.options.clone();
self.defaults = Arc::clone(&old.defaults);
#[cfg(feature = "validation")]
{
self.validation_rules = old.validation_rules.take();
}
}
#[cfg(feature = "validation")]
pub(crate) fn return_validation_rules(&mut self, old: &mut Config) {
old.validation_rules = self.validation_rules.take();
}
pub(crate) fn is_empty(&self) -> bool {
match &self.values {
Value::Table(table) => table.is_empty(),
Value::Null => true,
_ => false,
}
}
pub fn key(&self, path: &str) -> ConfigValue<'_> {
ConfigValue::new(self.get(path))
}
pub fn has(&self, path: &str) -> bool {
self.contains_key(path)
}
pub fn get_or<V>(&self, path: &str, default: V) -> V
where
V: TryFrom<Value> + Clone,
V::Error: std::fmt::Debug,
{
self.get(path)
.and_then(|v| V::try_from(v.clone()).ok())
.unwrap_or(default)
}
#[cfg(feature = "validation")]
pub fn set_validation_rules(&mut self, rules: ValidationRuleSet) {
self.validation_rules = Some(rules);
}
#[cfg(feature = "validation")]
pub fn validate(&mut self) -> Result<Vec<ValidationError>> {
fn walk(
rules: &mut ValidationRuleSet,
table: &BTreeMap<String, Value>,
prefix: &str,
errors: &mut Vec<ValidationError>,
) {
for (key, value) in table {
let path = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}.{key}")
};
errors.extend(rules.validate(&path, value));
if let Value::Table(inner) = value {
walk(rules, inner, &path, errors);
}
}
}
match &mut self.validation_rules {
Some(rules) => {
if let Value::Table(table) = &self.values {
let mut errors = Vec::new();
walk(rules, table, "", &mut errors);
Ok(errors)
} else {
Err(Error::validation(
"Configuration root must be a table for validation",
))
}
}
None => Ok(Vec::new()), }
}
#[cfg(feature = "validation")]
pub fn validate_critical_only(&mut self) -> Result<Vec<ValidationError>> {
let all_errors = self.validate()?;
Ok(all_errors
.into_iter()
.filter(|e| e.severity == crate::validation::ValidationSeverity::Critical)
.collect())
}
#[cfg(feature = "validation")]
pub fn is_valid(&mut self) -> Result<bool> {
let critical_errors = self.validate_critical_only()?;
Ok(critical_errors.is_empty())
}
#[cfg(feature = "validation")]
pub fn validate_path(&mut self, path: &str) -> Result<Vec<ValidationError>> {
let value = self
.get(path)
.ok_or_else(|| Error::key_not_found(path))?
.clone();
match &mut self.validation_rules {
Some(rules) => Ok(rules.validate(path, &value)),
None => Ok(Vec::new()),
}
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ConfigOptions {
pub read_only: bool,
pub cache_enabled: bool,
pub cache_capacity: usize,
}
impl Default for ConfigOptions {
fn default() -> Self {
Self {
read_only: false,
cache_enabled: true,
cache_capacity: 1024,
}
}
}
impl ConfigOptions {
pub fn new() -> Self {
Self::default()
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn cache_enabled(mut self, cache_enabled: bool) -> Self {
self.cache_enabled = cache_enabled;
self
}
pub fn cache_capacity(mut self, cache_capacity: usize) -> Self {
self.cache_capacity = cache_capacity;
self
}
}
impl Config {
pub fn with_options(options: ConfigOptions) -> Self {
let mut config = Self::new();
config.options = options;
config
}
pub fn options(&self) -> &ConfigOptions {
&self.options
}
pub fn is_read_only(&self) -> bool {
self.options.read_only
}
fn ensure_writable(&self) -> Result<()> {
if self.options.read_only {
Err(Error::general("Configuration is read-only"))
} else {
Ok(())
}
}
pub fn cache_stats(&self) -> CacheStats {
let hits = self.cache_hits.load(Ordering::Relaxed);
let misses = self.cache_misses.load(Ordering::Relaxed);
let total = hits.saturating_add(misses);
let hit_ratio = if total == 0 {
0.0
} else {
hits as f64 / total as f64
};
CacheStats {
hits,
misses,
hit_ratio,
}
}
pub fn get_arc(&self, path: &str) -> Option<Arc<Value>> {
if self.options.cache_enabled {
if let Some(entry) = self.cache.get(path) {
self.cache_hits.fetch_add(1, Ordering::Relaxed);
return Some(Arc::clone(entry.value()));
}
self.cache_misses.fetch_add(1, Ordering::Relaxed);
let resolved = self.values.get(path)?.clone();
let arc = Arc::new(resolved);
self.cache.insert(path.into(), Arc::clone(&arc));
Some(arc)
} else {
self.cache_misses.fetch_add(1, Ordering::Relaxed);
Some(Arc::new(self.values.get(path)?.clone()))
}
}
pub fn clear_cache(&self) {
self.cache.clear();
}
pub fn set_default<V: Into<Value>>(&self, path: &str, value: V) -> Result<()> {
let mut defaults = self
.defaults
.write()
.map_err(|_| Error::concurrency("defaults table lock poisoned"))?;
defaults.insert(path.to_string(), value.into());
Ok(())
}
pub fn get_or_default(&self, path: &str) -> Option<Value> {
if let Some(v) = self.values.get(path) {
return Some(v.clone());
}
let defaults = self.defaults.read().ok()?;
defaults.get(path).cloned()
}
pub fn make_read_only(&mut self) {
self.options.read_only = true;
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct CacheStats {
pub hits: u64,
pub misses: u64,
pub hit_ratio: f64,
}
pub struct ConfigValue<'a> {
value: Option<&'a Value>,
}
impl<'a> ConfigValue<'a> {
fn new(value: Option<&'a Value>) -> Self {
Self { value }
}
pub fn as_string(&self) -> Result<String> {
match self.value {
Some(v) => v.as_string().map(|s| s.to_string()),
None => Err(Error::key_not_found("value not found")),
}
}
pub fn as_string_or(&self, default: &str) -> String {
self.value
.and_then(|v| v.as_string().ok())
.map(|s| s.to_string())
.unwrap_or_else(|| default.to_string())
}
pub fn as_integer(&self) -> Result<i64> {
match self.value {
Some(v) => v.as_integer(),
None => Err(Error::key_not_found("value not found")),
}
}
pub fn as_integer_or(&self, default: i64) -> i64 {
self.value
.and_then(|v| v.as_integer().ok())
.unwrap_or(default)
}
pub fn as_bool(&self) -> Result<bool> {
match self.value {
Some(v) => v.as_bool(),
None => Err(Error::key_not_found("value not found")),
}
}
pub fn as_bool_or(&self, default: bool) -> bool {
self.value.and_then(|v| v.as_bool().ok()).unwrap_or(default)
}
pub fn exists(&self) -> bool {
self.value.is_some()
}
pub fn value(&self) -> Option<&'a Value> {
self.value
}
}
pub struct ConfigBuilder {
format: Option<String>,
load: LoadOptions,
#[cfg(feature = "validation")]
validation_rules: Option<ValidationRuleSet>,
}
impl ConfigBuilder {
pub fn new() -> Self {
Self {
format: None,
load: LoadOptions::default(),
#[cfg(feature = "validation")]
validation_rules: None,
}
}
pub fn load_options(mut self, options: LoadOptions) -> Self {
self.load = options;
self
}
pub fn format<S: Into<String>>(mut self, format: S) -> Self {
self.format = Some(format.into());
self
}
#[cfg(feature = "validation")]
pub fn validation_rules(mut self, rules: ValidationRuleSet) -> Self {
self.validation_rules = Some(rules);
self
}
pub fn from_string(self, source: &str) -> Result<Config> {
#[cfg(feature = "validation")]
let mut config = Config::from_string_with(source, self.format.as_deref(), &self.load)?;
#[cfg(not(feature = "validation"))]
let config = Config::from_string_with(source, self.format.as_deref(), &self.load)?;
#[cfg(feature = "validation")]
if let Some(rules) = self.validation_rules {
config.set_validation_rules(rules);
}
Ok(config)
}
pub fn from_file<P: AsRef<Path>>(self, path: P) -> Result<Config> {
#[cfg(feature = "validation")]
let mut config = Config::from_file_with(path, &self.load)?;
#[cfg(not(feature = "validation"))]
let config = Config::from_file_with(path, &self.load)?;
#[cfg(feature = "validation")]
if let Some(rules) = self.validation_rules {
config.set_validation_rules(rules);
}
Ok(config)
}
}
impl Default for ConfigBuilder {
fn default() -> Self {
Self::new()
}
}
impl From<Value> for Config {
fn from(value: Value) -> Self {
Self {
values: value,
file_path: None,
format: "conf".to_string(),
modified: false,
options: ConfigOptions::default(),
cache_hits: AtomicU64::new(0),
cache_misses: AtomicU64::new(0),
cache: new_cache(),
defaults: Arc::new(RwLock::new(BTreeMap::new())),
#[cfg(feature = "noml")]
noml_document: None,
#[cfg(feature = "validation")]
validation_rules: None,
}
}
}
fn merge_in_place(target: &mut Value, other: &Value) {
match (target, other) {
(Value::Table(target_table), Value::Table(other_table)) => {
for (key, other_value) in other_table {
match target_table.get_mut(key) {
Some(existing) if existing.is_table() && other_value.is_table() => {
merge_in_place(existing, other_value);
}
Some(existing) => *existing = other_value.clone(),
None => {
target_table.insert(key.clone(), other_value.clone());
}
}
}
}
(target, other) => *target = other.clone(),
}
}
fn new_cache() -> DashMap<Box<str>, Arc<Value>> {
DashMap::with_shard_amount(8)
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
use std::sync::atomic::AtomicUsize;
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let io_err = |e| Error::io(path.display().to_string(), e);
let target = match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => std::fs::canonicalize(path).map_err(io_err)?,
_ => path.to_path_buf(),
};
let dir = match target.parent() {
Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
_ => PathBuf::from("."),
};
let name = target
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "config".to_string());
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let tmp = dir.join(format!(".{name}.{}.{n}.tmp", std::process::id()));
let result = (|| -> std::io::Result<()> {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
if let Ok(meta) = std::fs::metadata(&target) {
file.set_permissions(meta.permissions())?;
}
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, &target)
})();
if result.is_err() {
let _ = std::fs::remove_file(&tmp);
}
result.map_err(io_err)
}
mod conf_writer {
use crate::error::{Error, Result};
use crate::value::Value;
use std::collections::BTreeMap;
use std::fmt::Write;
fn key_ok(key: &str) -> bool {
!key.is_empty()
&& key
.chars()
.all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
}
fn bad_key() -> Error {
Error::serialize("a key holds characters CONF cannot write")
}
pub(super) fn write_table(
out: &mut String,
table: &BTreeMap<String, Value>,
path: &mut Vec<String>,
) -> Result<()> {
let has_plain = table.values().any(|v| !v.is_table());
if !path.is_empty() && (has_plain || table.is_empty()) {
if !out.is_empty() {
out.push('\n');
}
out.push('[');
out.push_str(&path.join("."));
out.push_str("]\n");
}
for (key, value) in table {
if value.is_table() {
continue;
}
if !key_ok(key) {
return Err(bad_key());
}
out.push_str(key);
out.push_str(" = ");
write_value(out, value)?;
out.push('\n');
}
for (key, value) in table {
if let Value::Table(inner) = value {
if !key_ok(key) || key.contains('.') {
return Err(bad_key());
}
path.push(key.clone());
write_table(out, inner, path)?;
path.pop();
}
}
Ok(())
}
fn write_value(out: &mut String, value: &Value) -> Result<()> {
match value {
Value::Null => out.push_str("null"),
Value::Bool(b) => {
let _ = write!(out, "{b}");
}
Value::Integer(i) => {
let _ = write!(out, "{i}");
}
Value::Float(f) if f.is_finite() => {
let _ = write!(out, "{f:?}");
}
Value::Float(_) => {
return Err(Error::serialize("CONF cannot hold NaN or infinity"));
}
Value::String(s) => write_string(out, s),
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
if item.is_table() {
return Err(Error::serialize("CONF cannot hold a table in an array"));
}
write_value(out, item)?;
}
out.push(']');
}
Value::Table(_) => {
return Err(Error::serialize("CONF cannot hold a table as a value"));
}
#[cfg(feature = "chrono")]
Value::DateTime(dt) => write_string(out, &dt.to_rfc3339()),
}
Ok(())
}
fn write_string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
c => out.push(c),
}
}
out.push('"');
}
}
#[cfg(any(feature = "toml", feature = "noml"))]
mod toml_writer {
use crate::error::{Error, Result};
use crate::value::Value;
use std::collections::BTreeMap;
use std::fmt::Write;
fn is_table_array(value: &Value) -> bool {
matches!(value, Value::Array(items)
if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Table(_))))
}
pub(super) fn write_table(
out: &mut String,
table: &BTreeMap<String, Value>,
path: &mut Vec<String>,
noml: bool,
) -> Result<()> {
for (key, value) in table {
if !matches!(value, Value::Table(_)) && !is_table_array(value) {
write_key(out, key);
out.push_str(" = ");
write_value(out, value, path, key, noml)?;
out.push('\n');
}
}
for (key, value) in table {
path.push(key.clone());
match value {
Value::Table(inner) => {
header(out, path, false);
write_table(out, inner, path, noml)?;
}
Value::Array(items) if is_table_array(value) => {
for item in items {
header(out, path, true);
if let Value::Table(inner) = item {
write_table(out, inner, path, noml)?;
}
}
}
_ => {}
}
path.pop();
}
Ok(())
}
fn header(out: &mut String, path: &[String], array: bool) {
if !out.is_empty() {
out.push('\n');
}
out.push_str(if array { "[[" } else { "[" });
for (i, key) in path.iter().enumerate() {
if i > 0 {
out.push('.');
}
write_key(out, key);
}
out.push_str(if array { "]]\n" } else { "]\n" });
}
fn write_key(out: &mut String, key: &str) {
let bare = key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
&& key
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
if bare {
out.push_str(key);
} else {
write_string(out, key, false);
}
}
fn write_string(out: &mut String, s: &str, noml: bool) {
out.push('"');
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
'$' if noml && chars.peek() == Some(&'{') => out.push_str("$$"),
c if c.is_control() => {
let _ = write!(out, "\\u{:04X}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
}
fn write_value(
out: &mut String,
value: &Value,
path: &[String],
key: &str,
noml: bool,
) -> Result<()> {
match value {
Value::Null if noml => out.push_str("null"),
Value::Null => {
let mut full = path.join(".");
if !full.is_empty() {
full.push('.');
}
full.push_str(key);
return Err(Error::serialize(format!(
"TOML has no null value; cannot write '{full}'"
)));
}
Value::Bool(b) => {
let _ = write!(out, "{b}");
}
Value::Integer(i) => {
let _ = write!(out, "{i}");
}
Value::Float(f) => {
if f.is_nan() {
out.push_str("nan");
} else if f.is_infinite() {
out.push_str(if *f > 0.0 { "inf" } else { "-inf" });
} else {
let _ = write!(out, "{f:?}");
}
}
Value::String(s) => write_string(out, s, noml),
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
write_value(out, item, path, key, noml)?;
}
out.push(']');
}
Value::Table(table) => {
out.push('{');
for (i, (k, v)) in table.iter().enumerate() {
out.push_str(if i > 0 { ", " } else { " " });
write_key(out, k);
out.push_str(" = ");
write_value(out, v, path, key, noml)?;
}
out.push_str(if table.is_empty() { "}" } else { " }" });
}
#[cfg(feature = "chrono")]
Value::DateTime(dt) => write_string(out, &dt.to_rfc3339(), noml),
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_creation() {
let config = Config::new();
assert!(!config.is_modified());
assert_eq!(config.format(), "conf");
}
#[test]
fn test_config_from_string() {
let config = Config::from_string("key = value\nport = 8080", Some("conf")).unwrap();
assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
assert_eq!(config.get("port").unwrap().as_integer().unwrap(), 8080);
}
#[test]
fn test_config_modification() {
let mut config = Config::new();
assert!(!config.is_modified());
config.set("key", "value").unwrap();
assert!(config.is_modified());
config.mark_clean();
assert!(!config.is_modified());
}
#[test]
fn test_config_merge() {
let mut config1 = Config::new();
config1.set("a", 1).unwrap();
config1.set("b.x", 2).unwrap();
let mut config2 = Config::new();
config2.set("b.y", 3).unwrap();
config2.set("c", 4).unwrap();
config1.merge(&config2).unwrap();
assert_eq!(config1.get("a").unwrap().as_integer().unwrap(), 1);
assert_eq!(config1.get("b.x").unwrap().as_integer().unwrap(), 2);
assert_eq!(config1.get("b.y").unwrap().as_integer().unwrap(), 3);
assert_eq!(config1.get("c").unwrap().as_integer().unwrap(), 4);
}
#[cfg(feature = "toml")]
#[test]
fn modified_toml_serializes_current_values() {
let source = "# comment\nname = \"app\"\n\n[server]\nport = 80\n";
let mut config = Config::from_string(source, Some("toml")).unwrap();
#[cfg(feature = "noml")]
assert_eq!(config.serialize().unwrap(), source);
config.set("server.port", 8080).unwrap();
config.set("path", "C:\\dir \"q\"").unwrap();
let text = config.serialize().unwrap();
let reloaded = Config::from_string(&text, Some("toml")).unwrap();
assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
config.set("nothing", Value::Null).unwrap();
assert!(config.serialize().is_err(), "TOML has no null");
}
#[cfg(feature = "noml")]
#[test]
fn modified_noml_serializes_current_values() {
let source = "name = \"app\"\nlog = \"/var/log/${name}.log\"\n";
let mut config = Config::from_string(source, Some("noml")).unwrap();
assert_eq!(
config.get("log").unwrap().as_string().unwrap(),
"/var/log/app.log"
);
config.set("template", "${not_a_reference}").unwrap();
config.set("nothing", Value::Null).unwrap();
let text = config.serialize().unwrap();
let reloaded = Config::from_string(&text, Some("noml")).unwrap();
assert_eq!(reloaded.as_value(), config.as_value(), "{text}");
}
}