use std::io;
use crate::{PlainOldData, RawRepr, ReadableError, TryFromRawRepr};
pub trait AsyncFixedReadable: Sized {
fn read_fixed_from(
reader: &mut (impl tokio::io::AsyncReadExt + ?Sized + Unpin),
) -> impl Future<Output = Result<Self, ReadableError>>;
}
impl<T: TryFromRawRepr> AsyncFixedReadable for T {
#[inline]
fn read_fixed_from(
reader: &mut (impl tokio::io::AsyncReadExt + ?Sized + Unpin),
) -> impl Future<Output = Result<Self, ReadableError>> {
async {
let mut b = T::Raw::zeroed();
reader.read_exact(b.as_bytes_mut()).await?;
let r = T::try_from_raw(b)?;
Ok(r)
}
}
}
pub trait AsyncReadable: Sized {
fn read_from(
reader: &mut (impl tokio::io::AsyncReadExt + ?Sized + Unpin),
) -> impl Future<Output = Result<Self, ReadableError>>;
}
impl<T: AsyncFixedReadable> AsyncReadable for T {
#[inline]
fn read_from(
reader: &mut (impl tokio::io::AsyncReadExt + ?Sized + Unpin),
) -> impl Future<Output = Result<Self, ReadableError>> {
T::read_fixed_from(reader)
}
}
pub trait AsyncFixedWritable {
fn write_fixed_to(
&self,
writer: &mut (impl tokio::io::AsyncWriteExt + ?Sized + Unpin),
) -> impl Future<Output = io::Result<()>>;
}
impl<T: RawRepr> AsyncFixedWritable for T {
#[inline]
fn write_fixed_to(
&self,
writer: &mut (impl tokio::io::AsyncWriteExt + ?Sized + Unpin),
) -> impl Future<Output = io::Result<()>> {
async {
let raw = self.to_raw();
writer.write_all(raw.as_bytes()).await
}
}
}
pub trait AsyncWritable {
fn write_to(
&self,
writer: &mut (impl tokio::io::AsyncWriteExt + ?Sized + Unpin),
) -> impl Future<Output = io::Result<()>>;
}
impl<T: AsyncFixedWritable> AsyncWritable for T {
#[inline]
fn write_to(
&self,
writer: &mut (impl tokio::io::AsyncWriteExt + ?Sized + Unpin),
) -> impl Future<Output = io::Result<()>> {
self.write_fixed_to(writer)
}
}
pub trait AsyncReadFixed: tokio::io::AsyncReadExt + Unpin {
#[inline]
fn read_fixed<T: AsyncFixedReadable>(
&mut self,
) -> impl Future<Output = Result<T, ReadableError>> {
T::read_fixed_from(self)
}
}
impl<T: tokio::io::AsyncReadExt + ?Sized + Unpin> AsyncReadFixed for T {}
pub trait AsyncReadValue: tokio::io::AsyncReadExt + Unpin {
#[inline]
fn read_value<T: AsyncReadable>(&mut self) -> impl Future<Output = Result<T, ReadableError>> {
T::read_from(self)
}
}
impl<T: tokio::io::AsyncReadExt + ?Sized + Unpin> AsyncReadValue for T {}
pub trait AsyncWriteFixed: tokio::io::AsyncWriteExt + Unpin {
#[inline]
fn write_fixed(
&mut self,
val: &impl AsyncFixedWritable,
) -> impl Future<Output = io::Result<()>> {
val.write_fixed_to(self)
}
}
impl<T: tokio::io::AsyncWriteExt + ?Sized + Unpin> AsyncWriteFixed for T {}
pub trait AsyncWriteValue: tokio::io::AsyncWriteExt + Unpin {
#[inline]
fn write_value<T: AsyncWritable + ?Sized>(
&mut self,
data: &T,
) -> impl Future<Output = io::Result<()>> {
data.write_to(self)
}
}
impl<T: tokio::io::AsyncWriteExt + ?Sized + Unpin> AsyncWriteValue for T {}