@@ -99,7 +99,10 @@ impl<R: Read> BufReader<R> {
9999impl < R : Read + ?Sized > BufReader < R > {
100100/// Attempt to look ahead `n` bytes.
101101///
102- /// `n` must be less than `capacity`.
102+ /// `n` must be less than or equal to `capacity`.
103+ ///
104+ /// the returned slice may be less than `n` bytes long if
105+ /// end of file is reached.
103106///
104107/// ## Examples
105108///
@@ -117,6 +120,7 @@ impl<R: Read + ?Sized> BufReader<R> {
117120/// let mut s = String::new();
118121/// rdr.read_to_string(&mut s).unwrap();
119122/// assert_eq!(&s, "hello");
123+ /// assert_eq!(rdr.peek(1).unwrap().len(), 0);
120124/// ```
121125#[ unstable( feature = "bufreader_peek" , issue = "128405" ) ]
122126pub fn peek ( & mut self , n : usize ) -> io:: Result < & [ u8 ] > {
@@ -125,7 +129,11 @@ impl<R: Read + ?Sized> BufReader<R> {
125129if self . buf . pos ( ) > 0 {
126130self . buf . backshift ( ) ;
127131}
128- self . buf . read_more ( & mut self . inner ) ?;
132+ let new = self . buf . read_more ( & mut self . inner ) ?;
133+ if new == 0 {
134+ // end of file, no more bytes to read
135+ return Ok ( & self . buf . buffer ( ) [ ..] ) ;
136+ }
129137debug_assert_eq ! ( self . buf. pos( ) , 0 ) ;
130138}
131139Ok ( & self . buf . buffer ( ) [ ..n] )
0 commit comments