From 7610f2a9dc30a86d6857ad390d7bd1714fa4c604 Mon Sep 17 00:00:00 2001 From: Jeremiah Russell Date: Wed, 8 Oct 2025 10:00:14 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(config):=20enhance=20rule=20ma?= =?UTF-8?q?nagement=20with=20BTreeMap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - migrate rules from Vec to BTreeMap for efficient access - add rule existence check to prevent duplicates - improve rule listing by iterating over values --- src/config.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index d966857..e92d8ce 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,5 @@ use std::{ + collections::BTreeMap, env, fs::{self, read_to_string}, path::PathBuf, @@ -16,12 +17,12 @@ use crate::{Error, MessageAge, Retention}; #[derive(Debug, Serialize, Deserialize)] pub struct Config { credentials: Option, - rules: Vec, + rules: BTreeMap, } impl Default for Config { fn default() -> Self { - let rules = Vec::new(); + let rules = BTreeMap::new(); let mut cfg = Self { credentials: Some("credential.json".to_string()), @@ -51,7 +52,15 @@ impl Config { /// Add a new rule to the rule set by setting the retention age pub fn add_rule(&mut self, retention: Retention) -> &mut Self { - let id = if let Some(max) = self.rules.iter().max_by_key(|r| r.id()) { + if self + .rules + .contains_key(retention.age().to_string().as_str()) + { + log::warn!("rule already exists"); + return self; + } + + let id = if let Some((_, max)) = self.rules.iter().max_by_key(|(_, r)| r.id()) { max.id() + 1 } else { 1 @@ -59,7 +68,8 @@ impl Config { let mut rule = EolRule::new(id); rule.set_retention(retention); - self.rules.push(rule); + log::info!("added rule: {rule}"); + self.rules.insert(rule.retention().to_string(), rule); self } @@ -100,7 +110,7 @@ impl Config { /// List the end of life rules set in the configuration pub fn list_rules(&self) -> Result<(), Error> { - for rule in &self.rules { + for rule in self.rules.values() { println!("{rule}"); } Ok(())