2022-12-10
·
sdttttt
现在开始总算是可以松口气了,今天把配置文件部分写好了,配置文件使用的是ini格式,这个解析非常简单。而且Rust上的库也不少,最后选择了tini这个库。
https://github.com/pinecrew/tini
主要是这个库完全咩有依赖, 草草的看了一下源码,写的也非常精妙,实际解析ini的逻辑也就30行。
/// parse single line of ini file
pub fn parse_line(line: &str, index: usize) -> Result<Parsed, ParseError> {
let content = match line.split(&[';', '#'][..]).next() {
Some(value) => value.trim(),
None => return Ok(Parsed::Empty),
};
if content.is_empty() {
return Ok(Parsed::Empty);
}
// add checks for content
if content.starts_with('[') {
if content.ends_with(']') {
let section_name = content.trim_matches(|c| c == '[' || c == ']').to_owned();
return Ok(Parsed::Section(section_name));
}
return Err(ParseError::IncorrectSection(index));
}
if content.contains('=') {
let mut pair = content.splitn(2, '=').map(|s| s.trim());
// if key is None => error
let key = match pair.next() {
Some(value) => value.to_owned(),
None => return Err(ParseError::EmptyKey(index)),
};
if key.is_empty() {
return Err(ParseError::EmptyKey(index));
}
// if value is None => empty string
let value = match pair.next() {
Some(value) => value.to_owned(),
None => "".to_owned(),
};
return Ok(Parsed::Value(key, value));
}
Err(ParseError::IncorrectSyntax(index))
}
真的想歇会了。