use std::marker::PhantomData; use bytes::Buf; use serde::{de::DeserializeOwned, Serialize}; use crate::error::Error; use super::{ConnectCodec, ConnectDecoder, ConnectEncoder, EncodeBuf, MessageCodec}; pub struct JsonConnectCodec { _phantom: PhantomData U>, } impl JsonConnectCodec { pub fn new() -> Self { Self { _phantom: PhantomData, } } } impl Default for JsonConnectCodec { fn default() -> Self { Self::new() } } impl ConnectCodec for JsonConnectCodec { type Encode = T; type Decode = U; type Encoder = JsonConnectEncoder; type Decoder = JsonConnectDecoder; fn message_codec(&self) -> MessageCodec { MessageCodec::Json } fn encoder(&mut self) -> Self::Encoder { JsonConnectEncoder { _phantom: PhantomData, } } fn decoder(&mut self) -> Self::Decoder { JsonConnectDecoder { _phantom: PhantomData, } } } pub struct JsonConnectEncoder { _phantom: PhantomData, } impl ConnectEncoder for JsonConnectEncoder { fn encode(&mut self, message: T, buf: &mut EncodeBuf) -> Result<(), Error> { serde_json::to_writer(&mut buf.writer(), &message)?; Ok(()) } } pub struct JsonConnectDecoder { _phantom: PhantomData T>, } impl ConnectDecoder for JsonConnectDecoder { fn decode(&mut self, buf: impl Buf) -> Result { Ok(serde_json::from_reader(buf.reader())?) } }