use core::pin::Pin;
use core::task::{Context, Poll};
use alloc::vec::Vec;
use crate::transaction::{
AsyncWriteTransaction, Buffered, Unbuffered, WriteTransaction,
};
use crate::{AsyncWrite, Write};
#[derive(Debug)]
pub enum WriteTransactionKind<'a> {
Buffered(&'a mut Vec<u8>),
Unbuffered,
}
#[derive(Debug)]
pub enum WriteTransactionVariant<'a, W> {
Buffered(Buffered<'a, W>),
Unbuffered(Unbuffered<W>),
}
impl<'a, W> WriteTransactionVariant<'a, W> {
pub fn buffered(writer: W, buf: &'a mut Vec<u8>) -> Self {
Self::Buffered(Buffered::new(writer, buf))
}
pub fn unbuffered(writer: W) -> Self {
Self::Unbuffered(Unbuffered::new(writer))
}
pub fn new(writer: W, kind: WriteTransactionKind<'a>) -> Self {
match kind {
WriteTransactionKind::Buffered(buf) => {
Self::buffered(writer, buf)
},
WriteTransactionKind::Unbuffered => {
Self::unbuffered(writer)
},
}
}
pub fn writer(&self) -> &W {
match self {
Self::Buffered(x) => x.writer(),
Self::Unbuffered(x) => x.writer(),
}
}
pub fn writer_mut(&mut self) -> &mut W {
match self {
Self::Buffered(x) => x.writer_mut(),
Self::Unbuffered(x) => x.writer_mut(),
}
}
}
impl<'a, W> Write for WriteTransactionVariant<'a, W>
where
W: Write,
{
type Error = W::Error;
fn write_slice(
&mut self,
buf: &[u8],
) -> Result<usize, Self::Error> {
match self {
Self::Buffered(x) => x.write_slice(buf),
Self::Unbuffered(x) => x.write_slice(buf),
}
}
fn flush_once(&mut self) -> Result<(), Self::Error> {
match self {
Self::Buffered(x) => x.flush_once(),
Self::Unbuffered(x) => x.flush_once(),
}
}
}
impl<'a, W> WriteTransaction for WriteTransactionVariant<'a, W>
where
W: Write,
{
fn finish(self) -> Result<(), Self::Error> {
match self {
Self::Buffered(x) => x.finish(),
Self::Unbuffered(x) => x.finish(),
}
}
}
impl<'a, W> AsyncWrite for WriteTransactionVariant<'a, W>
where
W: AsyncWrite + Unpin,
{
type Error = W::Error;
fn poll_write_slice(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8],
) -> Poll<Result<usize, Self::Error>> {
match *self {
Self::Buffered(ref mut x) => {
Pin::new(x).poll_write_slice(cx, buf)
},
Self::Unbuffered(ref mut x) => {
Pin::new(x).poll_write_slice(cx, buf)
},
}
}
fn poll_flush_once(
mut self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Result<(), Self::Error>> {
match *self {
Self::Buffered(ref mut x) => {
Pin::new(x).poll_flush_once(cx)
},
Self::Unbuffered(ref mut x) => {
Pin::new(x).poll_flush_once(cx)
},
}
}
}
impl<'a, W> AsyncWriteTransaction for WriteTransactionVariant<'a, W>
where
W: AsyncWrite + Unpin,
{
fn poll_finish(
mut self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Result<(), Self::Error>> {
match *self {
Self::Buffered(ref mut x) => Pin::new(x).poll_finish(cx),
Self::Unbuffered(ref mut x) => {
Pin::new(x).poll_finish(cx)
},
}
}
}