Skip to main content

eoka_protocol/
io.rs

1use serde::{Deserialize, Serialize};
2use tokio::io::{AsyncReadExt, AsyncWriteExt};
3
4pub async fn write_msg<W: AsyncWriteExt + Unpin>(
5    writer: &mut W,
6    msg: &impl Serialize,
7) -> std::io::Result<()> {
8    let payload = serde_json::to_vec(msg).map_err(|e| std::io::Error::other(e.to_string()))?;
9    let len = (payload.len() as u32).to_be_bytes();
10    writer.write_all(&len).await?;
11    writer.write_all(&payload).await?;
12    writer.flush().await?;
13    Ok(())
14}
15pub async fn read_msg<R: AsyncReadExt + Unpin, T: for<'de> Deserialize<'de>>(
16    reader: &mut R,
17) -> std::io::Result<T> {
18    let mut len_buf = [0u8; 4];
19    reader.read_exact(&mut len_buf).await?;
20    let len = u32::from_be_bytes(len_buf) as usize;
21
22    if len > 64 * 1024 * 1024 {
23        return Err(std::io::Error::other("message too large (>64MB)"));
24    }
25
26    let mut buf = vec![0u8; len];
27    reader.read_exact(&mut buf).await?;
28    serde_json::from_slice(&buf).map_err(|e| std::io::Error::other(e.to_string()))
29}