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

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

            
8
pub struct ReadMessages;
9

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

            
15
impl Command for ReadMessages {
16
    type Response = ReadMessagesResponse;
17
    const COMMAND: &'static str = "readmessages";
18

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

            
22
        Ok((Request::ReadMessages, ""))
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
        debug_assert!(parts.len() % 2 == 0);
30

            
31
1
        let mut messages = Vec::with_capacity(parts.len() / 2);
32

            
33
2
        for channel_message_pair in parts.chunks_exact(2) {
34
2
            let (ckey, cvalue) = channel_message_pair[0];
35
2
            let (mkey, mvalue) = channel_message_pair[1];
36
2

            
37
2
            debug_assert!(ckey == "channel");
38
2
            debug_assert!(mkey == "message");
39

            
40
2
            let channel = expect_property_type!(Some(cvalue), "channel", Text).to_string();
41
2
            let message = expect_property_type!(Some(mvalue), "message", Text).to_string();
42
2

            
43
2
            messages.push((channel, message));
44
        }
45

            
46
1
        Ok(ReadMessagesResponse { messages })
47
1
    }
48
}
49

            
50
#[cfg(test)]
51
mod tests {
52
    use indoc::indoc;
53

            
54
    use super::*;
55

            
56
    #[test]
57
1
    fn test_parse_response() {
58
1
        let input = indoc! {"
59
1
            channel: channel1
60
1
            message: message1
61
1
            channel: channel2
62
1
            message: message2
63
1
            OK
64
1
        "};
65
1
        let result = ReadMessages::parse_raw_response(input);
66
1
        assert_eq!(
67
1
            result,
68
1
            Ok(ReadMessagesResponse {
69
1
                messages: vec![
70
1
                    ("channel1".to_string(), "message1".to_string()),
71
1
                    ("channel2".to_string(), "message2".to_string()),
72
1
                ]
73
1
            })
74
1
        );
75
1
    }
76
}