1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::{fmt::Display, str::FromStr};

use crate::{command::Command, error::Error};

#[derive(Debug)]
pub struct Request {
    command: Command,
    args: Vec<String>,
}

impl Into<Command> for Request {
    fn into(self) -> Command {
        self.command
    }
}

impl From<Command> for Request {
    fn from(command: Command) -> Self {
        Self::new(command, &Vec::<String>::new())
    }
}

impl Display for Request {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.command)?;

        for arg in &self.args {
            write!(f, " {}", arg)?;
        }

        Ok(())
    }
}

impl FromStr for Request {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let command: Command = s.parse()?;

        Ok(command.into())
    }
}

impl Request {
    pub fn new<A: Display>(command: Command, args: &Vec<A>) -> Self {
        Self {
            command: command.into(),
            args: args.iter().map(|arg| arg.to_string()).collect(),
        }
    }

    pub fn add_arg<A: Display>(&mut self, arg: A) {
        self.args.push(arg.to_string())
    }

    pub fn command(&self) -> &Command {
        &self.command
    }
}