rabbitmq_stream_protocol/commands/
credit.rs

1use std::io::Write;
2
3use crate::{
4    codec::{Decoder, Encoder},
5    error::{DecodeError, EncodeError},
6    protocol::commands::COMMAND_CREDIT,
7    ResponseCode,
8};
9
10use super::Command;
11
12#[cfg_attr(test, derive(fake::Dummy))]
13#[derive(PartialEq, Eq, Debug)]
14pub struct CreditCommand {
15    subscription_id: u8,
16    credit: u16,
17}
18
19impl CreditCommand {
20    pub fn new(subscription_id: u8, credit: u16) -> Self {
21        Self {
22            subscription_id,
23            credit,
24        }
25    }
26}
27
28impl Encoder for CreditCommand {
29    fn encoded_size(&self) -> u32 {
30        self.subscription_id.encoded_size() + self.credit.encoded_size()
31    }
32
33    fn encode(&self, writer: &mut impl Write) -> Result<(), EncodeError> {
34        self.subscription_id.encode(writer)?;
35        self.credit.encode(writer)?;
36        Ok(())
37    }
38}
39
40impl Decoder for CreditCommand {
41    fn decode(input: &[u8]) -> Result<(&[u8], Self), DecodeError> {
42        let (input, subscription_id) = u8::decode(input)?;
43        let (input, credit) = u16::decode(input)?;
44
45        Ok((
46            input,
47            CreditCommand {
48                subscription_id,
49                credit,
50            },
51        ))
52    }
53}
54
55impl Command for CreditCommand {
56    fn key(&self) -> u16 {
57        COMMAND_CREDIT
58    }
59}
60
61#[cfg_attr(test, derive(fake::Dummy))]
62#[derive(Debug, PartialEq, Eq)]
63pub struct CreditResponse {
64    pub(crate) code: ResponseCode,
65    pub(crate) subscription_id: u8,
66}
67
68impl Decoder for CreditResponse {
69    fn decode(input: &[u8]) -> Result<(&[u8], Self), DecodeError> {
70        let (input, code) = ResponseCode::decode(input)?;
71        let (input, subscription_id) = u8::decode(input)?;
72
73        Ok((
74            input,
75            CreditResponse {
76                code,
77                subscription_id,
78            },
79        ))
80    }
81}
82
83impl Encoder for CreditResponse {
84    fn encoded_size(&self) -> u32 {
85        0
86    }
87
88    fn encode(&self, writer: &mut impl std::io::Write) -> Result<(), crate::error::EncodeError> {
89        self.code.encode(writer)?;
90        self.subscription_id.encode(writer)?;
91        Ok(())
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use crate::commands::tests::command_encode_decode_test;
98
99    use super::CreditCommand;
100    use crate::commands::credit::CreditResponse;
101
102    #[test]
103    fn credit_request_test() {
104        command_encode_decode_test::<CreditCommand>()
105    }
106
107    #[test]
108    fn credit_response_test() {
109        command_encode_decode_test::<CreditResponse>();
110    }
111}