compio_io/framed/codec/bytes.rs
1//! [`Encoder`]/[`Decoder`] implementation with Bytes
2//!
3//! This module provides a codec implementation for bytes serialization and
4//! deserialization (noop per se).
5//!
6//! # Examples
7//!
8//! ```
9//! use compio_buf::{IoBuf, bytes::Bytes};
10//! use compio_io::framed::codec::{Decoder, Encoder, bytes::BytesCodec};
11//!
12//! let mut codec = BytesCodec::new();
13//! let data = Bytes::from("Hello, world!");
14//!
15//! // Encoding
16//! let mut buffer = Vec::new();
17//! codec.encode(data.clone(), &mut buffer).unwrap();
18//!
19//! // Decoding
20//! let decoded = codec.decode(&buffer.slice(..)).unwrap();
21//! assert_eq!(decoded, data);
22//! ```
23use std::io::{self, Write};
24
25use compio_buf::{IoBuf, IoBufMut, Slice, bytes::Bytes};
26
27use crate::framed::codec::{Decoder, Encoder};
28
29/// A codec for bytes serialization and deserialization.
30///
31/// This codec can be used to write into and read from [`Bytes`].
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub struct BytesCodec;
34
35impl BytesCodec {
36 /// Creates a new `BytesCodec`.
37 pub fn new() -> Self {
38 Self {}
39 }
40}
41
42impl Default for BytesCodec {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48impl<B: IoBufMut> Encoder<Bytes, B> for BytesCodec {
49 type Error = io::Error;
50
51 fn encode(&mut self, item: Bytes, buf: &mut B) -> Result<(), Self::Error> {
52 let mut writer = buf.as_writer();
53 writer.write_all(&item)?;
54 Ok(())
55 }
56}
57
58impl<B: IoBuf> Decoder<Bytes, B> for BytesCodec {
59 type Error = io::Error;
60
61 fn decode(&mut self, buf: &Slice<B>) -> Result<Bytes, Self::Error> {
62 let inner = buf.as_ref().to_vec();
63 Ok(Bytes::from(inner))
64 }
65}