Skip to content

Commit

Permalink
rename remaining to remaining_slice and add a new remaining
Browse files Browse the repository at this point in the history
  • Loading branch information
soerenmeier committed Jun 17, 2021
1 parent 212e91a commit 664bde0
Showing 1 changed file with 34 additions and 8 deletions.
42 changes: 34 additions & 8 deletions library/std/src/io/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,32 @@ impl<T> Cursor<T>
where
T: AsRef<[u8]>,
{
/// Returns the remaining length.
///
/// # Examples
///
/// ```
/// #![feature(cursor_remaining)]
/// use std::io::Cursor;
///
/// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
///
/// assert_eq!(buff.remaining(), 5);
///
/// buff.set_position(2);
/// assert_eq!(buff.remaining(), 3);
///
/// buff.set_position(4);
/// assert_eq!(buff.remaining(), 1);
///
/// buff.set_position(6);
/// assert_eq!(buff.remaining(), 0);
/// ```
#[unstable(feature = "cursor_remaining", issue = "86369")]
pub fn remaining(&self) -> u64 {
(self.inner.as_ref().len() as u64).checked_sub(self.pos).unwrap_or(0)
}

/// Returns the remaining slice.
///
/// # Examples
Expand All @@ -219,19 +245,19 @@ where
///
/// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
///
/// assert_eq!(buff.remaining(), &[1, 2, 3, 4, 5]);
/// assert_eq!(buff.remaining_slice(), &[1, 2, 3, 4, 5]);
///
/// buff.set_position(2);
/// assert_eq!(buff.remaining(), &[3, 4, 5]);
/// assert_eq!(buff.remaining_slice(), &[3, 4, 5]);
///
/// buff.set_position(4);
/// assert_eq!(buff.remaining(), &[5]);
/// assert_eq!(buff.remaining_slice(), &[5]);
///
/// buff.set_position(6);
/// assert_eq!(buff.remaining(), &[]);
/// assert_eq!(buff.remaining_slice(), &[]);
/// ```
#[unstable(feature = "cursor_remaining", issue = "86369")]
pub fn remaining(&self) -> &[u8] {
pub fn remaining_slice(&self) -> &[u8] {
let len = self.pos.min(self.inner.as_ref().len() as u64);
&self.inner.as_ref()[(len as usize)..]
}
Expand Down Expand Up @@ -324,7 +350,7 @@ where
T: AsRef<[u8]>,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = Read::read(&mut self.remaining(), buf)?;
let n = Read::read(&mut self.remaining_slice(), buf)?;
self.pos += n as u64;
Ok(n)
}
Expand All @@ -347,7 +373,7 @@ where

fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
let n = buf.len();
Read::read_exact(&mut self.remaining(), buf)?;
Read::read_exact(&mut self.remaining_slice(), buf)?;
self.pos += n as u64;
Ok(())
}
Expand All @@ -364,7 +390,7 @@ where
T: AsRef<[u8]>,
{
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Ok(self.remaining())
Ok(self.remaining_slice())
}
fn consume(&mut self, amt: usize) {
self.pos += amt as u64;
Expand Down

0 comments on commit 664bde0

Please sign in to comment.