Skip to content

Commit

Permalink
refactor: factor out serdes of T in send/recv
Browse files Browse the repository at this point in the history
  • Loading branch information
threadexio committed May 4, 2024
1 parent ef4e5ac commit 013e2a1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
23 changes: 17 additions & 6 deletions channels/src/receiver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,21 @@ where
}
}

impl<T, R, D> Receiver<T, R, D>
where
D: Deserializer<T>,
{
#[inline]
fn deserialize_t<Io>(
&mut self,
data: &mut [u8],
) -> Result<T, RecvError<D::Error, Io>> {
self.deserializer
.deserialize(data)
.map_err(RecvError::Serde)
}
}

impl<T, R, D> Receiver<T, R, D>
where
R: AsyncRead,
Expand Down Expand Up @@ -301,9 +316,7 @@ where
)
.await?;

self.deserializer
.deserialize(&mut payload)
.map_err(RecvError::Serde)
self.deserialize_t(&mut payload)
}
}

Expand Down Expand Up @@ -341,9 +354,7 @@ where
&mut self.reader,
)?;

self.deserializer
.deserialize(&mut payload)
.map_err(RecvError::Serde)
self.deserialize_t(&mut payload)
}
}

Expand Down
23 changes: 15 additions & 8 deletions channels/src/sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,19 @@ where
}
}

impl<T, W, S> Sender<T, W, S>
where
S: Serializer<T>,
{
#[inline]
fn serialize_t<Io>(
&mut self,
t: &T,
) -> Result<Vec<u8>, SendError<S::Error, Io>> {
self.serializer.serialize(t).map_err(SendError::Serde)
}
}

impl<T, W, S> Sender<T, W, S>
where
W: AsyncWrite,
Expand Down Expand Up @@ -262,10 +275,7 @@ where
where
D: Borrow<T>,
{
let payload = self
.serializer
.serialize(data.borrow())
.map_err(SendError::Serde)?;
let payload = self.serialize_t(data.borrow())?;

crate::protocol::send_async(
&self.config,
Expand Down Expand Up @@ -314,10 +324,7 @@ where
where
D: Borrow<T>,
{
let payload = self
.serializer
.serialize(data.borrow())
.map_err(SendError::Serde)?;
let payload = self.serialize_t(data.borrow())?;

crate::protocol::send_sync(
&self.config,
Expand Down

0 comments on commit 013e2a1

Please sign in to comment.