use super::Transport; use crate::encoding::Message; use anyhow::{anyhow, Result}; use log::debug; use std::str::FromStr; use tokio::net::UdpSocket; pub struct UdpTransport { sock: UdpSocket, } impl UdpTransport { pub async fn new(sock: UdpSocket) -> Result { Ok(Self { sock }) } } impl Transport for UdpTransport { async fn recv(&self) -> Result { let mut buf = [0; 1024]; let size = self.sock.recv(&mut buf).await?; let message = String::from_utf8(buf[..size].to_vec())?; let (head, body) = message .split_once("\r\n\r\n") .ok_or(anyhow!("header end missing"))?; debug!("<- {head}\n\n{body}"); let mut mesg = Message::from_str(head.trim_end())?; *mesg.body_mut() = body.to_string(); Ok(mesg) } async fn send(&self, request: Message) -> Result<()> { debug!("-> {request}"); self.sock.send(format!("{request}").as_bytes()).await?; Ok(()) } }