use std::collections::BTreeSet;
pub(crate) type Section<'a> = (&'a str, Vec<(String, String)>);
pub(crate) fn sections<'a>(text: &'a str, kinds: &[&str]) -> Result<Vec<Section<'a>>, String> {
let mut sections: Vec<Section<'a>> = Vec::new();
for line in text.lines().map(str::trim) {
if line.is_empty() || line.starts_with('#') {
continue;
}
let kind = line.strip_prefix("[[").and_then(|s| s.strip_suffix("]]"));
if let Some(kind) = kind.filter(|kind| kinds.contains(kind)) {
sections.push((kind, Vec::new()));
continue;
}
let pair = line
.split_once('=')
.map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned()));
match (pair, sections.last_mut()) {
(Some(pair), Some((_, section))) => section.push(pair),
_ => return Err(line.to_owned()),
}
}
Ok(sections)
}
pub(crate) fn repeated_key(section: &[(String, String)]) -> Option<&str> {
let mut seen = BTreeSet::new();
section
.iter()
.map(|(key, _)| key.as_str())
.find(|key| !seen.insert(*key))
}
pub(crate) fn quoted(text: &str) -> Option<String> {
if text.chars().any(char::is_control) {
return None;
}
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
if matches!(c, '\\' | '"') {
out.push('\\');
}
out.push(c);
}
out.push('"');
Some(out)
}
fn unquoted(value: &str) -> Option<String> {
let inner = value.strip_prefix('"')?.strip_suffix('"')?;
let mut text = String::with_capacity(inner.len());
let mut chars = inner.chars();
while let Some(c) = chars.next() {
match c {
'\\' => match chars.next()? {
escaped @ ('\\' | '"') => text.push(escaped),
_ => return None,
},
'"' => return None,
c if c.is_control() => return None,
c => text.push(c),
}
}
Some(text)
}
pub(crate) fn value_of<'a>(section: &'a [(String, String)], key: &str) -> Option<&'a str> {
section
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
}
pub(crate) fn text_of<E>(
section: &[(String, String)],
key: &str,
wrong: impl FnOnce() -> E,
) -> Result<Option<String>, E> {
value_of(section, key)
.map(|value| unquoted(value).ok_or_else(wrong))
.transpose()
}
#[cfg(test)]
mod tests;