messaging_api/
commands.rs1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4#[serde(tag = "command", rename_all = "snake_case")]
5pub enum MessagingSystemCommand {
6 Info,
7 Help,
8 Rotate,
9 Switch { selection: usize },
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum MessagingCommandParse {
14 NotCommand,
15 InvalidSwitch,
16 Command(MessagingSystemCommand),
17}
18
19pub fn parse_messaging_command(input: &str) -> MessagingCommandParse {
20 let command = input.trim().to_ascii_lowercase();
21 match command.as_str() {
22 "/info" => MessagingCommandParse::Command(MessagingSystemCommand::Info),
23 "/help" => MessagingCommandParse::Command(MessagingSystemCommand::Help),
24 "/new" | "/clear" => MessagingCommandParse::Command(MessagingSystemCommand::Rotate),
25 _ if command.starts_with("/switch") => {
26 let suffix = command["/switch".len()..].trim();
27 match suffix
28 .parse::<usize>()
29 .ok()
30 .filter(|selection| *selection > 0)
31 {
32 Some(selection) => {
33 MessagingCommandParse::Command(MessagingSystemCommand::Switch { selection })
34 }
35 None => MessagingCommandParse::InvalidSwitch,
36 }
37 }
38 _ => MessagingCommandParse::NotCommand,
39 }
40}
41
42pub fn sort_scope_ids(scope_ids: &mut [String]) {
43 scope_ids.sort();
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn parser_is_case_insensitive_and_accepts_compact_switch() {
52 assert_eq!(
53 parse_messaging_command(" /SWITCH2 "),
54 MessagingCommandParse::Command(MessagingSystemCommand::Switch { selection: 2 })
55 );
56 assert_eq!(
57 parse_messaging_command("/switch 0"),
58 MessagingCommandParse::InvalidSwitch
59 );
60 assert_eq!(
61 parse_messaging_command("hello"),
62 MessagingCommandParse::NotCommand
63 );
64 }
65}