File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed
library/std/src/io/buffered Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -94,6 +94,32 @@ impl<R: Read> BufReader<R> {
9494 pub fn with_capacity ( capacity : usize , inner : R ) -> BufReader < R > {
9595 BufReader { inner, buf : Buffer :: with_capacity ( capacity) }
9696 }
97+
98+ /// Attempt to look ahead `n` bytes.
99+ ///
100+ /// `n` must be less than `capacity`.
101+ ///
102+ /// ## Examples
103+ ///
104+ /// ```rust
105+ /// #![feature(bufreader_peek)]
106+ /// use std::io::{Read, BufReader};
107+ ///
108+ /// let mut bytes = &b"hello"[..];
109+ /// let mut rdr = BufReader::with_capacity(6, &mut bytes);
110+ /// assert_eq!(rdr.peek(2).unwrap(), b"he");
111+ /// let mut s = String::new();
112+ /// rdr.read_to_string(&mut s).unwrap();
113+ /// assert_eq!(&s, "hello");
114+ /// ```
115+ #[ unstable( feature = "bufreader_peek" , issue = "128405" ) ]
116+ pub fn peek ( & mut self , n : usize ) -> io:: Result < & [ u8 ] > {
117+ assert ! ( n < self . capacity( ) ) ;
118+ while n > self . buf . buffer ( ) . len ( ) {
119+ self . buf . read_more ( & mut self . inner ) ?;
120+ }
121+ Ok ( & self . buf . buffer ( ) [ ..n] )
122+ }
97123}
98124
99125impl < R : ?Sized > BufReader < R > {
Original file line number Diff line number Diff line change @@ -97,6 +97,18 @@ impl Buffer {
9797 self . pos = self . pos . saturating_sub ( amt) ;
9898 }
9999
100+ pub fn read_more ( & mut self , mut reader : impl Read ) -> io:: Result < ( ) > {
101+ let mut buf = BorrowedBuf :: from ( & mut self . buf [ self . pos ..] ) ;
102+ let old_init = self . initialized - self . pos ;
103+ unsafe {
104+ buf. set_init ( old_init) ;
105+ }
106+ reader. read_buf ( buf. unfilled ( ) ) ?;
107+ self . filled += buf. len ( ) ;
108+ self . initialized += buf. init_len ( ) - old_init;
109+ Ok ( ( ) )
110+ }
111+
100112 #[ inline]
101113 pub fn fill_buf ( & mut self , mut reader : impl Read ) -> io:: Result < & [ u8 ] > {
102114 // If we've reached the end of our internal buffer then we need to fetch
You can’t perform that action at this time.
0 commit comments