Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add "read with limit" functionality to DataStream #990

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions core/lib/src/data/data_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,43 @@ pub type InnerStream = Chain<Cursor<Vec<u8>>, BodyReader>;
/// be used as an opaque [`Read`] structure.
pub struct DataStream(crate InnerStream);

impl DataStream {
pub fn read_to_string_with_limit(
&mut self,
buf: &mut String,
limit: usize,
) -> Result<usize, LimitReadError> {
self.do_with_limit(limit, |r| r.read_to_string(buf))
}

pub fn read_to_end_with_limit(
&mut self,
buf: &mut Vec<u8>,
limit: usize,
) -> Result<usize, LimitReadError> {
self.do_with_limit(limit, |r| r.read_to_end(buf))
}

fn do_with_limit<F: FnOnce(&mut io::Take<&mut Self>) -> io::Result<T>, T>(
jebrosen marked this conversation as resolved.
Show resolved Hide resolved
&mut self,
limit: usize,
f: F,
) -> Result<T, LimitReadError> {
let mut r = self.by_ref().take(limit as u64 + 1);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using take with 1 more than the real limit is clever. Maybe a bit too clever -- I want to double check the edge cases.

let s = f(&mut r).map_err(LimitReadError::Io)?;
if r.limit() > 0 {
Ok(s)
} else {
Err(LimitReadError::LimitReached)
}
}
}

pub enum LimitReadError {
LimitReached,
Io(io::Error),
}

// TODO: Have a `BufRead` impl for `DataStream`. At the moment, this isn't
// possible since Hyper's `HttpReader` doesn't implement `BufRead`.
impl Read for DataStream {
Expand Down