1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::collections::HashMap;
pub struct IniFile {
// section_name, key, list of values
pub sections : HashMap<String, HashMap<String, Vec<String>>>
}
impl IniFile {
pub fn from_file(path : &str) -> Result<IniFile, io::Error> {
let mut file : HashMap<String, HashMap<String,Vec<String>>> = HashMap::new();
let fd = File::open(path)?;
let reader = io::BufReader::new(fd);
let mut current_section = String::from("");
for line in reader.lines() {
let line = line?;
let line = line.trim().to_string();
if line.starts_with("#") || line.is_empty() {
println!("kommentar or empts: {}", line);
continue;
}
// another section begins
if line.starts_with("[") && line.ends_with("]") {
let nam = line.get(1..(line.len()-1));
let n;
match nam {
Some(sec_name) => n = sec_name,
// TODO no name given, what should be done
None => n = ""
}
current_section = n.to_string();
// TODO maybe the sections has been specified twice?
file.insert(n.to_string(), HashMap::new() );
continue;
}
let kv : Vec<&str> = line.split("=").collect();
let mut key = String::from("");
if let Some(t) = kv.get(0) {
key = t.to_string();
}
let mut value = String::from("");
if let Some(t) = kv.get(1) {
value = t.to_string();
}
println!("key: {}, value: {}", key, value);
if let Some(section) = file.get_mut(¤t_section) {
println!("found current section");
// get the values for key in section current_section
let mut hack_first = true;
if let Some(ent) = section.get_mut(&key) {
println!("found key in map");
ent.push(value.to_string());
hack_first = false;
}
if hack_first {
let mut new = Vec::new();
new.push(value.to_string());
section.insert(key, new);
// TODO create new HashMap and insert
println!("inserted new one");
}
}
}
Ok(IniFile { sections : file })
}
}
|