diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs index db720531e3a..04f13cdeb88 100644 --- a/library/std/src/io/cursor.rs +++ b/library/std/src/io/cursor.rs @@ -209,6 +209,32 @@ impl Cursor 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 @@ -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)..] } @@ -324,7 +350,7 @@ where T: AsRef<[u8]>, { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let n = Read::read(&mut self.remaining(), buf)?; + let n = Read::read(&mut self.remaining_slice(), buf)?; self.pos += n as u64; Ok(n) } @@ -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(()) } @@ -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;