Skip to main content

compio_io/framed/codec/
mod.rs

1//! Traits and implementations for encoding/decoding structured types to/from
2//! bytes.
3
4use std::io;
5
6use compio_buf::{IoBuf, IoBufMut, Slice};
7
8#[cfg(feature = "bytes")]
9pub mod bytes;
10
11#[cfg(feature = "codec-serde-json")]
12pub mod serde_json;
13
14/// Trait for types that encode values into bytes.
15pub trait Encoder<Item, B: IoBufMut> {
16    /// The error type that can be returned during encoding operations.
17    type Error: From<io::Error>;
18
19    /// Encodes an item into bytes.
20    ///
21    /// The `buf` is *guaranteed* to have 0 initialized bytes (`buf_len()` ==
22    /// 0). If the function is returned successfully, all initialized bytes will
23    /// be treated as valid content to be transmitted.
24    fn encode(&mut self, item: Item, buf: &mut B) -> Result<(), Self::Error>;
25}
26
27/// Trait for decoding byte sequences back into structured items.
28pub trait Decoder<Item, B: IoBuf> {
29    /// Errors happened during the decoding process
30    type Error: From<io::Error>;
31
32    /// Decodes a byte sequence into an item.
33    ///
34    /// The given `buf` is a sliced view into the underlying buffer, which gives
35    /// one complete frame. [`Slice`] implements [`IoBuf`].
36    ///
37    /// You may escape the view by calling [`Slice::as_inner`].
38    fn decode(&mut self, buf: &Slice<B>) -> Result<Item, Self::Error>;
39}