willow_encoding/
traits_sync.rs

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