Skip to main content

apalis_core/backend/
codec.rs

1//! Utilities for encoding and decoding task arguments and results
2//!
3//! # Overview
4//!
5//! The `Codec` trait allows for converting values
6//! between a type `T` and a more compact or transport-friendly representation.
7//! This is particularly useful for serializing/deserializing, compressing/expanding,
8//! or otherwise encoding/decoding values in a custom format.
9
10/// A trait for converting values between a type `T` and a more compact or
11/// transport-friendly representation for a `Backend`. Examples include json
12/// and bytes.
13///
14/// This is useful when you need to serialize/deserialize, compress/expand,
15/// or otherwise encode/decode values in a custom format.
16///
17/// By default, a backend doesn't care about the specific type implementing [`Codec`]
18/// but rather the [`Codec::Compact`] type. This means if it can accept bytes, you
19/// can use familiar crates such as bincode and rkyv
20///
21/// # Type Parameters
22/// - `T`: The type of value being encoded/decoded.
23pub trait Codec<T> {
24    /// The error type returned if encoding or decoding fails.
25    type Error;
26
27    /// The compact or encoded representation of `T`.
28    ///
29    /// This could be a primitive type, a byte buffer, or any other
30    /// representation that is more efficient to store or transmit.
31    type Compact;
32
33    /// Encode a value of type `T` into its compact representation.
34    ///
35    /// # Errors
36    /// Returns [`Self::Error`] if the value cannot be encoded.
37    fn encode(&self, val: &T) -> Result<Self::Compact, Self::Error>;
38
39    /// Decode a compact representation back into a value of type `T`.
40    ///
41    /// # Errors
42    /// Returns [`Self::Error`] if the compact representation cannot
43    /// be decoded into a valid `T`.
44    fn decode(&self, val: &Self::Compact) -> Result<T, Self::Error>;
45}