1
use serde::{Deserialize, Serialize};
2

            
3
use crate::commands::{
4
    Command, GenericResponseValue, Request, RequestParserResult, ResponseAttributes,
5
    ResponseParserError,
6
};
7

            
8
pub struct Channels;
9

            
10
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11
pub struct ChannelsResponse {
12
    pub channels: Vec<String>,
13
}
14

            
15
impl Command for Channels {
16
    type Response = ChannelsResponse;
17
    const COMMAND: &'static str = "channels";
18

            
19
    fn parse_request(mut parts: std::str::SplitWhitespace<'_>) -> RequestParserResult<'_> {
20
        debug_assert!(parts.next().is_none());
21

            
22
        Ok((Request::Channels, ""))
23
    }
24

            
25
1
    fn parse_response(
26
1
        parts: ResponseAttributes<'_>,
27
1
    ) -> Result<Self::Response, ResponseParserError> {
28
1
        let parts: Vec<_> = parts.into();
29
1
        let mut channel_names = Vec::with_capacity(parts.len());
30
4
        for (key, value) in parts {
31
3
            debug_assert!(key == "channels");
32
3
            let channel_name = match value {
33
3
                GenericResponseValue::Text(s) => s,
34
                GenericResponseValue::Binary(_) => {
35
                    return Err(ResponseParserError::UnexpectedPropertyType(
36
                        "channels", "Binary",
37
                    ));
38
                }
39
            };
40
3
            channel_names.push(channel_name.to_string());
41
        }
42

            
43
1
        Ok(ChannelsResponse {
44
1
            channels: channel_names,
45
1
        })
46
1
    }
47
}
48

            
49
#[cfg(test)]
50
mod tests {
51
    use super::*;
52

            
53
    use indoc::indoc;
54

            
55
    #[test]
56
1
    fn test_parse_response() {
57
1
        let response = indoc! {"
58
1
            channels: foo
59
1
            channels: bar
60
1
            channels: baz
61
1
            OK
62
1
        "};
63
1
        let response = Channels::parse_raw_response(response).unwrap();
64
1
        assert_eq!(
65
1
            response,
66
1
            ChannelsResponse {
67
1
                channels: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]
68
1
            }
69
1
        );
70
1
    }
71
}