Skip to content

Commit 167f798

Browse files
committed
Implement Cursor::{remaining, is_empty}
1 parent 7ec478d commit 167f798

File tree

1 file changed

+59
-4
lines changed

1 file changed

+59
-4
lines changed

std/src/io/cursor.rs

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,62 @@ impl<T> Cursor<T> {
205205
}
206206
}
207207

208+
impl<T> Cursor<T>
209+
where
210+
T: AsRef<[u8]>,
211+
{
212+
/// Returns the remaining slice.
213+
///
214+
/// # Examples
215+
///
216+
/// ```
217+
/// #![feature(cursor_remaining)]
218+
/// use std::io::Cursor;
219+
///
220+
/// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
221+
///
222+
/// assert_eq!(buff.remaining(), &[1, 2, 3, 4, 5]);
223+
///
224+
/// buff.set_position(2);
225+
/// assert_eq!(buff.remaining(), &[3, 4, 5]);
226+
///
227+
/// buff.set_position(4);
228+
/// assert_eq!(buff.remaining(), &[5]);
229+
///
230+
/// buff.set_position(6);
231+
/// assert_eq!(buff.remaining(), &[]);
232+
/// ```
233+
#[unstable(feature = "cursor_remaining", issue = "none")]
234+
pub fn remaining(&self) -> &[u8] {
235+
let len = self.pos.min(self.inner.as_ref().len() as u64);
236+
&self.inner.as_ref()[(len as usize)..]
237+
}
238+
239+
/// Returns `true` if the remaining slice is empty.
240+
///
241+
/// # Examples
242+
///
243+
/// ```
244+
/// #![feature(cursor_remaining)]
245+
/// use std::io::Cursor;
246+
///
247+
/// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
248+
///
249+
/// buff.set_position(2);
250+
/// assert!(!buff.is_empty());
251+
///
252+
/// buff.set_position(5);
253+
/// assert!(buff.is_empty());
254+
///
255+
/// buff.set_position(10);
256+
/// assert!(buff.is_empty());
257+
/// ```
258+
#[unstable(feature = "cursor_remaining", issue = "none")]
259+
pub fn is_empty(&self) -> bool {
260+
self.pos >= self.inner.as_ref().len() as u64
261+
}
262+
}
263+
208264
#[stable(feature = "rust1", since = "1.0.0")]
209265
impl<T> Clone for Cursor<T>
210266
where
@@ -268,7 +324,7 @@ where
268324
T: AsRef<[u8]>,
269325
{
270326
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
271-
let n = Read::read(&mut self.fill_buf()?, buf)?;
327+
let n = Read::read(&mut self.remaining(), buf)?;
272328
self.pos += n as u64;
273329
Ok(n)
274330
}
@@ -291,7 +347,7 @@ where
291347

292348
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
293349
let n = buf.len();
294-
Read::read_exact(&mut self.fill_buf()?, buf)?;
350+
Read::read_exact(&mut self.remaining(), buf)?;
295351
self.pos += n as u64;
296352
Ok(())
297353
}
@@ -308,8 +364,7 @@ where
308364
T: AsRef<[u8]>,
309365
{
310366
fn fill_buf(&mut self) -> io::Result<&[u8]> {
311-
let amt = cmp::min(self.pos, self.inner.as_ref().len() as u64);
312-
Ok(&self.inner.as_ref()[(amt as usize)..])
367+
Ok(self.remaining())
313368
}
314369
fn consume(&mut self, amt: usize) {
315370
self.pos += amt as u64;

0 commit comments

Comments
 (0)