diff --git a/rust/agama-dbus-server/src/questions/answers.rs b/rust/agama-dbus-server/src/questions/answers.rs index a955093fdd..d6ef306e59 100644 --- a/rust/agama-dbus-server/src/questions/answers.rs +++ b/rust/agama-dbus-server/src/questions/answers.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; +use agama_lib::questions::GenericQuestion; use anyhow::Context; use serde::{Deserialize, Serialize}; @@ -19,6 +20,37 @@ struct Answer { pub password: Option, } +impl Answer { + /// Determines whether the answer responds to the given question. + /// + /// * `question`: question to compare with. + pub fn responds(&self, question: &GenericQuestion) -> bool { + if let Some(class) = &self.class { + if question.class != *class { + return false; + } + } + + if let Some(text) = &self.text { + if question.text != *text { + return false; + } + } + + if let Some(data) = &self.data { + return data.iter().all(|(key, value)| { + let Some(e_val) = question.data.get(key) else { + return false; + }; + + e_val == value + }); + } + + true + } +} + /// Data structure holding list of Answer. /// The first matching Answer is used, even if there is /// a better (more specific) match later in the list. @@ -40,36 +72,8 @@ impl Answers { 2 } - fn find_answer(&self, question: &agama_lib::questions::GenericQuestion) -> Option<&Answer> { - 'main: for answerd in self.answers.iter() { - if let Some(v) = &answerd.class { - if !question.class.eq(v) { - continue; - } - } - if let Some(v) = &answerd.text { - if !question.text.eq(v) { - continue; - } - } - if let Some(v) = &answerd.data { - for (key, value) in v { - // all keys defined in answer has to match - let entry = question.data.get(key); - if let Some(e_val) = entry { - if !e_val.eq(value) { - continue 'main; - } - } else { - continue 'main; - } - } - } - - return Some(answerd); - } - - None + fn find_answer(&self, question: &GenericQuestion) -> Option<&Answer> { + self.answers.iter().find(|a| a.responds(&question)) } } @@ -78,7 +82,7 @@ impl crate::questions::AnswerStrategy for Answers { Answers::id() } - fn answer(&self, question: &agama_lib::questions::GenericQuestion) -> Option { + fn answer(&self, question: &GenericQuestion) -> Option { let answer = self.find_answer(question); answer.map(|answer| answer.answer.clone()) }