Skip to content

Fix io::Take behavior with limit 0 #22640

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

Merged
merged 2 commits into from
Feb 23, 2015
Merged
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
35 changes: 35 additions & 0 deletions src/libstd/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,13 +669,33 @@ impl<T> Take<T> {

impl<T: Read> Read for Take<T> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
// Don't call into inner reader at all at EOF because it may still block
if self.limit == 0 {
return Ok(0);
}

let max = cmp::min(buf.len() as u64, self.limit) as usize;
let n = try!(self.inner.read(&mut buf[..max]));
self.limit -= n as u64;
Ok(n)
}
}

impl<T: BufRead> BufRead for Take<T> {
fn fill_buf(&mut self) -> Result<&[u8]> {
let buf = try!(self.inner.fill_buf());
let cap = cmp::min(buf.len() as u64, self.limit) as usize;
Ok(&buf[..cap])
}

fn consume(&mut self, amt: usize) {
// Don't let callers reset the limit by passing an overlarge value
let amt = cmp::min(amt as u64, self.limit) as usize;
self.limit -= amt as u64;
self.inner.consume(amt);
}
}

/// An adaptor which will emit all read data to a specified writer as well.
///
/// For more information see `ReadExt::tee`
Expand Down Expand Up @@ -846,6 +866,7 @@ impl<B: BufRead> Iterator for Lines<B> {
mod tests {
use prelude::v1::*;
use io::prelude::*;
use io;
use super::Cursor;

#[test]
Expand Down Expand Up @@ -943,4 +964,18 @@ mod tests {
let mut v = String::new();
assert!(c.read_to_string(&mut v).is_err());
}

#[test]
fn take_eof() {
struct R;

impl Read for R {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::Other, "", None))
}
}

let mut buf = [0; 1];
assert_eq!(Ok(0), R.take(0).read(&mut buf));
}
}