Skip to main content

core/io/
cursor.rs

1use crate::io::{self, ErrorKind, SeekFrom};
2
3/// A `Cursor` wraps an in-memory buffer and provides it with a
4/// [`Seek`] implementation.
5///
6/// `Cursor`s are used with in-memory buffers, anything implementing
7/// <code>[AsRef]<\[u8]></code>, to allow them to implement [`Read`] and/or [`Write`],
8/// allowing these buffers to be used anywhere you might use a reader or writer
9/// that does actual I/O.
10///
11/// The standard library implements some I/O traits on various types which
12/// are commonly used as a buffer, like <code>Cursor<[Vec]\<u8>></code> and
13/// <code>Cursor<[&\[u8\]][bytes]></code>.
14///
15/// # Examples
16///
17/// We may want to write bytes to a [`File`] in our production
18/// code, but use an in-memory buffer in our tests. We can do this with
19/// `Cursor`:
20///
21// FIXME(#74481): Hard-links required to link from `core` to `std`
22/// [bytes]: crate::slice "slice"
23/// [`File`]: ../../std/fs/struct.File.html
24/// [`Read`]: ../../std/io/trait.Read.html
25/// [`Write`]: ../../std/io/trait.Write.html
26/// [`Seek`]: crate::io::Seek
27/// [Vec]: ../../alloc/vec/struct.Vec.html
28///
29/// ```no_run
30/// use std::io::prelude::*;
31/// use std::io::{self, SeekFrom};
32/// use std::fs::File;
33///
34/// // a library function we've written
35/// fn write_ten_bytes_at_end<W: Write + Seek>(mut writer: W) -> io::Result<()> {
36///     writer.seek(SeekFrom::End(-10))?;
37///
38///     for i in 0..10 {
39///         writer.write(&[i])?;
40///     }
41///
42///     // all went well
43///     Ok(())
44/// }
45///
46/// # fn foo() -> io::Result<()> {
47/// // Here's some code that uses this library function.
48/// //
49/// // We might want to use a BufReader here for efficiency, but let's
50/// // keep this example focused.
51/// let mut file = File::create("foo.txt")?;
52/// // First, we need to allocate 10 bytes to be able to write into.
53/// file.set_len(10)?;
54///
55/// write_ten_bytes_at_end(&mut file)?;
56/// # Ok(())
57/// # }
58///
59/// // now let's write a test
60/// #[test]
61/// fn test_writes_bytes() {
62///     // setting up a real File is much slower than an in-memory buffer,
63///     // let's use a cursor instead
64///     use std::io::Cursor;
65///     let mut buff = Cursor::new(vec![0; 15]);
66///
67///     write_ten_bytes_at_end(&mut buff).unwrap();
68///
69///     assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
70/// }
71/// ```
72#[stable(feature = "rust1", since = "1.0.0")]
73#[derive(Debug, Default, Eq, PartialEq)]
74pub struct Cursor<T> {
75    inner: T,
76    pos: u64,
77}
78
79impl<T> Cursor<T> {
80    /// Creates a new cursor wrapping the provided underlying in-memory buffer.
81    ///
82    /// Cursor initial position is `0` even if underlying buffer (e.g., [`Vec`])
83    /// is not empty. So writing to cursor starts with overwriting [`Vec`]
84    /// content, not with appending to it.
85    ///
86    // FIXME(#74481): Hard-links required to link from `core` to `alloc`
87    /// [`Vec`]: ../../alloc/vec/struct.Vec.html
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use std::io::Cursor;
93    ///
94    /// let buff = Cursor::new(Vec::new());
95    /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
96    /// # force_inference(&buff);
97    /// ```
98    #[stable(feature = "rust1", since = "1.0.0")]
99    #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
100    pub const fn new(inner: T) -> Cursor<T> {
101        Cursor { pos: 0, inner }
102    }
103
104    /// Consumes this cursor, returning the underlying value.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use std::io::Cursor;
110    ///
111    /// let buff = Cursor::new(Vec::new());
112    /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
113    /// # force_inference(&buff);
114    ///
115    /// let vec = buff.into_inner();
116    /// ```
117    #[stable(feature = "rust1", since = "1.0.0")]
118    pub fn into_inner(self) -> T {
119        self.inner
120    }
121
122    /// Gets a reference to the underlying value in this cursor.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use std::io::Cursor;
128    ///
129    /// let buff = Cursor::new(Vec::new());
130    /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
131    /// # force_inference(&buff);
132    ///
133    /// let reference = buff.get_ref();
134    /// ```
135    #[stable(feature = "rust1", since = "1.0.0")]
136    #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
137    pub const fn get_ref(&self) -> &T {
138        &self.inner
139    }
140
141    /// Gets a mutable reference to the underlying value in this cursor.
142    ///
143    /// Care should be taken to avoid modifying the internal I/O state of the
144    /// underlying value as it may corrupt this cursor's position.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use std::io::Cursor;
150    ///
151    /// let mut buff = Cursor::new(Vec::new());
152    /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
153    /// # force_inference(&buff);
154    ///
155    /// let reference = buff.get_mut();
156    /// ```
157    #[stable(feature = "rust1", since = "1.0.0")]
158    #[rustc_const_stable(feature = "const_mut_cursor", since = "1.86.0")]
159    pub const fn get_mut(&mut self) -> &mut T {
160        &mut self.inner
161    }
162
163    /// Returns the current position of this cursor.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// use std::io::Cursor;
169    /// use std::io::prelude::*;
170    /// use std::io::SeekFrom;
171    ///
172    /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
173    ///
174    /// assert_eq!(buff.position(), 0);
175    ///
176    /// buff.seek(SeekFrom::Current(2)).unwrap();
177    /// assert_eq!(buff.position(), 2);
178    ///
179    /// buff.seek(SeekFrom::Current(-1)).unwrap();
180    /// assert_eq!(buff.position(), 1);
181    /// ```
182    #[stable(feature = "rust1", since = "1.0.0")]
183    #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
184    pub const fn position(&self) -> u64 {
185        self.pos
186    }
187
188    /// Sets the position of this cursor.
189    ///
190    /// # Examples
191    ///
192    /// ```
193    /// use std::io::Cursor;
194    ///
195    /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
196    ///
197    /// assert_eq!(buff.position(), 0);
198    ///
199    /// buff.set_position(2);
200    /// assert_eq!(buff.position(), 2);
201    ///
202    /// buff.set_position(4);
203    /// assert_eq!(buff.position(), 4);
204    /// ```
205    #[stable(feature = "rust1", since = "1.0.0")]
206    #[rustc_const_stable(feature = "const_mut_cursor", since = "1.86.0")]
207    pub const fn set_position(&mut self, pos: u64) {
208        self.pos = pos;
209    }
210
211    #[doc(hidden)]
212    #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
213    #[inline]
214    pub const fn into_parts_mut(&mut self) -> (&mut u64, &mut T) {
215        (&mut self.pos, &mut self.inner)
216    }
217}
218
219impl<T> Cursor<T>
220where
221    T: AsRef<[u8]>,
222{
223    /// Splits the underlying slice at the cursor position and returns them.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// #![feature(cursor_split)]
229    /// use std::io::Cursor;
230    ///
231    /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
232    ///
233    /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice()));
234    ///
235    /// buff.set_position(2);
236    /// assert_eq!(buff.split(), ([1, 2].as_slice(), [3, 4, 5].as_slice()));
237    ///
238    /// buff.set_position(6);
239    /// assert_eq!(buff.split(), ([1, 2, 3, 4, 5].as_slice(), [].as_slice()));
240    /// ```
241    #[unstable(feature = "cursor_split", issue = "86369")]
242    pub fn split(&self) -> (&[u8], &[u8]) {
243        let slice = self.inner.as_ref();
244        let pos = self.pos.min(slice.len() as u64);
245        slice.split_at(pos as usize)
246    }
247}
248
249impl<T> Cursor<T>
250where
251    T: AsMut<[u8]>,
252{
253    /// Splits the underlying slice at the cursor position and returns them
254    /// mutably.
255    ///
256    /// # Examples
257    ///
258    /// ```
259    /// #![feature(cursor_split)]
260    /// use std::io::Cursor;
261    ///
262    /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
263    ///
264    /// assert_eq!(buff.split_mut(), ([].as_mut_slice(), [1, 2, 3, 4, 5].as_mut_slice()));
265    ///
266    /// buff.set_position(2);
267    /// assert_eq!(buff.split_mut(), ([1, 2].as_mut_slice(), [3, 4, 5].as_mut_slice()));
268    ///
269    /// buff.set_position(6);
270    /// assert_eq!(buff.split_mut(), ([1, 2, 3, 4, 5].as_mut_slice(), [].as_mut_slice()));
271    /// ```
272    #[unstable(feature = "cursor_split", issue = "86369")]
273    pub fn split_mut(&mut self) -> (&mut [u8], &mut [u8]) {
274        let slice = self.inner.as_mut();
275        let pos = self.pos.min(slice.len() as u64);
276        slice.split_at_mut(pos as usize)
277    }
278}
279
280#[stable(feature = "rust1", since = "1.0.0")]
281impl<T> Clone for Cursor<T>
282where
283    T: Clone,
284{
285    #[inline]
286    fn clone(&self) -> Self {
287        Cursor { inner: self.inner.clone(), pos: self.pos }
288    }
289
290    #[inline]
291    fn clone_from(&mut self, other: &Self) {
292        self.inner.clone_from(&other.inner);
293        self.pos = other.pos;
294    }
295}
296
297#[stable(feature = "rust1", since = "1.0.0")]
298impl<T> io::Seek for Cursor<T>
299where
300    T: AsRef<[u8]>,
301{
302    fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
303        let (base_pos, offset) = match style {
304            SeekFrom::Start(n) => {
305                self.set_position(n);
306                return Ok(n);
307            }
308            SeekFrom::End(n) => (self.get_ref().as_ref().len() as u64, n),
309            SeekFrom::Current(n) => (self.position(), n),
310        };
311        match base_pos.checked_add_signed(offset) {
312            Some(n) => {
313                self.set_position(n);
314                Ok(n)
315            }
316            None => Err(io::const_error!(
317                ErrorKind::InvalidInput,
318                "invalid seek to a negative or overflowing position",
319            )),
320        }
321    }
322
323    fn stream_len(&mut self) -> io::Result<u64> {
324        Ok(self.get_ref().as_ref().len() as u64)
325    }
326
327    fn stream_position(&mut self) -> io::Result<u64> {
328        Ok(self.position())
329    }
330}