willow_encoding/
traits.rs

1use std::future::Future;
2
3use crate::error::DecodeError;
4use ufotofu::local_nb::{BulkConsumer, BulkProducer};
5
6/// A type that can be encoded to a bytestring, ensuring that any value of `Self` maps to exactly one bytestring.
7///
8/// [Definition](https://willowprotocol.org/specs/encodings/index.html#encodings_what)
9pub trait Encodable {
10    /// Encode a value to a bytestring in a specific way that is best described over at [willowprotocol.org](https://willowprotocol.org/specs/encodings/index.html#encodings_what).
11    ///
12    /// [Definition](https://willowprotocol.org/specs/encodings/index.html#encode_s)
13    fn encode<Consumer>(
14        &self,
15        consumer: &mut Consumer,
16    ) -> impl Future<Output = Result<(), Consumer::Error>>
17    where
18        Consumer: BulkConsumer<Item = u8>;
19}
20
21/// A type that can be decoded from a bytestring, ensuring that every valid encoding maps to exactly one member of `Self`.
22///
23/// [Definition](https://willowprotocol.org/specs/encodings/index.html#encodings_what)
24pub trait Decodable {
25    /// Decade a value to a bytestring in a specific way that is best described over at [willowprotocol.org](https://willowprotocol.org/specs/encodings/index.html#encodings_what).
26    ///
27    /// [Definition](https://willowprotocol.org/specs/encodings/index.html#decode_s)
28    fn decode<Producer>(
29        producer: &mut Producer,
30    ) -> impl Future<Output = Result<Self, DecodeError<Producer::Error>>>
31    where
32        Producer: BulkProducer<Item = u8>,
33        Self: Sized;
34}
35
36/// A type that can be used to encode `T` to a bytestring *encoded relative to `R`*.
37/// This can be used to create more compact encodings from which `T` can be derived by anyone with `R`.
38pub trait RelativeEncodable<R> {
39    /// Encode a value (relative to a reference value) to a bytestring in a specific way that is best described over at [willowprotocol.org](https://willowprotocol.org/specs/encodings/index.html#encodings_what).
40    fn relative_encode<Consumer>(
41        &self,
42        reference: &R,
43        consumer: &mut Consumer,
44    ) -> impl Future<Output = Result<(), Consumer::Error>>
45    where
46        Consumer: BulkConsumer<Item = u8>;
47}
48
49/// A type that can be used to decode `T` from a bytestring *encoded relative to `Self`*.
50/// This can be used to decode a compact encoding frow which `T` can be derived by anyone with `R`.
51pub trait RelativeDecodable<R> {
52    /// Decode a value (relative to a reference value) to a bytestring in a specific way that is best described over at [willowprotocol.org](https://willowprotocol.org/specs/encodings/index.html#encodings_what).
53    fn relative_decode<Producer>(
54        reference: &R,
55        producer: &mut Producer,
56    ) -> impl Future<Output = Result<Self, DecodeError<Producer::Error>>>
57    where
58        Producer: BulkProducer<Item = u8>,
59        Self: Sized;
60}