forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

config.rs41 lines, 1.1 KiBHistoryRawDownload
1use std::collections::HashMap;
2
3#[derive(Debug, thiserror::Error)]
4pub enum ConfigError {
5 #[error("invalid line: {0}")]
6 InvalidLine(String),
7 #[error("missing key: {0}")]
8 MissingKey(String),
9}
10
11pub struct Config(HashMap<String, String>);
12
13impl Config {
14 pub fn parse(content: &str) -> Result<Self, ConfigError> {
15 let mut fields = HashMap::new();
16
17 for line in content.lines().map(str::trim) {
18 if line.is_empty() || line.starts_with('[') || line.starts_with('#') {
19 continue;
20 }
21
22 let (key, value) = line
23 .split_once('=')
24 .ok_or_else(|| ConfigError::InvalidLine(line.to_string()))?;
25
26 fields.insert(
27 key.trim().to_string(),
28 value.trim().trim_matches('"').to_string(),
29 );
30 }
31
32 Ok(Self(fields))
33 }
34
35 pub fn get(&self, key: &str) -> Result<String, ConfigError> {
36 self.0
37 .get(key)
38 .cloned()
39 .ok_or_else(|| ConfigError::MissingKey(key.to_string()))
40 }
41}