1use crate::prelude::*;
2use bytes::Bytes;
3use tracing::{debug, instrument};
4
5#[derive(Debug, Default)]
6pub struct Ping {
7 msg: Option<Bytes>,
8}
9
10impl Ping {
11 pub fn new(msg: Option<Bytes>) -> Ping { Ping { msg } }
12
13 pub fn parse_frames(parse: &mut Parse) -> crate::Result<Ping> {
14 match parse.next_bytes() {
15 Ok(msg) => Ok(Ping::new(Some(msg))),
16 Err(ParseError::EndOfStream) => Ok(Ping::default()),
17 Err(e) => Err(e.into()),
18 }
19 }
20
21 #[instrument(skip(self, dst))]
22 pub async fn apply(self, dst: &mut Connection) -> crate::Result<()> {
23 let response = match self.msg {
24 None => Frame::Simple("PONG".to_string()),
25 Some(msg) => Frame::Bulk(msg),
26 };
27
28 debug!(?response);
29 dst.write_frame(&response).await?;
30
31 Ok(())
32 }
33
34 pub fn into_frame(self) -> Frame {
35 let mut frame = Frame::array();
36 frame.push_bulk(Bytes::from("ping".as_bytes()));
37 if let Some(msg) = self.msg {
38 frame.push_bulk(msg);
39 }
40 frame
41 }
42}