Add `set_position` method to `Cursor`

Without the ability to seek, the `Cursor` type is only useful for
wrapping owned buffers. In `std` the equivalent type also allows
seeking. We currently do not have the `Seek` trait so this simply adds a
method to set the position. Further, this adds a method to access inner
type so seeking from the end can be implemented (to compute the position
relative to the end).

Closes #3174
This commit is contained in:
Martin Habovstiak 2024-08-15 21:43:01 +02:00
parent fc7e213f21
commit 94768d3f70
1 changed files with 17 additions and 0 deletions

View File

@ -202,11 +202,28 @@ impl<T: AsRef<[u8]>> Cursor<T> {
#[inline] #[inline]
pub fn position(&self) -> u64 { self.pos } pub fn position(&self) -> u64 { self.pos }
/// Sets the internal position.
///
/// This method allows seeking within the wrapped memory by setting the position.
///
/// Note that setting a position that is larger than the buffer length will cause reads to
/// return no bytes (EOF).
#[inline]
pub fn set_position(&mut self, position: u64) {
self.pos = position;
}
/// Returns the inner buffer. /// Returns the inner buffer.
/// ///
/// This is the whole wrapped buffer, including the bytes already read. /// This is the whole wrapped buffer, including the bytes already read.
#[inline] #[inline]
pub fn into_inner(self) -> T { self.inner } pub fn into_inner(self) -> T { self.inner }
/// Returns a reference to the inner buffer.
///
/// This is the whole wrapped buffer, including the bytes already read.
#[inline]
pub fn inner(&self) -> &T { &self.inner }
} }
impl<T: AsRef<[u8]>> Read for Cursor<T> { impl<T: AsRef<[u8]>> Read for Cursor<T> {