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