Skip to content

Commit 1151bba

Browse files
committed
refactor: ini format parser
Intended to be easier to grok and match the same flow as other format parsers. Signed-off-by: Brennan Kinney <[email protected]>
1 parent d7c1656 commit 1151bba

File tree

1 file changed

+35
-25
lines changed

1 file changed

+35
-25
lines changed

src/file/format/ini.rs

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,45 @@ use std::error::Error;
33
use ini::Ini;
44

55
use crate::map::Map;
6-
use crate::value::{Value, ValueKind};
6+
use crate::value::{Table, Value, ValueKind};
77

88
pub fn parse(
99
uri: Option<&String>,
1010
text: &str,
1111
) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
12-
let mut map: Map<String, Value> = Map::new();
13-
let i = Ini::load_from_str(text)?;
14-
for (sec, prop) in i.iter() {
15-
match sec {
16-
Some(sec) => {
17-
let mut sec_map: Map<String, Value> = Map::new();
18-
for (k, v) in prop.iter() {
19-
sec_map.insert(
20-
k.to_owned(),
21-
Value::new(uri, ValueKind::String(v.to_owned())),
22-
);
23-
}
24-
map.insert(sec.to_owned(), Value::new(uri, ValueKind::Table(sec_map)));
25-
}
26-
None => {
27-
for (k, v) in prop.iter() {
28-
map.insert(
29-
k.to_owned(),
30-
Value::new(uri, ValueKind::String(v.to_owned())),
31-
);
32-
}
33-
}
34-
}
12+
let value = from_ini(uri, Ini::load_from_str(text)?);
13+
14+
match value.kind {
15+
ValueKind::Table(map) => Ok(map),
16+
17+
_ => Ok(Map::new()),
18+
}
19+
}
20+
21+
fn from_ini(
22+
uri: Option<&String>,
23+
data: Ini,
24+
) -> Value {
25+
let mut map = Map::new();
26+
27+
let mut sections: Map<Option<&str>, Table> = data.into_iter().map(|(section, props)| {(
28+
section,
29+
props.iter().map(|(k, v)| {(
30+
k.to_owned(),
31+
Value::new(uri, ValueKind::String(v.to_owned())),
32+
)}).collect()
33+
)}).collect();
34+
35+
// These (optional) properties should exist top-level alongside sections:
36+
if let Some(sectionless) = sections.remove(&None) {
37+
map.extend(sectionless);
3538
}
36-
Ok(map)
39+
40+
// Wrap each section Table into Value for merging into `map`:
41+
map.extend(sections.into_iter().map(|(k,v)| {(
42+
k.unwrap_or_default().to_owned(),
43+
Value::new(uri, ValueKind::Table(v)),
44+
)}));
45+
46+
Value::new(uri, ValueKind::Table(map))
3747
}

0 commit comments

Comments
 (0)