Skip to content

Commit

Permalink
change implementation and add size hint
Browse files Browse the repository at this point in the history
Co-authored-by: neoeinstein <marcus@griep.us>
  • Loading branch information
programatik29 and neoeinstein committed May 20, 2022
1 parent 60419ac commit e1e3232
Showing 1 changed file with 33 additions and 15 deletions.
48 changes: 33 additions & 15 deletions src/limited.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Body types.
use crate::Body;
use crate::{Body, SizeHint};
use bytes::Buf;
use pin_project_lite::pin_project;
use std::{
Expand All @@ -16,8 +16,7 @@ pin_project! {
pub struct Limited<B> {
#[pin]
inner: B,
limit: usize,
read: usize,
remaining: usize,
}
}

Expand All @@ -26,8 +25,7 @@ impl<B> Limited<B> {
pub fn new(inner: B, limit: usize) -> Self {
Self {
inner,
limit,
read: 0,
remaining: limit,
}
}
}
Expand All @@ -46,20 +44,22 @@ where
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
let this = self.project();

match this.inner.poll_data(cx) {
let res = match this.inner.poll_data(cx) {
Poll::Ready(Some(Ok(data))) => {
*this.read += data.remaining();

if this.read <= this.limit {
Poll::Ready(Some(Ok(data)))
if data.remaining() > *this.remaining {
*this.remaining = 0;
Some(Err("length limit exceeded".into()))
} else {
Poll::Ready(Some(Err("body limit exceeded".into())))
*this.remaining -= data.remaining();
Some(Ok(data))
}
}
Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e.into()))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
Poll::Ready(Some(Err(e))) => Some(Err(e.into())),
Poll::Ready(None) => None,
Poll::Pending => return Poll::Pending,
};

Poll::Ready(res)
}

fn poll_trailers(
Expand All @@ -72,6 +72,24 @@ where
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}

fn size_hint(&self) -> SizeHint {
use std::convert::TryFrom;
match u64::try_from(self.remaining) {
Ok(n) => {
let mut hint = self.inner.size_hint();
if hint.lower() >= n {
hint.set_exact(n)
} else if let Some(max) = hint.upper() {
hint.set_upper(n.min(max))
} else {
hint.set_upper(n)
}
hint
}
Err(_) => self.inner.size_hint(),
}
}
}

#[cfg(test)]
Expand Down

0 comments on commit e1e3232

Please sign in to comment.