use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct Config {
values: HashMap<String, String>,
}
impl Config {
pub fn new() -> Self {
Self {
values: HashMap::new(),
}
}
pub fn set(&mut self, key: &str, value: &str) {
self.values.insert(key.to_string(), value.to_string());
}
pub fn get(&self, key: &str) -> Option<&str> {
self.values.get(key).map(|s| s.as_str())
}
pub fn get_or(&self, key: &str, default: &str) -> String {
self.values
.get(key)
.cloned()
.unwrap_or_else(|| default.to_string())
}
pub fn get_f64(&self, key: &str) -> Option<f64> {
self.values.get(key).and_then(|v| v.parse().ok())
}
pub fn get_usize(&self, key: &str) -> Option<usize> {
self.values.get(key).and_then(|v| v.parse().ok())
}
pub fn get_bool(&self, key: &str) -> Option<bool> {
self.values.get(key).and_then(|v| v.parse().ok())
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.values.keys().map(|s| s.as_str())
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn merge(&mut self, other: &Config) {
for (k, v) in &other.values {
self.values.insert(k.clone(), v.clone());
}
}
pub fn from_env_prefix(prefix: &str) -> Self {
let mut cfg = Self::new();
for (key, value) in std::env::vars() {
if let Some(stripped) = key.strip_prefix(prefix) {
cfg.set(&stripped.to_lowercase(), &value);
}
}
cfg
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}