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

            
3
use crate::{
4
    commands::{CommandResponse, ResponseParserError, empty_command_request},
5
    response_tokenizer::{ResponseAttributes, expect_property_type},
6
    types::ChannelName,
7
};
8

            
9
empty_command_request!(Channels, "channels");
10

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

            
16
impl ChannelsResponse {
17
    pub fn new(channels: Vec<ChannelName>) -> Self {
18
        ChannelsResponse { channels }
19
    }
20
}
21

            
22
impl CommandResponse for ChannelsResponse {
23
    type Request = ChannelsRequest;
24

            
25
1
    fn parse(parts: ResponseAttributes<'_>) -> Result<Self, ResponseParserError> {
26
1
        let parts: Vec<_> = parts.into_vec()?;
27
1
        let mut channel_names = Vec::with_capacity(parts.len());
28
3
        for (key, value) in parts {
29
3
            debug_assert!(key == "channels");
30
3
            let channel_name = expect_property_type!(Some(value), "channels", Text);
31
3
            let channel_name = channel_name
32
3
                .parse()
33
3
                .map_err(|_| ResponseParserError::SyntaxError(0, channel_name.to_string()))?;
34
3
            channel_names.push(channel_name);
35
        }
36

            
37
1
        Ok(ChannelsResponse {
38
1
            channels: channel_names,
39
1
        })
40
1
    }
41

            
42
    fn serialize(&self) -> Vec<u8> {
43
        unimplemented!("response serialization is not yet implemented for ChannelsResponse")
44
    }
45
}
46

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

            
51
    use indoc::indoc;
52

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