futures_util/io/cursor.rs
1use futures_core::task::{Context, Poll};
2use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, IoSliceMut, SeekFrom};
3use std::boxed::Box;
4use std::io;
5use std::pin::Pin;
6use std::vec::Vec;
7
8/// A `Cursor` wraps an in-memory buffer and provides it with a
9/// [`AsyncSeek`] implementation.
10///
11/// `Cursor`s are used with in-memory buffers, anything implementing
12/// `AsRef<[u8]>`, to allow them to implement [`AsyncRead`] and/or [`AsyncWrite`],
13/// allowing these buffers to be used anywhere you might use a reader or writer
14/// that does actual I/O.
15///
16/// This library implements some I/O traits on various types which
17/// are commonly used as a buffer, like `Cursor<`[`Vec`]`<u8>>` and
18/// `Cursor<`[`&[u8]`][bytes]`>`.
19///
20/// [`AsyncSeek`]: trait.AsyncSeek.html
21/// [`AsyncRead`]: trait.AsyncRead.html
22/// [`AsyncWrite`]: trait.AsyncWrite.html
23/// [bytes]: https://doc.rust-lang.org/std/primitive.slice.html
24#[derive(Clone, Debug, Default)]
25pub struct Cursor<T> {
26 inner: io::Cursor<T>,
27}
28
29impl<T> Cursor<T> {
30 /// Creates a new cursor wrapping the provided underlying in-memory buffer.
31 ///
32 /// Cursor initial position is `0` even if underlying buffer (e.g., `Vec`)
33 /// is not empty. So writing to cursor starts with overwriting `Vec`
34 /// content, not with appending to it.
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use futures::io::Cursor;
40 ///
41 /// let buff = Cursor::new(Vec::new());
42 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
43 /// # force_inference(&buff);
44 /// ```
45 pub fn new(inner: T) -> Self {
46 Self { inner: io::Cursor::new(inner) }
47 }
48
49 /// Consumes this cursor, returning the underlying value.
50 ///
51 /// # Examples
52 ///
53 /// ```
54 /// use futures::io::Cursor;
55 ///
56 /// let buff = Cursor::new(Vec::new());
57 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
58 /// # force_inference(&buff);
59 ///
60 /// let vec = buff.into_inner();
61 /// ```
62 pub fn into_inner(self) -> T {
63 self.inner.into_inner()
64 }
65
66 /// Gets a reference to the underlying value in this cursor.
67 ///
68 /// # Examples
69 ///
70 /// ```
71 /// use futures::io::Cursor;
72 ///
73 /// let buff = Cursor::new(Vec::new());
74 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
75 /// # force_inference(&buff);
76 ///
77 /// let reference = buff.get_ref();
78 /// ```
79 pub fn get_ref(&self) -> &T {
80 self.inner.get_ref()
81 }
82
83 /// Gets a mutable reference to the underlying value in this cursor.
84 ///
85 /// Care should be taken to avoid modifying the internal I/O state of the
86 /// underlying value as it may corrupt this cursor's position.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// use futures::io::Cursor;
92 ///
93 /// let mut buff = Cursor::new(Vec::new());
94 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
95 /// # force_inference(&buff);
96 ///
97 /// let reference = buff.get_mut();
98 /// ```
99 pub fn get_mut(&mut self) -> &mut T {
100 self.inner.get_mut()
101 }
102
103 /// Returns the current position of this cursor.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// # futures::executor::block_on(async {
109 /// use futures::io::{AsyncSeekExt, Cursor, SeekFrom};
110 ///
111 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
112 ///
113 /// assert_eq!(buff.position(), 0);
114 ///
115 /// buff.seek(SeekFrom::Current(2)).await?;
116 /// assert_eq!(buff.position(), 2);
117 ///
118 /// buff.seek(SeekFrom::Current(-1)).await?;
119 /// assert_eq!(buff.position(), 1);
120 /// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
121 /// ```
122 pub fn position(&self) -> u64 {
123 self.inner.position()
124 }
125
126 /// Sets the position of this cursor.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use futures::io::Cursor;
132 ///
133 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
134 ///
135 /// assert_eq!(buff.position(), 0);
136 ///
137 /// buff.set_position(2);
138 /// assert_eq!(buff.position(), 2);
139 ///
140 /// buff.set_position(4);
141 /// assert_eq!(buff.position(), 4);
142 /// ```
143 pub fn set_position(&mut self, pos: u64) {
144 self.inner.set_position(pos)
145 }
146}
147
148impl<T> AsyncSeek for Cursor<T>
149where
150 T: AsRef<[u8]> + Unpin,
151{
152 fn poll_seek(
153 mut self: Pin<&mut Self>,
154 _: &mut Context<'_>,
155 pos: SeekFrom,
156 ) -> Poll<io::Result<u64>> {
157 Poll::Ready(io::Seek::seek(&mut self.inner, pos))
158 }
159}
160
161impl<T: AsRef<[u8]> + Unpin> AsyncRead for Cursor<T> {
162 fn poll_read(
163 mut self: Pin<&mut Self>,
164 _cx: &mut Context<'_>,
165 buf: &mut [u8],
166 ) -> Poll<io::Result<usize>> {
167 Poll::Ready(io::Read::read(&mut self.inner, buf))
168 }
169
170 fn poll_read_vectored(
171 mut self: Pin<&mut Self>,
172 _: &mut Context<'_>,
173 bufs: &mut [IoSliceMut<'_>],
174 ) -> Poll<io::Result<usize>> {
175 Poll::Ready(io::Read::read_vectored(&mut self.inner, bufs))
176 }
177}
178
179impl<T> AsyncBufRead for Cursor<T>
180where
181 T: AsRef<[u8]> + Unpin,
182{
183 fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
184 Poll::Ready(io::BufRead::fill_buf(&mut self.get_mut().inner))
185 }
186
187 fn consume(mut self: Pin<&mut Self>, amt: usize) {
188 io::BufRead::consume(&mut self.inner, amt)
189 }
190}
191
192macro_rules! delegate_async_write_to_stdio {
193 () => {
194 fn poll_write(
195 mut self: Pin<&mut Self>,
196 _: &mut Context<'_>,
197 buf: &[u8],
198 ) -> Poll<io::Result<usize>> {
199 Poll::Ready(io::Write::write(&mut self.inner, buf))
200 }
201
202 fn poll_write_vectored(
203 mut self: Pin<&mut Self>,
204 _: &mut Context<'_>,
205 bufs: &[IoSlice<'_>],
206 ) -> Poll<io::Result<usize>> {
207 Poll::Ready(io::Write::write_vectored(&mut self.inner, bufs))
208 }
209
210 fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
211 Poll::Ready(io::Write::flush(&mut self.inner))
212 }
213
214 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
215 self.poll_flush(cx)
216 }
217 };
218}
219
220impl AsyncWrite for Cursor<&mut [u8]> {
221 delegate_async_write_to_stdio!();
222}
223
224impl AsyncWrite for Cursor<&mut Vec<u8>> {
225 delegate_async_write_to_stdio!();
226}
227
228impl AsyncWrite for Cursor<Vec<u8>> {
229 delegate_async_write_to_stdio!();
230}
231
232impl AsyncWrite for Cursor<Box<[u8]>> {
233 delegate_async_write_to_stdio!();
234}