connection-utils 0.8.0

Connection related utilities.
Documentation
use std::io::{Error, ErrorKind};

use bytes::BytesMut;
use serde::{Serialize, de::DeserializeOwned};
use tokio_util::codec::Decoder;

use super::GenericLinesCodec;

impl<T: Serialize + DeserializeOwned> Decoder for GenericLinesCodec<T> {
    type Item = T;
    type Error = Error;

    fn decode(
        &mut self,
        buf: &mut BytesMut,
    ) -> Result<Option<Self::Item>, Self::Error> {
        let str_result = Decoder::decode(
            &mut self.length_delimited_codec, 
            buf,
        );

        let maybe_str = match str_result {
            Ok(s) => s,
            Err(_err) => return Err(
                Error::new(
                    ErrorKind::InvalidData,
                    format!("Cannot decode input: {:0>2X?}.", buf),
                ),
            ),
        };

        let string = match maybe_str {
            None => return Ok(None),
            Some(b) => b,
        };

        let message: T = serde_json::from_str(&string)
            .expect(
                &format!(
                    "Cannot deserialize string to message: {:?}.",
                    &string,
                ),
            );

        return Ok(Some(message));
    } 
}