File tree 2 files changed +39
-0
lines changed
library/std/src/io/buffered
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -94,6 +94,33 @@ impl<R: Read> BufReader<R> {
94
94
pub fn with_capacity ( capacity : usize , inner : R ) -> BufReader < R > {
95
95
BufReader { inner, buf : Buffer :: with_capacity ( capacity) }
96
96
}
97
+
98
+
99
+ /// Attempt to look ahead `n` bytes.
100
+ ///
101
+ /// `n` must be less than `capacity`.
102
+ ///
103
+ /// ## Examples
104
+ ///
105
+ /// ```rust
106
+ /// #![feature(bufreader_peek)]
107
+ /// use std::io::{Read, BufReader};
108
+ ///
109
+ /// let mut bytes = &b"hello"[..];
110
+ /// let mut rdr = BufReader::with_capacity(6, &mut bytes);
111
+ /// assert_eq!(rdr.peek(2).unwrap(), b"he");
112
+ /// let mut s = String::new();
113
+ /// rdr.read_to_string(&mut s).unwrap();
114
+ /// assert_eq!(&s, "hello");
115
+ /// ```
116
+ #[ unstable( feature = "bufreader_peek" , issue = "128405" ) ]
117
+ pub fn peek ( & mut self , n : usize ) -> io:: Result < & [ u8 ] > {
118
+ assert ! ( n < self . capacity( ) ) ;
119
+ while n > self . buf . buffer ( ) . len ( ) {
120
+ self . buf . read_more ( & mut self . inner ) ?;
121
+ }
122
+ Ok ( & self . buf . buffer ( ) [ ..n] )
123
+ }
97
124
}
98
125
99
126
impl < R : ?Sized > BufReader < R > {
Original file line number Diff line number Diff line change @@ -97,6 +97,18 @@ impl Buffer {
97
97
self . pos = self . pos . saturating_sub ( amt) ;
98
98
}
99
99
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
+
100
112
#[ inline]
101
113
pub fn fill_buf ( & mut self , mut reader : impl Read ) -> io:: Result < & [ u8 ] > {
102
114
// 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