|
| 1 | +//! Encoding and decoding for tokio |
| 2 | +
|
| 3 | +use crate::error::Category; |
| 4 | +use crate::Error; |
| 5 | + |
| 6 | +use std::marker::PhantomData; |
| 7 | + |
| 8 | +use bytes::{buf::ext::BufMutExt, buf::Buf, BytesMut}; |
| 9 | +use serde::de::DeserializeOwned; |
| 10 | +use serde::Serialize; |
| 11 | +use tokio_util::codec; |
| 12 | + |
| 13 | +/// A `tokio_util::codec::Encoder` for CBOR frames |
| 14 | +pub struct Encoder<T: Serialize>(PhantomData<T>); |
| 15 | + |
| 16 | +impl<T: Serialize> Default for Encoder<T> { |
| 17 | + fn default() -> Self { |
| 18 | + Self(PhantomData) |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl<T: Serialize> codec::Encoder<&T> for Encoder<T> { |
| 23 | + type Error = Error; |
| 24 | + |
| 25 | + fn encode(&mut self, item: &T, dst: &mut BytesMut) -> Result<(), Error> { |
| 26 | + crate::to_writer(dst.writer(), item) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/// A `tokio_util::codec::Decoder` for CBOR frames |
| 31 | +pub struct Decoder<T: DeserializeOwned>(PhantomData<T>); |
| 32 | + |
| 33 | +impl<T: DeserializeOwned> Default for Decoder<T> { |
| 34 | + fn default() -> Self { |
| 35 | + Self(PhantomData) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl<T: DeserializeOwned> codec::Decoder for Decoder<T> { |
| 40 | + type Item = T; |
| 41 | + type Error = Error; |
| 42 | + |
| 43 | + fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Error> { |
| 44 | + let mut bytes: &[u8] = src.as_ref(); |
| 45 | + let starting = bytes.len(); |
| 46 | + |
| 47 | + let item: T = match crate::from_reader(&mut bytes) { |
| 48 | + Err(e) if e.classify() == Category::Eof => return Ok(None), |
| 49 | + Ok(v) => v, |
| 50 | + e => e?, |
| 51 | + }; |
| 52 | + |
| 53 | + let ending = bytes.len(); |
| 54 | + src.advance(starting - ending); |
| 55 | + Ok(Some(item)) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +/// A Codec for CBOR frames |
| 60 | +#[derive(Default)] |
| 61 | +pub struct Codec<T: Serialize, U: DeserializeOwned>(Encoder<T>, Decoder<U>); |
| 62 | + |
| 63 | +impl<T: Serialize, U: DeserializeOwned> codec::Encoder<&T> for Codec<T, U> { |
| 64 | + type Error = Error; |
| 65 | + |
| 66 | + #[inline] |
| 67 | + fn encode(&mut self, item: &T, dst: &mut BytesMut) -> Result<(), Error> { |
| 68 | + self.0.encode(item, dst) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl<T: Serialize, U: DeserializeOwned> codec::Decoder for Codec<T, U> { |
| 73 | + type Item = U; |
| 74 | + type Error = Error; |
| 75 | + |
| 76 | + #[inline] |
| 77 | + fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Error> { |
| 78 | + self.1.decode(src) |
| 79 | + } |
| 80 | +} |
0 commit comments