#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{boxed::Box, vec::Vec};
use crate::prelude::*;
pub trait Encodable<Symbol = u8> {
async fn encode<C>(&self, consumer: &mut C) -> Result<(), C::Error>
where
C: BulkConsumer<Item = Symbol> + ?Sized;
}
impl<T, Symbol> Encodable<Symbol> for &T
where
T: Encodable<Symbol>,
{
async fn encode<C>(&self, consumer: &mut C) -> Result<(), C::Error>
where
C: BulkConsumer<Item = Symbol> + ?Sized,
{
(*self).encode(consumer).await
}
}
pub trait EncodableExt<Symbol = u8>: Encodable<Symbol> {
#[cfg(feature = "alloc")]
async fn new_vec_storing_encoding(&self) -> Vec<Symbol>
where
Symbol: Default,
{
let mut c = Vec::new().into_consumer();
match self.encode(&mut c).await {
Ok(()) => c.into(),
Err(_) => unreachable!(),
}
}
}
impl<T, S> EncodableExt<S> for T where T: Encodable<S> {}
pub trait EncodableKnownLength<Symbol = u8>: Encodable<Symbol> {
fn len_of_encoding(&self) -> usize;
}
impl<T, Symbol> EncodableKnownLength<Symbol> for &T
where
T: EncodableKnownLength<Symbol>,
{
fn len_of_encoding(&self) -> usize {
(*self).len_of_encoding()
}
}
pub trait EncodableKnownLengthExt<Symbol = u8>: EncodableKnownLength<Symbol> {
#[cfg(feature = "alloc")]
async fn new_boxed_slice_storing_encoding(&self) -> Box<[Symbol]>
where
Symbol: Default,
{
let mut c = Vec::with_capacity(self.len_of_encoding()).into_consumer();
match self.encode(&mut c).await {
Ok(()) => Vec::<Symbol>::from(c).into_boxed_slice(),
Err(_) => unreachable!(),
}
}
}
impl<T, S> EncodableKnownLengthExt<S> for T where T: EncodableKnownLength<S> {}