Struct asynchronous_codec::LengthCodec
source · [−]pub struct LengthCodec;
Expand description
A simple Codec
implementation sending your data by prefixing it by its length.
Example
This codec will most likely be used wrapped in another codec like so.
use asynchronous_codec::{Decoder, Encoder, LengthCodec};
use bytes::{Bytes, BytesMut};
use std::io::{Error, ErrorKind};
pub struct MyStringCodec(LengthCodec);
impl Encoder for MyStringCodec {
type Item = String;
type Error = Error;
fn encode(&mut self, src: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let bytes = Bytes::from(src);
self.0.encode(bytes, dst)
}
}
impl Decoder for MyStringCodec {
type Item = String;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
match self.0.decode(src)? {
Some(bytes) => {
match String::from_utf8(bytes.to_vec()) {
Ok(string) => Ok(Some(string)),
Err(e) => Err(Error::new(ErrorKind::InvalidData, e))
}
},
None => Ok(None),
}
}
}
Trait Implementations
Auto Trait Implementations
impl RefUnwindSafe for LengthCodec
impl Send for LengthCodec
impl Sync for LengthCodec
impl Unpin for LengthCodec
impl UnwindSafe for LengthCodec
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcepub fn borrow_mut(&mut self) -> &mut T
pub fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more