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