async_std/io/write/
mod.rs

1mod flush;
2mod write;
3mod write_all;
4mod write_fmt;
5mod write_vectored;
6
7use flush::FlushFuture;
8use write::WriteFuture;
9use write_all::WriteAllFuture;
10use write_fmt::WriteFmtFuture;
11use write_vectored::WriteVectoredFuture;
12
13use crate::io::{self, IoSlice};
14
15extension_trait! {
16    use std::pin::Pin;
17    use std::ops::{Deref, DerefMut};
18
19    use crate::task::{Context, Poll};
20
21    #[doc = r#"
22        Allows writing to a byte stream.
23
24        This trait is a re-export of [`futures::io::AsyncWrite`] and is an async version of
25        [`std::io::Write`].
26
27        Methods other than [`poll_write`], [`poll_write_vectored`], [`poll_flush`], and
28        [`poll_close`] do not really exist in the trait itself, but they become available when
29        [`WriteExt`] from the [prelude] is imported:
30
31        ```
32        # #[allow(unused_imports)]
33        use async_std::prelude::*;
34        ```
35
36        [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
37        [`futures::io::AsyncWrite`]:
38        https://docs.rs/futures/0.3/futures/io/trait.AsyncWrite.html
39        [`poll_write`]: #tymethod.poll_write
40        [`poll_write_vectored`]: #method.poll_write_vectored
41        [`poll_flush`]: #tymethod.poll_flush
42        [`poll_close`]: #tymethod.poll_close
43        [`WriteExt`]: ../io/prelude/trait.WriteExt.html
44        [prelude]: ../prelude/index.html
45    "#]
46    pub trait Write {
47        #[doc = r#"
48            Attempt to write bytes from `buf` into the object.
49        "#]
50        fn poll_write(
51            self: Pin<&mut Self>,
52            cx: &mut Context<'_>,
53            buf: &[u8],
54        ) -> Poll<io::Result<usize>>;
55
56        #[doc = r#"
57            Attempt to write bytes from `bufs` into the object using vectored IO operations.
58        "#]
59        fn poll_write_vectored(
60            self: Pin<&mut Self>,
61            cx: &mut Context<'_>,
62            bufs: &[IoSlice<'_>]
63        ) -> Poll<io::Result<usize>> {
64            unreachable!("this impl only appears in the rendered docs")
65        }
66
67        #[doc = r#"
68            Attempt to flush the object, ensuring that any buffered data reach
69            their destination.
70        "#]
71        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
72
73        #[doc = r#"
74            Attempt to close the object.
75        "#]
76        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
77    }
78
79    #[doc = r#"
80        Extension methods for [`Write`].
81
82        [`Write`]: ../trait.Write.html
83    "#]
84    pub trait WriteExt: futures_io::AsyncWrite {
85        #[doc = r#"
86            Writes some bytes into the byte stream.
87
88            Returns the number of bytes written from the start of the buffer.
89
90            If the return value is `Ok(n)` then it must be guaranteed that
91            `0 <= n <= buf.len()`. A return value of `0` typically means that the underlying
92            object is no longer able to accept bytes and will likely not be able to in the
93            future as well, or that the buffer provided is empty.
94
95            # Examples
96
97            ```no_run
98            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
99            #
100            use async_std::fs::File;
101            use async_std::prelude::*;
102
103            let mut file = File::create("a.txt").await?;
104
105            let n = file.write(b"hello world").await?;
106            #
107            # Ok(()) }) }
108            ```
109        "#]
110        fn write<'a>(
111            &'a mut self,
112            buf: &'a [u8],
113        ) -> impl Future<Output = io::Result<usize>> + 'a [WriteFuture<'a, Self>]
114        where
115            Self: Unpin,
116        {
117            WriteFuture { writer: self, buf }
118        }
119
120        #[doc = r#"
121            Flushes the stream to ensure that all buffered contents reach their destination.
122
123            # Examples
124
125            ```no_run
126            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
127            #
128            use async_std::fs::File;
129            use async_std::prelude::*;
130
131            let mut file = File::create("a.txt").await?;
132
133            file.write_all(b"hello world").await?;
134            file.flush().await?;
135            #
136            # Ok(()) }) }
137            ```
138        "#]
139        fn flush(&mut self) -> impl Future<Output = io::Result<()>> + '_ [FlushFuture<'_, Self>]
140        where
141            Self: Unpin,
142        {
143            FlushFuture { writer: self }
144        }
145
146        #[doc = r#"
147            Like [`write`], except that it writes from a slice of buffers.
148
149            Data is copied from each buffer in order, with the final buffer read from possibly
150            being only partially consumed. This method must behave as a call to [`write`] with
151            the buffers concatenated would.
152
153            The default implementation calls [`write`] with either the first nonempty buffer
154            provided, or an empty one if none exists.
155
156            [`write`]: #tymethod.write
157        "#]
158        fn write_vectored<'a>(
159            &'a mut self,
160            bufs: &'a [IoSlice<'a>],
161        ) -> impl Future<Output = io::Result<usize>> + 'a [WriteVectoredFuture<'a, Self>]
162        where
163            Self: Unpin,
164        {
165            WriteVectoredFuture { writer: self, bufs }
166        }
167
168        #[doc = r#"
169            Writes an entire buffer into the byte stream.
170
171            This method will continuously call [`write`] until there is no more data to be
172            written or an error is returned. This method will not return until the entire
173            buffer has been successfully written or such an error occurs.
174
175            [`write`]: #tymethod.write
176
177            # Examples
178
179            ```no_run
180            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
181            #
182            use async_std::fs::File;
183            use async_std::prelude::*;
184
185            let mut file = File::create("a.txt").await?;
186
187            file.write_all(b"hello world").await?;
188            #
189            # Ok(()) }) }
190            ```
191
192            [`write`]: #tymethod.write
193        "#]
194        fn write_all<'a>(
195            &'a mut self,
196            buf: &'a [u8],
197        ) -> impl Future<Output = io::Result<()>> + 'a [WriteAllFuture<'a, Self>]
198        where
199            Self: Unpin,
200        {
201            WriteAllFuture { writer: self, buf }
202        }
203
204        #[doc = r#"
205            Writes a formatted string into this writer, returning any error encountered.
206
207            This method will continuously call [`write`] until there is no more data to be
208            written or an error is returned. This future will not resolve until the entire
209            buffer has been successfully written or such an error occurs.
210
211            [`write`]: #tymethod.write
212
213            # Examples
214
215            ```no_run
216            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
217            #
218            use async_std::io::prelude::*;
219            use async_std::fs::File;
220
221            let mut buffer = File::create("foo.txt").await?;
222
223            // this call
224            write!(buffer, "{:.*}", 2, 1.234567).await?;
225            // turns into this:
226            buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)).await?;
227            #
228            # Ok(()) }) }
229            ```
230        "#]
231        fn write_fmt<'a>(
232            &'a mut self,
233            fmt: std::fmt::Arguments<'_>,
234        ) -> impl Future<Output = io::Result<()>> + 'a [WriteFmtFuture<'a, Self>]
235        where
236            Self: Unpin,
237        {
238            // In order to not have to implement an async version of `fmt` including private types
239            // and all, we convert `Arguments` to a `Result<Vec<u8>>` and pass that to the Future.
240            // Doing an owned conversion saves us from juggling references.
241            let mut string = String::new();
242            let res = std::fmt::write(&mut string, fmt)
243                .map(|_| string.into_bytes())
244                .map_err(|_| io::Error::new(io::ErrorKind::Other, "formatter error"));
245            WriteFmtFuture { writer: self, res: Some(res), buffer: None, amt: 0 }
246        }
247    }
248
249    impl<T: Write + Unpin + ?Sized> Write for Box<T> {
250        fn poll_write(
251            self: Pin<&mut Self>,
252            cx: &mut Context<'_>,
253            buf: &[u8],
254        ) -> Poll<io::Result<usize>> {
255            unreachable!("this impl only appears in the rendered docs")
256        }
257
258        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
259            unreachable!("this impl only appears in the rendered docs")
260        }
261
262        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
263            unreachable!("this impl only appears in the rendered docs")
264        }
265    }
266
267    impl<T: Write + Unpin + ?Sized> Write for &mut T {
268        fn poll_write(
269            self: Pin<&mut Self>,
270            cx: &mut Context<'_>,
271            buf: &[u8],
272        ) -> Poll<io::Result<usize>> {
273            unreachable!("this impl only appears in the rendered docs")
274        }
275
276        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
277            unreachable!("this impl only appears in the rendered docs")
278        }
279
280        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
281            unreachable!("this impl only appears in the rendered docs")
282        }
283    }
284
285    impl<P> Write for Pin<P>
286    where
287        P: DerefMut + Unpin,
288        <P as Deref>::Target: Write,
289    {
290        fn poll_write(
291            self: Pin<&mut Self>,
292            cx: &mut Context<'_>,
293            buf: &[u8],
294        ) -> Poll<io::Result<usize>> {
295            unreachable!("this impl only appears in the rendered docs")
296        }
297
298        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
299            unreachable!("this impl only appears in the rendered docs")
300        }
301
302        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
303            unreachable!("this impl only appears in the rendered docs")
304        }
305    }
306
307    impl Write for Vec<u8> {
308        fn poll_write(
309            self: Pin<&mut Self>,
310            cx: &mut Context<'_>,
311            buf: &[u8],
312        ) -> Poll<io::Result<usize>> {
313            unreachable!("this impl only appears in the rendered docs")
314        }
315
316        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
317            unreachable!("this impl only appears in the rendered docs")
318        }
319
320        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
321            unreachable!("this impl only appears in the rendered docs")
322        }
323    }
324}