1#[cfg(test)]
2mod tests;
3
4use crate::io::prelude::*;
5
6use crate::alloc::Allocator;
7use crate::cmp;
8use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, SeekFrom};
9
10/// A `Cursor` wraps an in-memory buffer and provides it with a
11/// [`Seek`] implementation.
12///
13/// `Cursor`s are used with in-memory buffers, anything implementing
14/// <code>[AsRef]<\[u8]></code>, to allow them to implement [`Read`] and/or [`Write`],
15/// allowing these buffers to be used anywhere you might use a reader or writer
16/// that does actual I/O.
17///
18/// The standard library implements some I/O traits on various types which
19/// are commonly used as a buffer, like <code>Cursor<[Vec]\<u8>></code> and
20/// <code>Cursor<[&\[u8\]][bytes]></code>.
21///
22/// # Examples
23///
24/// We may want to write bytes to a [`File`] in our production
25/// code, but use an in-memory buffer in our tests. We can do this with
26/// `Cursor`:
27///
28/// [bytes]: crate::slice "slice"
29/// [`File`]: crate::fs::File
30///
31/// ```no_run
32/// use std::io::prelude::*;
33/// use std::io::{self, SeekFrom};
34/// use std::fs::File;
35///
36/// // a library function we've written
37/// fn write_ten_bytes_at_end<W: Write + Seek>(mut writer: W) -> io::Result<()> {
38/// writer.seek(SeekFrom::End(-10))?;
39///
40/// for i in 0..10 {
41/// writer.write(&[i])?;
42/// }
43///
44/// // all went well
45/// Ok(())
46/// }
47///
48/// # fn foo() -> io::Result<()> {
49/// // Here's some code that uses this library function.
50/// //
51/// // We might want to use a BufReader here for efficiency, but let's
52/// // keep this example focused.
53/// let mut file = File::create("foo.txt")?;
54/// // First, we need to allocate 10 bytes to be able to write into.
55/// file.set_len(10)?;
56///
57/// write_ten_bytes_at_end(&mut file)?;
58/// # Ok(())
59/// # }
60///
61/// // now let's write a test
62/// #[test]
63/// fn test_writes_bytes() {
64/// // setting up a real File is much slower than an in-memory buffer,
65/// // let's use a cursor instead
66/// use std::io::Cursor;
67/// let mut buff = Cursor::new(vec![0; 15]);
68///
69/// write_ten_bytes_at_end(&mut buff).unwrap();
70///
71/// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
72/// }
73/// ```
74#[stable(feature = "rust1", since = "1.0.0")]
75#[derive(Debug, Default, Eq, PartialEq)]
76pub struct Cursor<T> {
77 inner: T,
78 pos: u64,
79}
80
81impl<T> Cursor<T> {
82 /// Creates a new cursor wrapping the provided underlying in-memory buffer.
83 ///
84 /// Cursor initial position is `0` even if underlying buffer (e.g., [`Vec`])
85 /// is not empty. So writing to cursor starts with overwriting [`Vec`]
86 /// content, not with appending to it.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// use std::io::Cursor;
92 ///
93 /// let buff = Cursor::new(Vec::new());
94 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
95 /// # force_inference(&buff);
96 /// ```
97 #[stable(feature = "rust1", since = "1.0.0")]
98 #[rustc_const_stable(feature = "const_io_structs", since = "CURRENT_RUSTC_VERSION")]
99 pub const fn new(inner: T) -> Cursor<T> {
100 Cursor { pos: 0, inner }
101 }
102
103 /// Consumes this cursor, returning the underlying value.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use std::io::Cursor;
109 ///
110 /// let buff = Cursor::new(Vec::new());
111 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
112 /// # force_inference(&buff);
113 ///
114 /// let vec = buff.into_inner();
115 /// ```
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub fn into_inner(self) -> T {
118 self.inner
119 }
120
121 /// Gets a reference to the underlying value in this cursor.
122 ///
123 /// # Examples
124 ///
125 /// ```
126 /// use std::io::Cursor;
127 ///
128 /// let buff = Cursor::new(Vec::new());
129 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
130 /// # force_inference(&buff);
131 ///
132 /// let reference = buff.get_ref();
133 /// ```
134 #[stable(feature = "rust1", since = "1.0.0")]
135 #[rustc_const_stable(feature = "const_io_structs", since = "CURRENT_RUSTC_VERSION")]
136 pub const fn get_ref(&self) -> &T {
137 &self.inner
138 }
139
140 /// Gets a mutable reference to the underlying value in this cursor.
141 ///
142 /// Care should be taken to avoid modifying the internal I/O state of the
143 /// underlying value as it may corrupt this cursor's position.
144 ///
145 /// # Examples
146 ///
147 /// ```
148 /// use std::io::Cursor;
149 ///
150 /// let mut buff = Cursor::new(Vec::new());
151 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
152 /// # force_inference(&buff);
153 ///
154 /// let reference = buff.get_mut();
155 /// ```
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub fn get_mut(&mut self) -> &mut T {
158 &mut self.inner
159 }
160
161 /// Returns the current position of this cursor.
162 ///
163 /// # Examples
164 ///
165 /// ```
166 /// use std::io::Cursor;
167 /// use std::io::prelude::*;
168 /// use std::io::SeekFrom;
169 ///
170 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
171 ///
172 /// assert_eq!(buff.position(), 0);
173 ///
174 /// buff.seek(SeekFrom::Current(2)).unwrap();
175 /// assert_eq!(buff.position(), 2);
176 ///
177 /// buff.seek(SeekFrom::Current(-1)).unwrap();
178 /// assert_eq!(buff.position(), 1);
179 /// ```
180 #[stable(feature = "rust1", since = "1.0.0")]
181 #[rustc_const_stable(feature = "const_io_structs", since = "CURRENT_RUSTC_VERSION")]
182 pub const fn position(&self) -> u64 {
183 self.pos
184 }
185
186 /// Sets the position of this cursor.
187 ///
188 /// # Examples
189 ///
190 /// ```
191 /// use std::io::Cursor;
192 ///
193 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
194 ///
195 /// assert_eq!(buff.position(), 0);
196 ///
197 /// buff.set_position(2);
198 /// assert_eq!(buff.position(), 2);
199 ///
200 /// buff.set_position(4);
201 /// assert_eq!(buff.position(), 4);
202 /// ```
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub fn set_position(&mut self, pos: u64) {
205 self.pos = pos;
206 }
207}
208
209impl<T> Cursor<T>
210where
211 T: AsRef<[u8]>,
212{
213 /// Returns the remaining slice.
214 ///
215 /// # Examples
216 ///
217 /// ```
218 /// #![feature(cursor_remaining)]
219 /// use std::io::Cursor;
220 ///
221 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
222 ///
223 /// assert_eq!(buff.remaining_slice(), &[1, 2, 3, 4, 5]);
224 ///
225 /// buff.set_position(2);
226 /// assert_eq!(buff.remaining_slice(), &[3, 4, 5]);
227 ///
228 /// buff.set_position(4);
229 /// assert_eq!(buff.remaining_slice(), &[5]);
230 ///
231 /// buff.set_position(6);
232 /// assert_eq!(buff.remaining_slice(), &[]);
233 /// ```
234 #[unstable(feature = "cursor_remaining", issue = "86369")]
235 pub fn remaining_slice(&self) -> &[u8] {
236 let len = self.pos.min(self.inner.as_ref().len() as u64);
237 &self.inner.as_ref()[(len as usize)..]
238 }
239
240 /// Returns `true` if the remaining slice is empty.
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// #![feature(cursor_remaining)]
246 /// use std::io::Cursor;
247 ///
248 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
249 ///
250 /// buff.set_position(2);
251 /// assert!(!buff.is_empty());
252 ///
253 /// buff.set_position(5);
254 /// assert!(buff.is_empty());
255 ///
256 /// buff.set_position(10);
257 /// assert!(buff.is_empty());
258 /// ```
259 #[unstable(feature = "cursor_remaining", issue = "86369")]
260 pub fn is_empty(&self) -> bool {
261 self.pos >= self.inner.as_ref().len() as u64
262 }
263}
264
265#[stable(feature = "rust1", since = "1.0.0")]
266impl<T> Clone for Cursor<T>
267where
268 T: Clone,
269{
270 #[inline]
271 fn clone(&self) -> Self {
272 Cursor { inner: self.inner.clone(), pos: self.pos }
273 }
274
275 #[inline]
276 fn clone_from(&mut self, other: &Self) {
277 self.inner.clone_from(&other.inner);
278 self.pos = other.pos;
279 }
280}
281
282#[stable(feature = "rust1", since = "1.0.0")]
283impl<T> io::Seek for Cursor<T>
284where
285 T: AsRef<[u8]>,
286{
287 fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
288 let (base_pos, offset) = match style {
289 SeekFrom::Start(n) => {
290 self.pos = n;
291 return Ok(n);
292 }
293 SeekFrom::End(n) => (self.inner.as_ref().len() as u64, n),
294 SeekFrom::Current(n) => (self.pos, n),
295 };
296 match base_pos.checked_add_signed(offset) {
297 Some(n) => {
298 self.pos = n;
299 Ok(self.pos)
300 }
301 None => Err(io::const_io_error!(
302 ErrorKind::InvalidInput,
303 "invalid seek to a negative or overflowing position",
304 )),
305 }
306 }
307
308 fn stream_len(&mut self) -> io::Result<u64> {
309 Ok(self.inner.as_ref().len() as u64)
310 }
311
312 fn stream_position(&mut self) -> io::Result<u64> {
313 Ok(self.pos)
314 }
315}
316
317#[stable(feature = "rust1", since = "1.0.0")]
318impl<T> Read for Cursor<T>
319where
320 T: AsRef<[u8]>,
321{
322 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
323 let n = Read::read(&mut self.remaining_slice(), buf)?;
324 self.pos += n as u64;
325 Ok(n)
326 }
327
328 fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
329 let prev_written = cursor.written();
330
331 Read::read_buf(&mut self.fill_buf()?, cursor.reborrow())?;
332
333 self.pos += (cursor.written() - prev_written) as u64;
334
335 Ok(())
336 }
337
338 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
339 let mut nread = 0;
340 for buf in bufs {
341 let n = self.read(buf)?;
342 nread += n;
343 if n < buf.len() {
344 break;
345 }
346 }
347 Ok(nread)
348 }
349
350 fn is_read_vectored(&self) -> bool {
351 true
352 }
353
354 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
355 let n = buf.len();
356 Read::read_exact(&mut self.remaining_slice(), buf)?;
357 self.pos += n as u64;
358 Ok(())
359 }
360
361 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
362 let n = cursor.capacity();
363 Read::read_buf_exact(&mut self.remaining_slice(), cursor)?;
364 self.pos += n as u64;
365 Ok(())
366 }
367}
368
369#[stable(feature = "rust1", since = "1.0.0")]
370impl<T> BufRead for Cursor<T>
371where
372 T: AsRef<[u8]>,
373{
374 fn fill_buf(&mut self) -> io::Result<&[u8]> {
375 Ok(self.remaining_slice())
376 }
377 fn consume(&mut self, amt: usize) {
378 self.pos += amt as u64;
379 }
380}
381
382// Non-resizing write implementation
383#[inline]
384fn slice_write(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> io::Result<usize> {
385 let pos: u64 = cmp::min(*pos_mut, v2:slice.len() as u64);
386 let amt: usize = (&mut slice[(pos as usize)..]).write(buf)?;
387 *pos_mut += amt as u64;
388 Ok(amt)
389}
390
391#[inline]
392fn slice_write_vectored(
393 pos_mut: &mut u64,
394 slice: &mut [u8],
395 bufs: &[IoSlice<'_>],
396) -> io::Result<usize> {
397 let mut nwritten: usize = 0;
398 for buf: &IoSlice<'_> in bufs {
399 let n: usize = slice_write(pos_mut, slice, buf)?;
400 nwritten += n;
401 if n < buf.len() {
402 break;
403 }
404 }
405 Ok(nwritten)
406}
407
408/// Reserves the required space, and pads the vec with 0s if necessary.
409fn reserve_and_pad<A: Allocator>(
410 pos_mut: &mut u64,
411 vec: &mut Vec<u8, A>,
412 buf_len: usize,
413) -> io::Result<usize> {
414 let pos: usize = (*pos_mut).try_into().map_err(|_| {
415 io::const_io_error!(
416 ErrorKind::InvalidInput,
417 "cursor position exceeds maximum possible vector length",
418 )
419 })?;
420
421 // For safety reasons, we don't want these numbers to overflow
422 // otherwise our allocation won't be enough
423 let desired_cap = pos.saturating_add(buf_len);
424 if desired_cap > vec.capacity() {
425 // We want our vec's total capacity
426 // to have room for (pos+buf_len) bytes. Reserve allocates
427 // based on additional elements from the length, so we need to
428 // reserve the difference
429 vec.reserve(desired_cap - vec.len());
430 }
431 // Pad if pos is above the current len.
432 if pos > vec.len() {
433 let diff = pos - vec.len();
434 // Unfortunately, `resize()` would suffice but the optimiser does not
435 // realise the `reserve` it does can be eliminated. So we do it manually
436 // to eliminate that extra branch
437 let spare = vec.spare_capacity_mut();
438 debug_assert!(spare.len() >= diff);
439 // Safety: we have allocated enough capacity for this.
440 // And we are only writing, not reading
441 unsafe {
442 spare.get_unchecked_mut(..diff).fill(core::mem::MaybeUninit::new(0));
443 vec.set_len(pos);
444 }
445 }
446
447 Ok(pos)
448}
449
450/// Writes the slice to the vec without allocating
451/// # Safety: vec must have buf.len() spare capacity
452unsafe fn vec_write_unchecked<A>(pos: usize, vec: &mut Vec<u8, A>, buf: &[u8]) -> usize
453where
454 A: Allocator,
455{
456 debug_assert!(vec.capacity() >= pos + buf.len());
457 vec.as_mut_ptr().add(pos).copy_from(src:buf.as_ptr(), count:buf.len());
458 pos + buf.len()
459}
460
461/// Resizing write implementation for [`Cursor`]
462///
463/// Cursor is allowed to have a pre-allocated and initialised
464/// vector body, but with a position of 0. This means the [`Write`]
465/// will overwrite the contents of the vec.
466///
467/// This also allows for the vec body to be empty, but with a position of N.
468/// This means that [`Write`] will pad the vec with 0 initially,
469/// before writing anything from that point
470fn vec_write<A>(pos_mut: &mut u64, vec: &mut Vec<u8, A>, buf: &[u8]) -> io::Result<usize>
471where
472 A: Allocator,
473{
474 let buf_len: usize = buf.len();
475 let mut pos: usize = reserve_and_pad(pos_mut, vec, buf_len)?;
476
477 // Write the buf then progress the vec forward if necessary
478 // Safety: we have ensured that the capacity is available
479 // and that all bytes get written up to pos
480 unsafe {
481 pos = vec_write_unchecked(pos, vec, buf);
482 if pos > vec.len() {
483 vec.set_len(new_len:pos);
484 }
485 };
486
487 // Bump us forward
488 *pos_mut += buf_len as u64;
489 Ok(buf_len)
490}
491
492/// Resizing write_vectored implementation for [`Cursor`]
493///
494/// Cursor is allowed to have a pre-allocated and initialised
495/// vector body, but with a position of 0. This means the [`Write`]
496/// will overwrite the contents of the vec.
497///
498/// This also allows for the vec body to be empty, but with a position of N.
499/// This means that [`Write`] will pad the vec with 0 initially,
500/// before writing anything from that point
501fn vec_write_vectored<A>(
502 pos_mut: &mut u64,
503 vec: &mut Vec<u8, A>,
504 bufs: &[IoSlice<'_>],
505) -> io::Result<usize>
506where
507 A: Allocator,
508{
509 // For safety reasons, we don't want this sum to overflow ever.
510 // If this saturates, the reserve should panic to avoid any unsound writing.
511 let buf_len: usize = bufs.iter().fold(init:0usize, |a: usize, b: &IoSlice<'_>| a.saturating_add(b.len()));
512 let mut pos: usize = reserve_and_pad(pos_mut, vec, buf_len)?;
513
514 // Write the buf then progress the vec forward if necessary
515 // Safety: we have ensured that the capacity is available
516 // and that all bytes get written up to the last pos
517 unsafe {
518 for buf: &IoSlice<'_> in bufs {
519 pos = vec_write_unchecked(pos, vec, buf);
520 }
521 if pos > vec.len() {
522 vec.set_len(new_len:pos);
523 }
524 }
525
526 // Bump us forward
527 *pos_mut += buf_len as u64;
528 Ok(buf_len)
529}
530
531#[stable(feature = "rust1", since = "1.0.0")]
532impl Write for Cursor<&mut [u8]> {
533 #[inline]
534 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
535 slice_write(&mut self.pos, self.inner, buf)
536 }
537
538 #[inline]
539 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
540 slice_write_vectored(&mut self.pos, self.inner, bufs)
541 }
542
543 #[inline]
544 fn is_write_vectored(&self) -> bool {
545 true
546 }
547
548 #[inline]
549 fn flush(&mut self) -> io::Result<()> {
550 Ok(())
551 }
552}
553
554#[stable(feature = "cursor_mut_vec", since = "1.25.0")]
555impl<A> Write for Cursor<&mut Vec<u8, A>>
556where
557 A: Allocator,
558{
559 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
560 vec_write(&mut self.pos, self.inner, buf)
561 }
562
563 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
564 vec_write_vectored(&mut self.pos, self.inner, bufs)
565 }
566
567 #[inline]
568 fn is_write_vectored(&self) -> bool {
569 true
570 }
571
572 #[inline]
573 fn flush(&mut self) -> io::Result<()> {
574 Ok(())
575 }
576}
577
578#[stable(feature = "rust1", since = "1.0.0")]
579impl<A> Write for Cursor<Vec<u8, A>>
580where
581 A: Allocator,
582{
583 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
584 vec_write(&mut self.pos, &mut self.inner, buf)
585 }
586
587 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
588 vec_write_vectored(&mut self.pos, &mut self.inner, bufs)
589 }
590
591 #[inline]
592 fn is_write_vectored(&self) -> bool {
593 true
594 }
595
596 #[inline]
597 fn flush(&mut self) -> io::Result<()> {
598 Ok(())
599 }
600}
601
602#[stable(feature = "cursor_box_slice", since = "1.5.0")]
603impl<A> Write for Cursor<Box<[u8], A>>
604where
605 A: Allocator,
606{
607 #[inline]
608 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
609 slice_write(&mut self.pos, &mut self.inner, buf)
610 }
611
612 #[inline]
613 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
614 slice_write_vectored(&mut self.pos, &mut self.inner, bufs)
615 }
616
617 #[inline]
618 fn is_write_vectored(&self) -> bool {
619 true
620 }
621
622 #[inline]
623 fn flush(&mut self) -> io::Result<()> {
624 Ok(())
625 }
626}
627
628#[stable(feature = "cursor_array", since = "1.61.0")]
629impl<const N: usize> Write for Cursor<[u8; N]> {
630 #[inline]
631 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
632 slice_write(&mut self.pos, &mut self.inner, buf)
633 }
634
635 #[inline]
636 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
637 slice_write_vectored(&mut self.pos, &mut self.inner, bufs)
638 }
639
640 #[inline]
641 fn is_write_vectored(&self) -> bool {
642 true
643 }
644
645 #[inline]
646 fn flush(&mut self) -> io::Result<()> {
647 Ok(())
648 }
649}
650