fuel_compression/
traits.rs

1#![allow(async_fn_in_trait)] // We control the implementation so this is fine
2
3/// Defines the error type for the context used in compression and decompression.
4pub trait ContextError {
5    /// The error type returned by the context.
6    type Error;
7}
8
9/// This type can be compressed to a more compact form and back using
10/// `CompressibleBy` and `DecompressibleBy` traits.
11pub trait Compressible {
12    /// The compressed type.
13    type Compressed: Sized;
14}
15
16/// This type can be compressed to a more compact form and back using
17/// `CompressionContext`.
18pub trait CompressibleBy<Ctx>: Compressible
19where
20    Ctx: ContextError,
21{
22    /// Perform compression, returning the compressed data and possibly modifying the
23    /// context. The context is mutable to allow for stateful compression.
24    /// For instance, it can be used to extract original data when replacing it with
25    /// references.
26    async fn compress_with(&self, ctx: &mut Ctx) -> Result<Self::Compressed, Ctx::Error>;
27}
28
29/// This type can be decompressed using `CompressionContext`.
30pub trait DecompressibleBy<Ctx>: Compressible
31where
32    Ctx: ContextError,
33    Self: Sized,
34{
35    /// Perform decompression, returning the original data.
36    /// The context can be used to resolve references.
37    async fn decompress_with(c: Self::Compressed, ctx: &Ctx) -> Result<Self, Ctx::Error>;
38}
39
40/// The trait allows for decompression of a compressed type.
41/// This trait is syntax sugar for `DecompressibleBy` with the compressed type as the
42/// receiver.
43pub trait Decompress<Decompressed, Ctx>
44where
45    Ctx: ContextError,
46{
47    /// Perform decompression, returning the original data.
48    async fn decompress(self, ctx: &Ctx) -> Result<Decompressed, Ctx::Error>;
49}
50
51impl<T, Ctx, Decompressed> Decompress<Decompressed, Ctx> for T
52where
53    Ctx: ContextError,
54    Decompressed: DecompressibleBy<Ctx, Compressed = Self>,
55{
56    async fn decompress(self, ctx: &Ctx) -> Result<Decompressed, Ctx::Error> {
57        Decompressed::decompress_with(self, ctx).await
58    }
59}