typecode
RustConfig Parser/config.rs
1use std::collections::HashMap;
2use std::fs;
3
4#[derive(Debug, Clone)]
5pub struct Config {
6 entries: HashMap<String, String>,
7 path: String,
8}
9
10#[derive(Debug)]
11pub enum ConfigError {
12 IoError(String),
13 ParseError { line: usize, message: String },
14}
15
16impl Config {
17 pub fn from_file(path: &str) -> Result<Self, ConfigError> {
18 let content = fs::read_to_string(path)
19 .map_err(|e| ConfigError::IoError(e.to_string()))?;
20 let mut entries = HashMap::new();
21 for (idx, line) in content.lines().enumerate() {
22 let trimmed = line.trim();
23 if trimmed.is_empty() || trimmed.starts_with('#') {
24 continue;
25 }
26 match trimmed.split_once('=') {
27 Some((key, value)) => {
28 entries.insert(
29 key.trim().to_string(),
30 value.trim().to_string(),
31 );
32 }
33 None => {
34 return Err(ConfigError::ParseError {
35 line: idx + 1,
36 message: format!("Invalid syntax: {}", trimmed),
37 });
38 }
39 }
40 }
41 Ok(Config {
42 entries,
43 path: path.to_string(),
44 })
45 }
46
47 pub fn get(&self, key: &str) -> Option<&str> {
48 self.entries.get(key).map(|v| v.as_str())
49 }
50}
0WPM
100%Accuracy
00:00Time
0%
Progress