use std::collections::BTreeMap;
#[cfg(feature = "ini")]
use crate::error::{Error, ErrorKind};
use crate::value::Value;
type Dict = BTreeMap<String, Value>;
#[cfg(feature = "ini")]
pub(crate) fn parse(text: &str) -> Result<Value, Error> {
let mut root = Dict::new();
let mut section: Vec<String> = Vec::new();
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with(';') || line.starts_with('#') {
continue;
}
if let Some(header) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = header
.split('.')
.map(|part| part.trim().to_owned())
.collect();
if section.iter().any(String::is_empty) {
return Err(refused(index + 1, "an empty section name"));
}
continue;
}
if let Some((key, value)) = line.split_once('=') {
let key = key.trim();
if key.is_empty() {
return Err(refused(index + 1, "`= value` with no key"));
}
let mut path: Vec<&str> = section.iter().map(String::as_str).collect();
path.push(key);
insert(&mut root, &path, scalar(value.trim()), index + 1)
.map_err(|reason| Error::new(ErrorKind::Parse, reason))?;
continue;
}
return Err(refused(
index + 1,
"neither a section header nor `key = value`",
));
}
Ok(Value::Table(root))
}
#[cfg(feature = "ini")]
fn refused(line: usize, reason: &str) -> Error {
Error::new(ErrorKind::Parse, format!("line {line}: {reason}"))
}
pub(super) fn insert(
root: &mut Dict,
path: &[&str],
value: Value,
line: usize,
) -> Result<(), String> {
let (last, walk) = path.split_last().expect("a key is never empty");
let mut here = root;
for part in walk {
let slot = here
.entry((*part).to_owned())
.or_insert_with(|| Value::Table(Dict::new()));
match slot {
Value::Table(dict) => here = dict,
_ => {
return Err(format!(
"line {line}: `{part}` is already a value, so it cannot also \
hold `{last}`"
));
}
}
}
if let Some(Value::Table(_)) = here.get(*last) {
return Err(format!(
"line {line}: `{last}` is already a table, so it cannot also be a value"
));
}
here.insert((*last).to_owned(), value);
Ok(())
}
pub(super) fn scalar(text: &str) -> Value {
if text.len() >= 2 && text.starts_with('"') && text.ends_with('"') {
return Value::from(&text[1..text.len() - 1]);
}
if let Ok(flag) = text.parse::<bool>() {
Value::Bool(flag)
} else if let Ok(whole) = text.parse::<i64>() {
Value::Integer(i128::from(whole))
} else if let Ok(real) = text.parse::<f64>() {
Value::Float(real)
} else {
Value::from(text)
}
}