1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use crate::*;
use serde::de::DeserializeOwned;
use std::io as stio;
use tokio::io::AsyncRead;
pub async fn decode_response<F, T, S>(stream: &mut S, f: F) -> stio::Result<T>
where
F: Fn(u32, Vec<u8>) -> T,
S: AsyncRead + Unpin,
{
let mut buf = [0; 14];
stream.read_exact(&mut buf).await?;
assert!(&buf[0..6] == MAGIC.as_bytes(), "Magic str not received");
let payload_len = u32::from_ne_bytes([buf[6], buf[7], buf[8], buf[9]]) as usize;
let msg_type = u32::from_ne_bytes([buf[10], buf[11], buf[12], buf[13]]);
let mut payload = vec![0; payload_len];
stream.read_exact(&mut payload).await?;
Ok(f(msg_type, payload))
}
pub async fn decode_msg<D, S>(stream: &mut S) -> stio::Result<stio::Result<MsgResponse<D>>>
where
D: DeserializeOwned,
S: AsyncRead + Unpin,
{
decode_response(stream, MsgResponse::new).await
}
pub async fn decode_event_future<D, S>(stream: &mut S) -> stio::Result<stio::Result<event::Event>>
where
D: DeserializeOwned,
S: AsyncRead + Unpin,
{
decode_response(stream, decode_event).await
}