use std::io;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use crate::AsyncClose;
use crate::AsyncOutput;
use crate::traits::normalize_async_error;
#[must_use]
#[derive(Debug)]
pub struct AsyncLimitOutput<O> {
inner: O,
remaining: u64,
}
impl<O> AsyncClose for AsyncLimitOutput<O>
where
O: AsyncClose,
{
#[inline(always)]
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = unsafe { self.get_unchecked_mut() };
unsafe { Pin::new_unchecked(&mut this.inner) }
.poll_close(cx)
.map(|result| result.map_err(normalize_async_error))
}
}
impl<O> AsyncLimitOutput<O> {
#[inline(always)]
pub const fn new(inner: O, limit: u64) -> Self {
Self {
inner,
remaining: limit,
}
}
#[inline(always)]
#[must_use]
pub const fn remaining(&self) -> u64 {
self.remaining
}
#[inline(always)]
#[must_use]
pub const fn inner(&self) -> &O {
&self.inner
}
#[inline(always)]
#[must_use]
pub fn inner_mut(&mut self) -> &mut O {
&mut self.inner
}
#[inline(always)]
#[must_use]
pub fn into_inner(self) -> O {
self.inner
}
}
impl<O> AsyncOutput for AsyncLimitOutput<O>
where
O: AsyncOutput,
{
type Item = O::Item;
#[inline(always)]
fn is_buffered(&self) -> bool {
self.inner.is_buffered()
}
unsafe fn poll_write_unchecked(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
input: &[Self::Item],
index: usize,
count: usize,
) -> Poll<io::Result<usize>> {
let this = unsafe { self.as_mut().get_unchecked_mut() };
if this.remaining == 0 || count == 0 {
return Poll::Ready(Ok(0));
}
let requested = usize::try_from(this.remaining).unwrap_or(usize::MAX).min(count);
let source = &input[index..index + requested];
let inner = unsafe { Pin::new_unchecked(&mut this.inner) };
match inner.poll_write(cx, source) {
Poll::Ready(Ok(written)) => {
this.remaining -= written as u64;
Poll::Ready(Ok(written))
}
Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
Poll::Pending => Poll::Pending,
}
}
#[inline(always)]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = unsafe { self.get_unchecked_mut() };
unsafe { Pin::new_unchecked(&mut this.inner) }
.poll_flush(cx)
.map(|result| result.map_err(normalize_async_error))
}
}