現在開始總算是可以鬆口氣了,今天把配置文件部分寫好了,配置文件使用的是ini格式,這個解析非常簡單。而且Rust上的庫也不少,最後選擇了tini這個庫。
https://github.com/pinecrew/tini
主要是這個庫完全咩有依賴, 草草的看了一下源碼,寫的也非常精妙,實際解析ini的邏輯也就30行。
1/// parse single line of ini file
2pub fn parse_line(line: &str, index: usize) -> Result<Parsed, ParseError> {
3 let content = match line.split(&[';', '#'][..]).next() {
4 Some(value) => value.trim(),
5 None => return Ok(Parsed::Empty),
6 };
7 if content.is_empty() {
8 return Ok(Parsed::Empty);
9 }
10 // add checks for content
11 if content.starts_with('[') {
12 if content.ends_with(']') {
13 let section_name = content.trim_matches(|c| c == '[' || c == ']').to_owned();
14 return Ok(Parsed::Section(section_name));
15 }
16 return Err(ParseError::IncorrectSection(index));
17 }
18 if content.contains('=') {
19 let mut pair = content.splitn(2, '=').map(|s| s.trim());
20 // if key is None => error
21 let key = match pair.next() {
22 Some(value) => value.to_owned(),
23 None => return Err(ParseError::EmptyKey(index)),
24 };
25 if key.is_empty() {
26 return Err(ParseError::EmptyKey(index));
27 }
28 // if value is None => empty string
29 let value = match pair.next() {
30 Some(value) => value.to_owned(),
31 None => "".to_owned(),
32 };
33 return Ok(Parsed::Value(key, value));
34 }
35 Err(ParseError::IncorrectSyntax(index))
36}
真的想歇會了。