potatonet_common/
request.rs1use bytes::Bytes;
2use serde::de::DeserializeOwned;
3use serde::Serialize;
4use std::io::Cursor;
5
6#[derive(Serialize, Deserialize, Clone)]
8pub struct Request<T> {
9 pub method: u32,
10 pub data: T,
11}
12
13impl<T> Request<T> {
14 pub fn new(method: u32, data: T) -> Self {
15 Request {
16 method: method.into(),
17 data,
18 }
19 }
20}
21
22#[derive(Serialize, Deserialize)]
24pub struct Response<T> {
25 pub data: T,
26}
27
28impl<T> Response<T> {
29 pub fn new(data: T) -> Self {
30 Response { data }
31 }
32}
33
34pub type RequestBytes = Request<Bytes>;
35
36pub type ResponseBytes = Response<Bytes>;
37
38impl<T: Serialize> Request<T> {
39 pub fn to_bytes(&self) -> RequestBytes {
40 RequestBytes {
41 method: self.method.clone(),
42 data: Bytes::from(rmp_serde::to_vec(&self.data).unwrap()),
43 }
44 }
45}
46
47impl<T: DeserializeOwned> Request<T> {
48 pub fn from_bytes(req: RequestBytes) -> Self {
49 Self {
50 method: req.method,
51 data: rmp_serde::from_read(Cursor::new(&req.data)).unwrap(),
52 }
53 }
54}
55
56impl<T: Serialize> Response<T> {
57 pub fn to_bytes(&self) -> ResponseBytes {
58 ResponseBytes {
59 data: Bytes::from(rmp_serde::to_vec(&self.data).unwrap()),
60 }
61 }
62}
63
64impl<T: DeserializeOwned> Response<T> {
65 pub fn from_bytes(req: ResponseBytes) -> Self {
66 Self {
67 data: rmp_serde::from_read(Cursor::new(&req.data)).unwrap(),
68 }
69 }
70}