Skip to content

Commit

Permalink
codec: auto implement Encoder/Decoder for &mut T if T is Encoder/Decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
suikammd committed Jul 5, 2023
1 parent 2de69c4 commit 811a596
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
10 changes: 10 additions & 0 deletions tokio-util/src/codec/decoder.rs
Expand Up @@ -182,3 +182,13 @@ pub trait Decoder {
Framed::new(io, self)
}
}

impl<T: Decoder> Decoder for &mut T {
type Item = T::Item;

type Error = T::Error;

fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
(**self).decode(src)
}
}
8 changes: 8 additions & 0 deletions tokio-util/src/codec/encoder.rs
Expand Up @@ -23,3 +23,11 @@ pub trait Encoder<Item> {
/// [`FramedWrite`]: crate::codec::FramedWrite
fn encode(&mut self, item: Item, dst: &mut BytesMut) -> Result<(), Self::Error>;
}

impl<I, T: Encoder<I>> Encoder<I> for &mut T {
type Error = T::Error;

fn encode(&mut self, item: I, dst: &mut BytesMut) -> Result<(), Self::Error> {
(**self).encode(item, dst)
}
}
3 changes: 2 additions & 1 deletion tokio-util/tests/framed_write.rs
Expand Up @@ -116,7 +116,8 @@ fn borrow_framed_write() {
assert!(assert_ready!(pin!(framed).poll_ready(cx)).is_ok());
assert!(pin!(framed).start_send(0x04).is_ok());

let mut borrow_framed = framed.with_encoder(|_| U64Encoder);
let mut new_codec = U64Encoder;
let mut borrow_framed = framed.with_encoder(|_| &mut new_codec);
assert!(assert_ready!(pin!(borrow_framed).poll_ready(cx)).is_ok());
assert!(pin!(borrow_framed).start_send(0x08).is_ok());

Expand Down

0 comments on commit 811a596

Please sign in to comment.