core/io/cursor.rs
1use crate::cmp;
2use crate::io::{self, ErrorKind, IoSlice, SeekFrom, Write};
3
4/// A `Cursor` wraps an in-memory buffer and provides it with a
5/// [`Seek`] implementation.
6///
7/// `Cursor`s are used with in-memory buffers, anything implementing
8/// <code>[AsRef]<\[u8]></code>, to allow them to implement [`Read`] and/or [`Write`],
9/// allowing these buffers to be used anywhere you might use a reader or writer
10/// that does actual I/O.
11///
12/// The standard library implements some I/O traits on various types which
13/// are commonly used as a buffer, like <code>Cursor<[Vec]\<u8>></code> and
14/// <code>Cursor<[&\[u8\]][bytes]></code>.
15///
16/// # Examples
17///
18/// We may want to write bytes to a [`File`] in our production
19/// code, but use an in-memory buffer in our tests. We can do this with
20/// `Cursor`:
21///
22// FIXME(#74481): Hard-links required to link from `core` to `std`
23/// [bytes]: crate::slice "slice"
24/// [`File`]: ../../std/fs/struct.File.html
25/// [`Read`]: ../../std/io/trait.Read.html
26/// [`Write`]: crate::io::Write
27/// [`Seek`]: crate::io::Seek
28/// [Vec]: ../../alloc/vec/struct.Vec.html
29///
30/// ```no_run
31/// use std::io::prelude::*;
32/// use std::io::{self, SeekFrom};
33/// use std::fs::File;
34///
35/// // a library function we've written
36/// fn write_ten_bytes_at_end<W: Write + Seek>(mut writer: W) -> io::Result<()> {
37/// writer.seek(SeekFrom::End(-10))?;
38///
39/// for i in 0..10 {
40/// writer.write(&[i])?;
41/// }
42///
43/// // all went well
44/// Ok(())
45/// }
46///
47/// # fn foo() -> io::Result<()> {
48/// // Here's some code that uses this library function.
49/// //
50/// // We might want to use a BufReader here for efficiency, but let's
51/// // keep this example focused.
52/// let mut file = File::create("foo.txt")?;
53/// // First, we need to allocate 10 bytes to be able to write into.
54/// file.set_len(10)?;
55///
56/// write_ten_bytes_at_end(&mut file)?;
57/// # Ok(())
58/// # }
59///
60/// // now let's write a test
61/// #[test]
62/// fn test_writes_bytes() {
63/// // setting up a real File is much slower than an in-memory buffer,
64/// // let's use a cursor instead
65/// use std::io::Cursor;
66/// let mut buff = Cursor::new(vec![0; 15]);
67///
68/// write_ten_bytes_at_end(&mut buff).unwrap();
69///
70/// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
71/// }
72/// ```
73#[stable(feature = "rust1", since = "1.0.0")]
74#[derive(Debug, Default, Eq, PartialEq)]
75pub struct Cursor<T> {
76 inner: T,
77 pos: u64,
78}
79
80impl<T> Cursor<T> {
81 /// Creates a new cursor wrapping the provided underlying in-memory buffer.
82 ///
83 /// Cursor initial position is `0` even if underlying buffer (e.g., [`Vec`])
84 /// is not empty. So writing to cursor starts with overwriting [`Vec`]
85 /// content, not with appending to it.
86 ///
87 // FIXME(#74481): Hard-links required to link from `core` to `alloc`
88 /// [`Vec`]: ../../alloc/vec/struct.Vec.html
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// use std::io::Cursor;
94 ///
95 /// let buff = Cursor::new(Vec::new());
96 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
97 /// # force_inference(&buff);
98 /// ```
99 #[stable(feature = "rust1", since = "1.0.0")]
100 #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
101 pub const fn new(inner: T) -> Cursor<T> {
102 Cursor { pos: 0, inner }
103 }
104
105 /// Consumes this cursor, returning the underlying value.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// use std::io::Cursor;
111 ///
112 /// let buff = Cursor::new(Vec::new());
113 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
114 /// # force_inference(&buff);
115 ///
116 /// let vec = buff.into_inner();
117 /// ```
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub fn into_inner(self) -> T {
120 self.inner
121 }
122
123 /// Gets a reference to the underlying value in this cursor.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// use std::io::Cursor;
129 ///
130 /// let buff = Cursor::new(Vec::new());
131 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
132 /// # force_inference(&buff);
133 ///
134 /// let reference = buff.get_ref();
135 /// ```
136 #[stable(feature = "rust1", since = "1.0.0")]
137 #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
138 pub const fn get_ref(&self) -> &T {
139 &self.inner
140 }
141
142 /// Gets a mutable reference to the underlying value in this cursor.
143 ///
144 /// Care should be taken to avoid modifying the internal I/O state of the
145 /// underlying value as it may corrupt this cursor's position.
146 ///
147 /// # Examples
148 ///
149 /// ```
150 /// use std::io::Cursor;
151 ///
152 /// let mut buff = Cursor::new(Vec::new());
153 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
154 /// # force_inference(&buff);
155 ///
156 /// let reference = buff.get_mut();
157 /// ```
158 #[stable(feature = "rust1", since = "1.0.0")]
159 #[rustc_const_stable(feature = "const_mut_cursor", since = "1.86.0")]
160 pub const fn get_mut(&mut self) -> &mut T {
161 &mut self.inner
162 }
163
164 /// Returns the current position of this cursor.
165 ///
166 /// # Examples
167 ///
168 /// ```
169 /// use std::io::Cursor;
170 /// use std::io::prelude::*;
171 /// use std::io::SeekFrom;
172 ///
173 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
174 ///
175 /// assert_eq!(buff.position(), 0);
176 ///
177 /// buff.seek(SeekFrom::Current(2)).unwrap();
178 /// assert_eq!(buff.position(), 2);
179 ///
180 /// buff.seek(SeekFrom::Current(-1)).unwrap();
181 /// assert_eq!(buff.position(), 1);
182 /// ```
183 #[stable(feature = "rust1", since = "1.0.0")]
184 #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
185 pub const fn position(&self) -> u64 {
186 self.pos
187 }
188
189 /// Sets the position of this cursor.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use std::io::Cursor;
195 ///
196 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
197 ///
198 /// assert_eq!(buff.position(), 0);
199 ///
200 /// buff.set_position(2);
201 /// assert_eq!(buff.position(), 2);
202 ///
203 /// buff.set_position(4);
204 /// assert_eq!(buff.position(), 4);
205 /// ```
206 #[stable(feature = "rust1", since = "1.0.0")]
207 #[rustc_const_stable(feature = "const_mut_cursor", since = "1.86.0")]
208 pub const fn set_position(&mut self, pos: u64) {
209 self.pos = pos;
210 }
211
212 #[doc(hidden)]
213 #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
214 #[inline]
215 pub const fn into_parts_mut(&mut self) -> (&mut u64, &mut T) {
216 (&mut self.pos, &mut self.inner)
217 }
218}
219
220impl<T> Cursor<T>
221where
222 T: AsRef<[u8]>,
223{
224 /// Splits the underlying slice at the cursor position and returns them.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// #![feature(cursor_split)]
230 /// use std::io::Cursor;
231 ///
232 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
233 ///
234 /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice()));
235 ///
236 /// buff.set_position(2);
237 /// assert_eq!(buff.split(), ([1, 2].as_slice(), [3, 4, 5].as_slice()));
238 ///
239 /// buff.set_position(6);
240 /// assert_eq!(buff.split(), ([1, 2, 3, 4, 5].as_slice(), [].as_slice()));
241 /// ```
242 #[unstable(feature = "cursor_split", issue = "86369")]
243 pub fn split(&self) -> (&[u8], &[u8]) {
244 let slice = self.inner.as_ref();
245 let pos = self.pos.min(slice.len() as u64);
246 slice.split_at(pos as usize)
247 }
248}
249
250impl<T> Cursor<T>
251where
252 T: AsMut<[u8]>,
253{
254 /// Splits the underlying slice at the cursor position and returns them
255 /// mutably.
256 ///
257 /// # Examples
258 ///
259 /// ```
260 /// #![feature(cursor_split)]
261 /// use std::io::Cursor;
262 ///
263 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
264 ///
265 /// assert_eq!(buff.split_mut(), ([].as_mut_slice(), [1, 2, 3, 4, 5].as_mut_slice()));
266 ///
267 /// buff.set_position(2);
268 /// assert_eq!(buff.split_mut(), ([1, 2].as_mut_slice(), [3, 4, 5].as_mut_slice()));
269 ///
270 /// buff.set_position(6);
271 /// assert_eq!(buff.split_mut(), ([1, 2, 3, 4, 5].as_mut_slice(), [].as_mut_slice()));
272 /// ```
273 #[unstable(feature = "cursor_split", issue = "86369")]
274 pub fn split_mut(&mut self) -> (&mut [u8], &mut [u8]) {
275 let slice = self.inner.as_mut();
276 let pos = self.pos.min(slice.len() as u64);
277 slice.split_at_mut(pos as usize)
278 }
279}
280
281#[stable(feature = "rust1", since = "1.0.0")]
282impl<T> Clone for Cursor<T>
283where
284 T: Clone,
285{
286 #[inline]
287 fn clone(&self) -> Self {
288 Cursor { inner: self.inner.clone(), pos: self.pos }
289 }
290
291 #[inline]
292 fn clone_from(&mut self, other: &Self) {
293 self.inner.clone_from(&other.inner);
294 self.pos = other.pos;
295 }
296}
297
298/// Non-resizing [`Write::write`] implementation for slices.
299/// Exported for `Cursor<Box<[u8], A>>`'s implementation of [`Write`].
300#[inline]
301#[doc(hidden)]
302#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
303pub fn slice_write(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> io::Result<usize> {
304 let pos = cmp::min(*pos_mut, slice.len() as u64);
305 let dst = &mut slice[(pos as usize)..];
306 let amt = cmp::min(buf.len(), dst.len());
307 dst[..amt].copy_from_slice(&buf[..amt]);
308 *pos_mut += amt as u64;
309 Ok(amt)
310}
311
312/// Non-resizing [`Write::write_vectored`] implementation for slices.
313/// Exported for `Cursor<Box<[u8], A>>`'s implementation of [`Write`].
314#[inline]
315#[doc(hidden)]
316#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
317pub fn slice_write_vectored(
318 pos_mut: &mut u64,
319 slice: &mut [u8],
320 bufs: &[IoSlice<'_>],
321) -> io::Result<usize> {
322 let mut nwritten = 0;
323 for buf in bufs {
324 let n = slice_write(pos_mut, slice, buf)?;
325 nwritten += n;
326 if n < buf.len() {
327 break;
328 }
329 }
330 Ok(nwritten)
331}
332
333/// Non-resizing [`Write::write_all`] implementation for slices.
334/// Exported for `Cursor<Box<[u8], A>>`'s implementation of [`Write`].
335#[inline]
336#[doc(hidden)]
337#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
338pub fn slice_write_all(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> io::Result<()> {
339 let n = slice_write(pos_mut, slice, buf)?;
340 if n < buf.len() { Err(io::Error::WRITE_ALL_EOF) } else { Ok(()) }
341}
342
343/// Non-resizing [`Write::write_all_vectored`] implementation for slices.
344/// Exported for `Cursor<Box<[u8], A>>`'s implementation of [`Write`].
345#[inline]
346#[doc(hidden)]
347#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
348pub fn slice_write_all_vectored(
349 pos_mut: &mut u64,
350 slice: &mut [u8],
351 bufs: &[IoSlice<'_>],
352) -> io::Result<()> {
353 for buf in bufs {
354 let n = slice_write(pos_mut, slice, buf)?;
355 if n < buf.len() {
356 return Err(io::Error::WRITE_ALL_EOF);
357 }
358 }
359 Ok(())
360}
361
362#[stable(feature = "rust1", since = "1.0.0")]
363impl Write for Cursor<&mut [u8]> {
364 #[inline]
365 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
366 let (pos, inner) = self.into_parts_mut();
367 slice_write(pos, inner, buf)
368 }
369
370 #[inline]
371 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
372 let (pos, inner) = self.into_parts_mut();
373 slice_write_vectored(pos, inner, bufs)
374 }
375
376 #[inline]
377 fn is_write_vectored(&self) -> bool {
378 true
379 }
380
381 #[inline]
382 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
383 let (pos, inner) = self.into_parts_mut();
384 slice_write_all(pos, inner, buf)
385 }
386
387 #[inline]
388 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
389 let (pos, inner) = self.into_parts_mut();
390 slice_write_all_vectored(pos, inner, bufs)
391 }
392
393 #[inline]
394 fn flush(&mut self) -> io::Result<()> {
395 Ok(())
396 }
397}
398
399#[stable(feature = "cursor_array", since = "1.61.0")]
400impl<const N: usize> Write for Cursor<[u8; N]> {
401 #[inline]
402 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
403 let (pos, inner) = self.into_parts_mut();
404 slice_write(pos, inner, buf)
405 }
406
407 #[inline]
408 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
409 let (pos, inner) = self.into_parts_mut();
410 slice_write_vectored(pos, inner, bufs)
411 }
412
413 #[inline]
414 fn is_write_vectored(&self) -> bool {
415 true
416 }
417
418 #[inline]
419 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
420 let (pos, inner) = self.into_parts_mut();
421 slice_write_all(pos, inner, buf)
422 }
423
424 #[inline]
425 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
426 let (pos, inner) = self.into_parts_mut();
427 slice_write_all_vectored(pos, inner, bufs)
428 }
429
430 #[inline]
431 fn flush(&mut self) -> io::Result<()> {
432 Ok(())
433 }
434}
435
436#[stable(feature = "rust1", since = "1.0.0")]
437impl<T> io::Seek for Cursor<T>
438where
439 T: AsRef<[u8]>,
440{
441 fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
442 let (base_pos, offset) = match style {
443 SeekFrom::Start(n) => {
444 self.set_position(n);
445 return Ok(n);
446 }
447 SeekFrom::End(n) => (self.get_ref().as_ref().len() as u64, n),
448 SeekFrom::Current(n) => (self.position(), n),
449 };
450 match base_pos.checked_add_signed(offset) {
451 Some(n) => {
452 self.set_position(n);
453 Ok(n)
454 }
455 None => Err(io::const_error!(
456 ErrorKind::InvalidInput,
457 "invalid seek to a negative or overflowing position",
458 )),
459 }
460 }
461
462 fn stream_len(&mut self) -> io::Result<u64> {
463 Ok(self.get_ref().as_ref().len() as u64)
464 }
465
466 fn stream_position(&mut self) -> io::Result<u64> {
467 Ok(self.position())
468 }
469}
470
471/// Trait used to allow indirect implementation of `Write` for `Cursor<Self>`.
472/// Since [`Cursor`] is not a foundational type, it is not possible to implement
473/// `Write` for `Cursor<T>` if `Write` is defined in `libcore` and `T` is in a
474/// downstream crate (e.g., `liballoc` or `libstd`).
475///
476/// Methods are identical in purpose and meaning to their `Write` namesakes.
477#[doc(hidden)]
478#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
479pub trait WriteThroughCursor: Sized {
480 fn write(this: &mut Cursor<Self>, buf: &[u8]) -> io::Result<usize>;
481 fn write_vectored(this: &mut Cursor<Self>, bufs: &[IoSlice<'_>]) -> io::Result<usize>;
482 fn is_write_vectored(this: &Cursor<Self>) -> bool;
483 fn write_all(this: &mut Cursor<Self>, buf: &[u8]) -> io::Result<()>;
484 fn write_all_vectored(this: &mut Cursor<Self>, bufs: &mut [IoSlice<'_>]) -> io::Result<()>;
485 fn flush(this: &mut Cursor<Self>) -> io::Result<()>;
486}
487
488#[doc(hidden)]
489impl<W: WriteThroughCursor> Write for Cursor<W> {
490 #[inline]
491 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
492 WriteThroughCursor::write(self, buf)
493 }
494
495 #[inline]
496 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
497 WriteThroughCursor::write_vectored(self, bufs)
498 }
499
500 #[inline]
501 fn is_write_vectored(&self) -> bool {
502 WriteThroughCursor::is_write_vectored(self)
503 }
504
505 #[inline]
506 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
507 WriteThroughCursor::write_all(self, buf)
508 }
509
510 #[inline]
511 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
512 WriteThroughCursor::write_all_vectored(self, bufs)
513 }
514
515 #[inline]
516 fn flush(&mut self) -> io::Result<()> {
517 WriteThroughCursor::flush(self)
518 }
519}