pub const MAX_WORDS: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Spoken {
AllowOnce,
Deny,
Cancel,
StopAll,
}
const PLEASE: &str = "please";
pub fn parse(transcript: &str, pending: bool) -> Option<Spoken> {
let words: Vec<String> = transcript
.split(|c: char| !c.is_alphanumeric() && c != '\'')
.filter(|word| !word.is_empty())
.map(str::to_lowercase)
.collect();
let phrase: Vec<&str> =
words.iter().map(String::as_str).filter(|word| *word != PLEASE).collect();
if phrase == ["stop", "all"] {
return Some(Spoken::StopAll);
}
if words.is_empty() || words.len() > MAX_WORDS || words.iter().any(|word| word == "always") {
return None;
}
match phrase.as_slice() {
["allow", "once"] => Some(Spoken::AllowOnce),
["deny"] | ["deny", "it"] => Some(Spoken::Deny),
["cancel"] if pending => Some(Spoken::Cancel),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_engines_answers_decide() {
let cases: &[(&str, bool, Option<Spoken>)] = &[
("Allow once.", false, Some(Spoken::AllowOnce)),
("allow once please", false, Some(Spoken::AllowOnce)),
("Please, allow once!", false, Some(Spoken::AllowOnce)),
("deny", false, Some(Spoken::Deny)),
("Deny it.", false, Some(Spoken::Deny)),
("deny, please", true, Some(Spoken::Deny)),
("always allow", false, None),
("allow once always", false, None),
("say allow once or deny", false, None),
("allow once or deny", false, None),
("allow once deny", false, None),
("sure", false, None),
("yes", false, None),
("yes, allow once", false, None),
("ok", false, None),
("go ahead", false, None),
("no", false, None),
("stop", false, None),
("stop", true, None),
("allow", false, None),
("once", false, None),
("cancel", false, None),
("Cancel.", true, Some(Spoken::Cancel)),
("cancel it", true, None),
("wait", true, None),
("stop that", true, None),
("stop all", false, Some(Spoken::StopAll)),
("Stop all, please.", true, Some(Spoken::StopAll)),
("please please allow once please", false, None),
("", false, None),
("...", false, None),
];
for (said, pending, expected) in cases {
assert_eq!(parse(said, *pending), *expected, "{said:?} (pending: {pending})");
}
}
#[test]
fn stop_all_is_never_a_denial() {
for said in ["stop all", "STOP ALL", "stop all please"] {
assert_eq!(parse(said, false), Some(Spoken::StopAll));
assert_eq!(parse(said, true), Some(Spoken::StopAll));
}
}
}