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